agentic-qe 3.9.0 → 3.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (416) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +43 -0
  3. package/dist/audit/witness-chain.d.ts +1 -1
  4. package/dist/cli/bundle.js +8 -8
  5. package/dist/cli/chunks/adapter-53WBPKXU.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-PQYB7VRU.js → agent-booster-wasm-AKAOHSCX.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-QDAB5NQS.js → agent-handler-MTGPOUVP.js} +2 -2
  8. package/dist/cli/chunks/agent-memory-branch-UFPKWUFK.js +2 -0
  9. package/dist/cli/chunks/aqe-learning-engine-MV7NGY24.js +2 -0
  10. package/dist/cli/chunks/{audit-S7JUYYVP.js → audit-VBEZHNHO.js} +2 -2
  11. package/dist/cli/chunks/base-DZVGMQN2.js +2 -0
  12. package/dist/cli/chunks/better-sqlite3-IRPHIXRU.js +2 -0
  13. package/dist/cli/chunks/brain-handler-7EO3FFRZ.js +68 -0
  14. package/dist/cli/chunks/{branch-enumerator-XK4V5W7L.js → branch-enumerator-MZRGP35N.js} +2 -2
  15. package/dist/cli/chunks/{browser-PALA5PL3.js → browser-VSIWQE7J.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-3J5YNMEI.js +2 -0
  17. package/dist/cli/chunks/chunk-25LFUL2K.js +79 -0
  18. package/dist/cli/chunks/{chunk-LHJQD2VU.js → chunk-2EC5Z2J4.js} +68 -68
  19. package/dist/cli/chunks/{chunk-4YOMLWEK.js → chunk-2VVV73PW.js} +1 -1
  20. package/dist/cli/chunks/{chunk-BPWXXEH2.js → chunk-2WBCYSUN.js} +128 -128
  21. package/dist/cli/chunks/{chunk-X3KI6JOY.js → chunk-2Z2TFEOL.js} +2 -2
  22. package/dist/cli/chunks/chunk-34U7JDCN.js +2 -0
  23. package/dist/cli/chunks/{chunk-24FKIJNC.js → chunk-3GZKAORV.js} +2 -2
  24. package/dist/cli/chunks/{chunk-72WOAVK6.js → chunk-4D2ZG2QO.js} +1 -1
  25. package/dist/cli/chunks/{chunk-B36CDR4U.js → chunk-4DAOZQ3V.js} +2 -2
  26. package/dist/cli/chunks/{chunk-CL6POIX4.js → chunk-4FMHBBG5.js} +1 -1
  27. package/dist/cli/chunks/{chunk-BXAXGEFC.js → chunk-4FT3PND7.js} +5 -5
  28. package/dist/cli/chunks/{chunk-IGJPMN4I.js → chunk-4LA7IW3V.js} +1 -1
  29. package/dist/cli/chunks/{chunk-JRYGQO2W.js → chunk-4PKXIBX2.js} +1 -1
  30. package/dist/cli/chunks/{chunk-YPFOCNOE.js → chunk-4UH25U4O.js} +1 -1
  31. package/dist/cli/chunks/{chunk-U5RN7YQW.js → chunk-4Z27TRQF.js} +2 -2
  32. package/dist/cli/chunks/{chunk-YW2THB5Q.js → chunk-563PJBDM.js} +2 -2
  33. package/dist/cli/chunks/{chunk-BDIEMZ22.js → chunk-56IWS2KY.js} +2 -2
  34. package/dist/cli/chunks/chunk-5AUKULWO.js +2 -0
  35. package/dist/cli/chunks/{chunk-VSVXUTJN.js → chunk-5L6AU3QK.js} +2 -2
  36. package/dist/cli/chunks/{chunk-RTGGL7D7.js → chunk-5RL66XSH.js} +2 -2
  37. package/dist/cli/chunks/{chunk-YANUP2RO.js → chunk-65M7C6SH.js} +1 -1
  38. package/dist/cli/chunks/{chunk-ESVQ6MEB.js → chunk-6SOJVEU7.js} +2 -2
  39. package/dist/cli/chunks/{chunk-UFUVUO3J.js → chunk-727BDQ3K.js} +2 -2
  40. package/dist/cli/chunks/{chunk-TLHP5EII.js → chunk-7NOIIC7G.js} +1 -1
  41. package/dist/cli/chunks/{chunk-N4TL73TH.js → chunk-7SLN2JGP.js} +8 -8
  42. package/dist/cli/chunks/{chunk-NZ2VCPN4.js → chunk-AA33R5U4.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Y7BHKZFJ.js → chunk-AKSJQ6B3.js} +2 -2
  44. package/dist/cli/chunks/{chunk-3ZOONQG6.js → chunk-BIVIPF4O.js} +1 -1
  45. package/dist/cli/chunks/{chunk-VOS4NQSF.js → chunk-BKCTNRC5.js} +2 -2
  46. package/dist/cli/chunks/{chunk-B6LLWYQ6.js → chunk-BOH22AKC.js} +2 -2
  47. package/dist/cli/chunks/{chunk-OI5NGQO2.js → chunk-BY47GV4T.js} +2 -2
  48. package/dist/cli/chunks/chunk-CCYMJKWX.js +2 -0
  49. package/dist/cli/chunks/chunk-CL3K5EJK.js +2 -0
  50. package/dist/cli/chunks/{chunk-GPQ57KA4.js → chunk-CQBSGYRA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-MZOFWJTM.js → chunk-CQP7ZFME.js} +2 -2
  52. package/dist/cli/chunks/chunk-DBE34QES.js +2 -0
  53. package/dist/cli/chunks/chunk-DHE66JRR.js +12 -0
  54. package/dist/cli/chunks/{chunk-2BZFNEN2.js → chunk-DNLMZTE2.js} +1 -1
  55. package/dist/cli/chunks/{chunk-XLRQYLWW.js → chunk-DSE57A5N.js} +1 -1
  56. package/dist/cli/chunks/{chunk-SUSEVMZT.js → chunk-E25S5E2D.js} +1 -1
  57. package/dist/cli/chunks/{chunk-FEKY7T6Q.js → chunk-FAXVVLPL.js} +2 -2
  58. package/dist/cli/chunks/chunk-FRJLP7IB.js +2 -0
  59. package/dist/cli/chunks/{chunk-CS2KS7LP.js → chunk-FUIHWBVF.js} +1 -1
  60. package/dist/cli/chunks/{chunk-LNQIY6BP.js → chunk-GCMVJS5X.js} +2 -2
  61. package/dist/cli/chunks/{chunk-XT2V2322.js → chunk-GITD7SRQ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-JJO7Y4H3.js → chunk-GK72GUHA.js} +3 -3
  63. package/dist/cli/chunks/{chunk-6EOS7KX2.js → chunk-GPLERTZU.js} +2 -2
  64. package/dist/cli/chunks/{chunk-2E5NQNSU.js → chunk-HW4ISY5B.js} +11 -11
  65. package/dist/cli/chunks/{chunk-HRO6OZQD.js → chunk-ICDXWIFZ.js} +1 -1
  66. package/dist/cli/chunks/{chunk-3NZLZHJI.js → chunk-J4BS6IWE.js} +1 -1
  67. package/dist/cli/chunks/{chunk-4VUPRTVX.js → chunk-JOVINE23.js} +2 -2
  68. package/dist/cli/chunks/chunk-JV7LX6OT.js +95 -0
  69. package/dist/cli/chunks/{chunk-6SVX4DJC.js → chunk-KBA7FBK3.js} +3 -3
  70. package/dist/cli/chunks/chunk-KDDZYXP4.js +2 -0
  71. package/dist/cli/chunks/{chunk-GAOJV3OX.js → chunk-KNVAAVHH.js} +2 -2
  72. package/dist/cli/chunks/{chunk-CWFB6BSA.js → chunk-KQTJ2YLI.js} +4 -4
  73. package/dist/cli/chunks/{chunk-FGA7VIFR.js → chunk-KTYUCZEM.js} +3 -3
  74. package/dist/cli/chunks/{chunk-RU5WAHB7.js → chunk-KZTO5EVM.js} +2 -2
  75. package/dist/cli/chunks/{chunk-IFNIIK34.js → chunk-KZUJBZ7B.js} +3 -3
  76. package/dist/cli/chunks/{chunk-GKNNSCLC.js → chunk-L5WZUPZF.js} +2 -2
  77. package/dist/cli/chunks/{chunk-MDUHYUHF.js → chunk-L5YEPSDU.js} +2 -2
  78. package/dist/cli/chunks/chunk-LCAA6H4J.js +2 -0
  79. package/dist/cli/chunks/{chunk-XRE2HCWG.js → chunk-LMMEUVE5.js} +1 -1
  80. package/dist/cli/chunks/{chunk-7VDBAVTY.js → chunk-MN742FIH.js} +2 -2
  81. package/dist/cli/chunks/chunk-MY4LMIG7.js +180 -0
  82. package/dist/cli/chunks/{chunk-WGMPEW2T.js → chunk-N3F3CX4V.js} +2 -2
  83. package/dist/cli/chunks/{chunk-YVA65UZL.js → chunk-NJY7ZA77.js} +1 -1
  84. package/dist/cli/chunks/{chunk-3IHG3WOY.js → chunk-NM6TIEJ3.js} +3 -3
  85. package/dist/cli/chunks/{chunk-KP5NUODU.js → chunk-NRCKGXJJ.js} +1 -1
  86. package/dist/cli/chunks/{chunk-3ADGXLTM.js → chunk-PFNFC43Q.js} +1 -1
  87. package/dist/cli/chunks/{chunk-4VBTXZRM.js → chunk-PJFLO37I.js} +2 -2
  88. package/dist/cli/chunks/{chunk-XIBDETCS.js → chunk-PNL5G6TE.js} +2 -2
  89. package/dist/cli/chunks/{chunk-AFLLQ5PP.js → chunk-Q4A72ZTV.js} +2 -2
  90. package/dist/cli/chunks/{chunk-EHDQJQ6Y.js → chunk-QEQTC4WQ.js} +5 -5
  91. package/dist/cli/chunks/{chunk-IAV2JMIX.js → chunk-QIH3E775.js} +2 -2
  92. package/dist/cli/chunks/{chunk-GRUUQAR6.js → chunk-QNBQBSAI.js} +2 -2
  93. package/dist/cli/chunks/{chunk-WIEC7VKK.js → chunk-QODE4LM6.js} +2 -2
  94. package/dist/cli/chunks/{chunk-HY6PMO5W.js → chunk-QPRVX4H2.js} +2 -2
  95. package/dist/cli/chunks/chunk-RC5CPXON.js +2 -0
  96. package/dist/cli/chunks/{chunk-TWUWL5EJ.js → chunk-RITN3XR4.js} +2 -2
  97. package/dist/cli/chunks/{chunk-WBQSXPBI.js → chunk-RJROC5M3.js} +2 -2
  98. package/dist/cli/chunks/chunk-RQGYJK7H.js +2 -0
  99. package/dist/cli/chunks/{chunk-XO6PVK2P.js → chunk-S3RDH5CI.js} +2 -2
  100. package/dist/cli/chunks/{chunk-3IUNFTIF.js → chunk-SCF7NRVE.js} +1 -1
  101. package/dist/cli/chunks/chunk-SDTVHR63.js +2 -0
  102. package/dist/cli/chunks/chunk-SGAW2WLI.js +65 -0
  103. package/dist/cli/chunks/{chunk-N2NS2PHA.js → chunk-SNVM4YJS.js} +2 -2
  104. package/dist/cli/chunks/{chunk-JXM26HEE.js → chunk-SRRFWTNF.js} +2 -2
  105. package/dist/cli/chunks/{chunk-UQHYFOBX.js → chunk-STE42EMB.js} +2 -2
  106. package/dist/cli/chunks/{chunk-WJ3DLOXF.js → chunk-T5GV6UIO.js} +2 -2
  107. package/dist/cli/chunks/{chunk-4YS3IJ45.js → chunk-TKF447CW.js} +1 -1
  108. package/dist/cli/chunks/{chunk-ZAPS3UGQ.js → chunk-TTOE336G.js} +3 -3
  109. package/dist/cli/chunks/{chunk-YAGODYIG.js → chunk-UKDOMLBI.js} +3 -3
  110. package/dist/cli/chunks/{chunk-JBANAPWG.js → chunk-V6XBAZNH.js} +1 -1
  111. package/dist/cli/chunks/{chunk-BULKFVYX.js → chunk-VHVWAXCF.js} +1 -1
  112. package/dist/cli/chunks/{chunk-5SKGFSKD.js → chunk-VL7YOOC2.js} +2 -2
  113. package/dist/cli/chunks/{chunk-AKE543X2.js → chunk-VUAO4VFC.js} +2 -2
  114. package/dist/cli/chunks/{chunk-7R6YMLVS.js → chunk-WG4GHAML.js} +2 -2
  115. package/dist/cli/chunks/{chunk-BTREG4IW.js → chunk-WXWY2GAF.js} +2 -2
  116. package/dist/cli/chunks/chunk-X35GP7TR.js +1 -0
  117. package/dist/cli/chunks/chunk-X6LCMOGC.js +2 -0
  118. package/dist/cli/chunks/{chunk-BGXNSCXX.js → chunk-XFMKJ3UD.js} +1 -1
  119. package/dist/cli/chunks/{chunk-BLBRY5UD.js → chunk-XH53ARZD.js} +2 -2
  120. package/dist/cli/chunks/chunk-XIBVVZGB.js +2 -0
  121. package/dist/cli/chunks/chunk-XYJL6DKI.js +2 -0
  122. package/dist/cli/chunks/{chunk-5T2ZQWKF.js → chunk-Y6O7CDLI.js} +2 -2
  123. package/dist/cli/chunks/{chunk-4I2IOUS4.js → chunk-YXCU4CJX.js} +1 -1
  124. package/dist/cli/chunks/{chunk-YR6ZZGH7.js → chunk-Z2IKNC5M.js} +1 -1
  125. package/dist/cli/chunks/{chunk-OLHKGP35.js → chunk-Z54EO6E6.js} +2 -2
  126. package/dist/cli/chunks/{chunk-ZDATDCYN.js → chunk-Z5HXGVXZ.js} +1 -1
  127. package/dist/cli/chunks/{ci-J374KDLI.js → ci-2BCOBWFG.js} +2 -2
  128. package/dist/cli/chunks/ci-output-FB4OJHAC.js +2 -0
  129. package/dist/cli/chunks/{claude-flow-setup-245JLJCN.js → claude-flow-setup-NEEFZTMB.js} +2 -2
  130. package/dist/cli/chunks/client-EF555KYW.js +2 -0
  131. package/dist/cli/chunks/{cline-installer-LBA2M5N3.js → cline-installer-ODO2PS4K.js} +2 -2
  132. package/dist/cli/chunks/{code-U4N4WONM.js → code-NSOF62VE.js} +2 -2
  133. package/dist/cli/chunks/{code-index-extractor-A57Z6BO4.js → code-index-extractor-YQL5XN52.js} +2 -2
  134. package/dist/cli/chunks/{codex-installer-UXMK2N4T.js → codex-installer-SPEY6VYT.js} +2 -2
  135. package/dist/cli/chunks/{completions-W66BSCOE.js → completions-OWKBUMBE.js} +2 -2
  136. package/dist/cli/chunks/complexity-analyzer-PGTXKP73.js +2 -0
  137. package/dist/cli/chunks/{continuedev-installer-LRFZ2SJM.js → continuedev-installer-KGOXAC7L.js} +2 -2
  138. package/dist/cli/chunks/{copilot-installer-CQ3JYBIB.js → copilot-installer-BF3UA3TG.js} +2 -2
  139. package/dist/cli/chunks/cost-tracker-2HDJ66E2.js +2 -0
  140. package/dist/cli/chunks/{coverage-4PUEQXAY.js → coverage-KPA2PHIN.js} +3 -3
  141. package/dist/cli/chunks/cross-domain-router-GXFNK5TS.js +2 -0
  142. package/dist/cli/chunks/{cursor-installer-JZEDEDHA.js → cursor-installer-7CDZFHTV.js} +2 -2
  143. package/dist/cli/chunks/{daemon-B7TWGHXQ.js → daemon-4BPGCKDJ.js} +3 -3
  144. package/dist/cli/chunks/dag-attention-scheduler-2MAVGSBB.js +2 -0
  145. package/dist/cli/chunks/detect-WRPWTGP5.js +2 -0
  146. package/dist/cli/chunks/{domain-handler-FT5FLZWL.js → domain-handler-JZVSJ7AG.js} +2 -2
  147. package/dist/cli/chunks/domain-transfer-XGIZOR2X.js +2 -0
  148. package/dist/cli/chunks/dream-3IKF5XH4.js +2 -0
  149. package/dist/cli/chunks/esm-node-DHAE52OW.js +2 -0
  150. package/dist/cli/chunks/{eval-GHMPFGWV.js → eval-T7YPAS4G.js} +2 -2
  151. package/dist/cli/chunks/{fast-paths-B3R647KN.js → fast-paths-QECJTKCQ.js} +2 -2
  152. package/dist/cli/chunks/{feature-flags-DWS7ARSX.js → feature-flags-LIFURSFZ.js} +2 -2
  153. package/dist/cli/chunks/feature-flags-R4QZYTIW.js +2 -0
  154. package/dist/cli/chunks/file-discovery-4W3K3W4C.js +2 -0
  155. package/dist/cli/chunks/{fleet-EKOKMOMW.js → fleet-NLLQWCI5.js} +3 -3
  156. package/dist/cli/chunks/gnn-wrapper-XEII72LN.js +2 -0
  157. package/dist/cli/chunks/{heartbeat-handler-MBBS4IBU.js → heartbeat-handler-DJ65RE5D.js} +4 -4
  158. package/dist/cli/chunks/{heartbeat-scheduler-XDGMOT7X.js → heartbeat-scheduler-H664265Q.js} +2 -2
  159. package/dist/cli/chunks/hnsw-adapter-DML5KXQR.js +2 -0
  160. package/dist/cli/chunks/hnsw-index-BUPPGVR6.js +2 -0
  161. package/dist/cli/chunks/hnsw-legacy-bridge-SQIDTWAA.js +2 -0
  162. package/dist/cli/chunks/hnswlib-node-WICYCU5U.js +2 -0
  163. package/dist/cli/chunks/{hooks-L5VLZGEK.js → hooks-GZUHUD63.js} +6 -6
  164. package/dist/cli/chunks/hypergraph-engine-MLCDZ6BL.js +2 -0
  165. package/dist/cli/chunks/{hypergraph-handler-3HDGB5SZ.js → hypergraph-handler-NNDDI4R3.js} +3 -3
  166. package/dist/cli/chunks/impact-analyzer-DPTMJRYS.js +2 -0
  167. package/dist/cli/chunks/{init-handler-JDET6WUN.js → init-handler-IJ6BHE6A.js} +6 -6
  168. package/dist/cli/chunks/init-wizard-35PUDJPW.js +2 -0
  169. package/dist/cli/chunks/kernel-2HZ44ZJ4.js +2 -0
  170. package/dist/cli/chunks/{kilocode-installer-GZZG5AFW.js → kilocode-installer-EPZFFPFE.js} +2 -2
  171. package/dist/cli/chunks/{kiro-installer-IWNY5TKH.js → kiro-installer-5VACG3HU.js} +2 -2
  172. package/dist/cli/chunks/knowledge-graph-JL62G72U.js +2 -0
  173. package/dist/cli/chunks/{learning-722ZNSZ6.js → learning-6FITK6XY.js} +3 -3
  174. package/dist/cli/chunks/{llm-router-DNAV746L.js → llm-router-4DDC6AKJ.js} +2 -2
  175. package/dist/cli/chunks/{load-Y3GCUFM4.js → load-KGDNVUBX.js} +2 -2
  176. package/dist/cli/chunks/load-test-LN245SSD.js +2 -0
  177. package/dist/cli/chunks/{mcp-LKPIBZ3W.js → mcp-4LETGVIV.js} +2 -2
  178. package/dist/cli/chunks/{memory-L57MLFOP.js → memory-II4I4QMO.js} +5 -5
  179. package/dist/cli/chunks/memory-backend-SVM7YRIE.js +2 -0
  180. package/dist/cli/chunks/memory-handlers-TQXTOJGQ.js +2 -0
  181. package/dist/cli/chunks/opencode-installer-EU6JCWBW.js +3 -0
  182. package/dist/cli/chunks/{orchestrator-QHSBB2UC.js → orchestrator-YLMGJVSP.js} +5 -5
  183. package/dist/cli/chunks/{pipeline-D3QER35Z.js → pipeline-MPZJWYKK.js} +2 -2
  184. package/dist/cli/chunks/{platform-T4E7Q3RD.js → platform-YH35ZZFZ.js} +2 -2
  185. package/dist/cli/chunks/{plugin-JHW2YPRC.js → plugin-B7JYZFNQ.js} +2 -2
  186. package/dist/cli/chunks/{prime-radiant-advanced-wasm-G7CFNNQV.js → prime-radiant-advanced-wasm-KTUK6UE2.js} +2 -2
  187. package/dist/cli/chunks/protocol-executor-IEN2XB4L.js +2 -0
  188. package/dist/cli/chunks/{protocol-handler-2BQQ4HDM.js → protocol-handler-3NXMVU34.js} +2 -2
  189. package/dist/cli/chunks/{prove-UQ6JFT73.js → prove-H5LMGSUC.js} +2 -2
  190. package/dist/cli/chunks/qe-reasoning-bank-Q3ZV3JRG.js +2 -0
  191. package/dist/cli/chunks/{quality-JRZYMC77.js → quality-RCWHY6GO.js} +2 -2
  192. package/dist/cli/chunks/queen-coordinator-E6ON3JUR.js +2 -0
  193. package/dist/cli/chunks/real-embeddings-NKH4VURF.js +2 -0
  194. package/dist/cli/chunks/{roocode-installer-F4E2LAYR.js → roocode-installer-SB7QJYM3.js} +2 -2
  195. package/dist/cli/chunks/router-WMC3LZ3C.js +2 -0
  196. package/dist/cli/chunks/routing-feedback-VKCZRCE3.js +2 -0
  197. package/dist/cli/chunks/{routing-handler-VNKFUUGB.js → routing-handler-SY7GKG2W.js} +2 -2
  198. package/dist/cli/chunks/ruvector-commands-HATTO3UQ.js +8 -0
  199. package/dist/cli/chunks/rvf-dual-writer-D57EXQUD.js +2 -0
  200. package/dist/cli/chunks/rvf-migration-adapter-OWDYN6KD.js +2 -0
  201. package/dist/cli/chunks/rvf-migration-coordinator-SIQVJB5S.js +2 -0
  202. package/dist/cli/chunks/rvf-native-adapter-C7NBH5UN.js +2 -0
  203. package/dist/cli/chunks/safe-db-5KLXCNXN.js +2 -0
  204. package/dist/cli/chunks/schedule-HAWWOXWB.js +2 -0
  205. package/dist/cli/chunks/scheduler-HTRDY5BC.js +2 -0
  206. package/dist/cli/chunks/{security-EBEG2OPU.js → security-DS3XLZWN.js} +3 -3
  207. package/dist/cli/chunks/shared-rvf-adapter-6I2Z5UGL.js +2 -0
  208. package/dist/cli/chunks/shared-rvf-dual-writer-YB7AH6XJ.js +2 -0
  209. package/dist/cli/chunks/sqlite-persistence-WNNRGTGG.js +2 -0
  210. package/dist/cli/chunks/{status-handler-VZ32M4G4.js → status-handler-TUYHE4FT.js} +2 -2
  211. package/dist/cli/chunks/{structural-health-K6LRCKV6.js → structural-health-XNGBNRRD.js} +2 -2
  212. package/dist/cli/chunks/{sync-MHSHNLIM.js → sync-K6CIRKBB.js} +2 -2
  213. package/dist/cli/chunks/{task-handler-JNOIBZ2G.js → task-handler-7PJY67DR.js} +2 -2
  214. package/dist/cli/chunks/task-handlers-WB5CDWUR.js +2 -0
  215. package/dist/cli/chunks/{test-DO22BNIL.js → test-WV5ALEBB.js} +4 -4
  216. package/dist/cli/chunks/{test-scheduling-VLRQZEFL.js → test-scheduling-N55ZGGA2.js} +3 -3
  217. package/dist/cli/chunks/token-bootstrap-SINWHAKR.js +2 -0
  218. package/dist/cli/chunks/{token-usage-LG3PXRXH.js → token-usage-R7TGEVGL.js} +2 -2
  219. package/dist/cli/chunks/transformers-6DBLXPV7.js +2 -0
  220. package/dist/cli/chunks/{tree-sitter-wasm-parser-FT2KB66N.js → tree-sitter-wasm-parser-7C7FKMQW.js} +2 -2
  221. package/dist/cli/chunks/types-VNPMOKQT.js +2 -0
  222. package/dist/cli/chunks/unified-memory-72SKVZ7Y.js +2 -0
  223. package/dist/cli/chunks/unified-memory-hnsw-TMN2L77W.js +2 -0
  224. package/dist/cli/chunks/unified-persistence-MDN3SRCR.js +2 -0
  225. package/dist/cli/chunks/{validate-VQCRSVNQ.js → validate-53MNIRAF.js} +2 -2
  226. package/dist/cli/chunks/{validate-swarm-A5DHAWTP.js → validate-swarm-ZY4RGUFO.js} +2 -2
  227. package/dist/cli/chunks/{vibium-RZBSL4EB.js → vibium-PBADBIV6.js} +2 -2
  228. package/dist/cli/chunks/visual-security-TRBCXPIB.js +2 -0
  229. package/dist/cli/chunks/{web-tree-sitter-7C4NXEOF.js → web-tree-sitter-O7VI6RLB.js} +2 -2
  230. package/dist/cli/chunks/{windsurf-installer-ES3KPQG3.js → windsurf-installer-HV3C3TAD.js} +2 -2
  231. package/dist/cli/chunks/witness-chain-4WIMYP4X.js +2 -0
  232. package/dist/cli/chunks/witness-chain-JOI2YYGK.js +2 -0
  233. package/dist/cli/chunks/{workflow-JETHX4ML.js → workflow-5RVAQ4TM.js} +4 -4
  234. package/dist/cli/chunks/workflow-orchestrator-2NQ72S3C.js +2 -0
  235. package/dist/cli/chunks/{wrappers-WP5RH745.js → wrappers-RRHCCA3E.js} +2 -2
  236. package/dist/cli/commands/ruvector-commands.js +14 -2
  237. package/dist/cli/index.js +10 -15
  238. package/dist/coordination/agent-memory-branch.d.ts +117 -0
  239. package/dist/coordination/agent-memory-branch.js +213 -0
  240. package/dist/coordination/agent-teams/mailbox.d.ts +43 -0
  241. package/dist/coordination/agent-teams/mailbox.js +130 -4
  242. package/dist/coordination/handlers/handler-utils.d.ts +1 -0
  243. package/dist/coordination/handlers/handler-utils.js +9 -2
  244. package/dist/coordination/handlers/quality-handlers.js +7 -1
  245. package/dist/domains/contract-testing/coordinator.js +11 -0
  246. package/dist/domains/quality-assessment/coherence/gate-controller.d.ts +20 -1
  247. package/dist/domains/quality-assessment/coherence/gate-controller.js +64 -0
  248. package/dist/domains/quality-assessment/coherence/index.d.ts +3 -3
  249. package/dist/domains/quality-assessment/coherence/index.js +2 -2
  250. package/dist/domains/quality-assessment/coherence/types.d.ts +39 -0
  251. package/dist/domains/quality-assessment/coherence/types.js +11 -0
  252. package/dist/domains/quality-assessment/coordinator.d.ts +14 -0
  253. package/dist/domains/quality-assessment/coordinator.js +92 -0
  254. package/dist/domains/test-execution/coordinator.d.ts +19 -0
  255. package/dist/domains/test-execution/coordinator.js +102 -5
  256. package/dist/domains/test-generation/coordinator.js +11 -0
  257. package/dist/domains/test-generation/interfaces.d.ts +2 -0
  258. package/dist/domains/test-generation/services/test-generator.d.ts +9 -0
  259. package/dist/domains/test-generation/services/test-generator.js +37 -0
  260. package/dist/init/agents-installer.d.ts +5 -3
  261. package/dist/init/agents-installer.js +17 -43
  262. package/dist/init/find-package-root.d.ts +22 -0
  263. package/dist/init/find-package-root.js +46 -0
  264. package/dist/init/n8n-installer.d.ts +4 -2
  265. package/dist/init/n8n-installer.js +23 -23
  266. package/dist/init/opencode-installer.d.ts +0 -5
  267. package/dist/init/opencode-installer.js +12 -39
  268. package/dist/init/skills-installer.d.ts +5 -2
  269. package/dist/init/skills-installer.js +15 -37
  270. package/dist/integrations/embeddings/index/HNSWIndex.d.ts +9 -2
  271. package/dist/integrations/embeddings/index/HNSWIndex.js +110 -35
  272. package/dist/integrations/ruvector/cognitive-routing.d.ts +67 -0
  273. package/dist/integrations/ruvector/cognitive-routing.js +208 -0
  274. package/dist/integrations/ruvector/feature-flags.d.ts +84 -0
  275. package/dist/integrations/ruvector/feature-flags.js +59 -0
  276. package/dist/integrations/ruvector/hdc-fingerprint.d.ts +76 -0
  277. package/dist/integrations/ruvector/hdc-fingerprint.js +217 -0
  278. package/dist/integrations/ruvector/hyperbolic-hnsw.d.ts +59 -0
  279. package/dist/integrations/ruvector/hyperbolic-hnsw.js +194 -0
  280. package/dist/integrations/ruvector/index.d.ts +5 -2
  281. package/dist/integrations/ruvector/index.js +13 -2
  282. package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +24 -0
  283. package/dist/integrations/ruvector/shared-rvf-adapter.js +55 -0
  284. package/dist/integrations/ruvector/shared-rvf-dual-writer.d.ts +6 -0
  285. package/dist/integrations/ruvector/shared-rvf-dual-writer.js +38 -0
  286. package/dist/integrations/ruvector/sona-persistence.d.ts +8 -0
  287. package/dist/integrations/ruvector/sona-persistence.js +10 -0
  288. package/dist/integrations/ruvector/vector-delta-tracker.d.ts +96 -0
  289. package/dist/integrations/ruvector/vector-delta-tracker.js +226 -0
  290. package/dist/kernel/agent-coordinator.d.ts +75 -1
  291. package/dist/kernel/agent-coordinator.js +250 -1
  292. package/dist/kernel/hnsw-legacy-bridge.d.ts +38 -0
  293. package/dist/kernel/hnsw-legacy-bridge.js +88 -0
  294. package/dist/kernel/hnsw-shadow-validator.d.ts +91 -0
  295. package/dist/kernel/hnsw-shadow-validator.js +139 -0
  296. package/dist/kernel/index.d.ts +1 -1
  297. package/dist/kernel/index.js +1 -1
  298. package/dist/kernel/interfaces.d.ts +39 -0
  299. package/dist/kernel/kernel.d.ts +23 -0
  300. package/dist/kernel/kernel.js +106 -1
  301. package/dist/kernel/unified-memory.d.ts +1 -1
  302. package/dist/kernel/unified-memory.js +7 -3
  303. package/dist/learning/aqe-learning-engine.d.ts +65 -0
  304. package/dist/learning/aqe-learning-engine.js +134 -0
  305. package/dist/learning/dream/dream-engine.d.ts +6 -1
  306. package/dist/learning/dream/dream-engine.js +37 -2
  307. package/dist/learning/dream/dream-scheduler.d.ts +25 -0
  308. package/dist/learning/dream/dream-scheduler.js +120 -0
  309. package/dist/learning/dream/rvcow-branch-manager.d.ts +6 -3
  310. package/dist/learning/dream/rvcow-branch-manager.js +60 -5
  311. package/dist/learning/experience-capture.d.ts +3 -3
  312. package/dist/learning/hyperbolic-pattern-index.d.ts +82 -0
  313. package/dist/learning/hyperbolic-pattern-index.js +142 -0
  314. package/dist/learning/index.d.ts +3 -3
  315. package/dist/learning/index.js +1 -1
  316. package/dist/learning/metrics-tracker.d.ts +44 -0
  317. package/dist/learning/metrics-tracker.js +37 -0
  318. package/dist/learning/pattern-promotion.d.ts +3 -3
  319. package/dist/learning/pattern-store.d.ts +45 -2
  320. package/dist/learning/pattern-store.js +239 -4
  321. package/dist/learning/qe-patterns.d.ts +1 -1
  322. package/dist/learning/qe-reasoning-bank.js +1 -1
  323. package/dist/learning/rvf-pattern-migration.d.ts +50 -0
  324. package/dist/learning/rvf-pattern-migration.js +106 -0
  325. package/dist/learning/rvf-pattern-store.d.ts +69 -0
  326. package/dist/learning/rvf-pattern-store.js +449 -0
  327. package/dist/mcp/bundle.js +1894 -1804
  328. package/dist/mcp/handlers/index.d.ts +1 -0
  329. package/dist/mcp/handlers/index.js +2 -0
  330. package/dist/mcp/handlers/migration-handlers.d.ts +52 -0
  331. package/dist/mcp/handlers/migration-handlers.js +85 -0
  332. package/dist/mcp/protocol-server.d.ts +1 -0
  333. package/dist/mcp/protocol-server.js +63 -2
  334. package/dist/mcp/types.d.ts +1 -1
  335. package/dist/optimization/early-exit-token-optimizer.d.ts +7 -7
  336. package/dist/optimization/early-exit-token-optimizer.js +3 -3
  337. package/dist/persistence/rvf-consistency-validator.d.ts +85 -0
  338. package/dist/persistence/rvf-consistency-validator.js +182 -0
  339. package/dist/persistence/rvf-migration-adapter.d.ts +125 -0
  340. package/dist/persistence/rvf-migration-adapter.js +303 -0
  341. package/dist/persistence/rvf-migration-coordinator.d.ts +115 -0
  342. package/dist/persistence/rvf-migration-coordinator.js +224 -0
  343. package/dist/persistence/rvf-stage-gate.d.ts +70 -0
  344. package/dist/persistence/rvf-stage-gate.js +163 -0
  345. package/package.json +10 -10
  346. package/dist/cli/chunks/adapter-WBR5NXS3.js +0 -2
  347. package/dist/cli/chunks/aqe-learning-engine-TK4JQCGT.js +0 -2
  348. package/dist/cli/chunks/base-2WXOSMBQ.js +0 -2
  349. package/dist/cli/chunks/better-sqlite3-7KY2RDXO.js +0 -2
  350. package/dist/cli/chunks/brain-handler-PPEGDCN4.js +0 -68
  351. package/dist/cli/chunks/browser-workflow-42F7GK5T.js +0 -2
  352. package/dist/cli/chunks/chunk-263XS447.js +0 -2
  353. package/dist/cli/chunks/chunk-2I7J3O6V.js +0 -2
  354. package/dist/cli/chunks/chunk-3JPRUND5.js +0 -2
  355. package/dist/cli/chunks/chunk-3THRQEZ2.js +0 -95
  356. package/dist/cli/chunks/chunk-4B6NCELM.js +0 -2
  357. package/dist/cli/chunks/chunk-62ADTHV7.js +0 -2
  358. package/dist/cli/chunks/chunk-BR26T7ZS.js +0 -180
  359. package/dist/cli/chunks/chunk-DRT3WKQW.js +0 -2
  360. package/dist/cli/chunks/chunk-FIA6X7UL.js +0 -2
  361. package/dist/cli/chunks/chunk-J3KWWR6Z.js +0 -1
  362. package/dist/cli/chunks/chunk-JZSDOIXA.js +0 -2
  363. package/dist/cli/chunks/chunk-MV6CMOJQ.js +0 -65
  364. package/dist/cli/chunks/chunk-N5UXCLFI.js +0 -2
  365. package/dist/cli/chunks/chunk-OF4D7MYI.js +0 -2
  366. package/dist/cli/chunks/chunk-QOVHWZEP.js +0 -1
  367. package/dist/cli/chunks/chunk-RFSN6IDA.js +0 -79
  368. package/dist/cli/chunks/chunk-X5IJGWYG.js +0 -2
  369. package/dist/cli/chunks/ci-output-7JN7F6CI.js +0 -2
  370. package/dist/cli/chunks/client-MCSNSH2C.js +0 -2
  371. package/dist/cli/chunks/complexity-analyzer-AB4OZARV.js +0 -2
  372. package/dist/cli/chunks/cost-tracker-4F723RB6.js +0 -2
  373. package/dist/cli/chunks/cross-domain-router-OWR5IJ5G.js +0 -2
  374. package/dist/cli/chunks/dag-attention-scheduler-JWO6XI6A.js +0 -2
  375. package/dist/cli/chunks/detect-L6ZZHUSX.js +0 -2
  376. package/dist/cli/chunks/domain-transfer-5Y4FGJAJ.js +0 -2
  377. package/dist/cli/chunks/dream-4TDBIYED.js +0 -2
  378. package/dist/cli/chunks/esm-node-2PKHKOTS.js +0 -2
  379. package/dist/cli/chunks/feature-flags-IVQ3AL4Q.js +0 -2
  380. package/dist/cli/chunks/file-discovery-QFPA6GMV.js +0 -2
  381. package/dist/cli/chunks/gnn-wrapper-OYC55N5E.js +0 -2
  382. package/dist/cli/chunks/hnsw-index-YO7CT23I.js +0 -2
  383. package/dist/cli/chunks/hnswlib-node-56YWVXFE.js +0 -2
  384. package/dist/cli/chunks/hypergraph-engine-A4Y2ZRAG.js +0 -2
  385. package/dist/cli/chunks/impact-analyzer-UEIGXSZ4.js +0 -2
  386. package/dist/cli/chunks/init-wizard-JWZUGIPJ.js +0 -2
  387. package/dist/cli/chunks/kernel-YNDTVKIW.js +0 -2
  388. package/dist/cli/chunks/knowledge-graph-NGJKFTSN.js +0 -2
  389. package/dist/cli/chunks/load-test-GZUBXFF3.js +0 -2
  390. package/dist/cli/chunks/memory-backend-3NQIZUXE.js +0 -2
  391. package/dist/cli/chunks/memory-handlers-MDZQ7HVW.js +0 -2
  392. package/dist/cli/chunks/opencode-installer-4HUB36H5.js +0 -3
  393. package/dist/cli/chunks/protocol-executor-SPUVRDWT.js +0 -2
  394. package/dist/cli/chunks/qe-reasoning-bank-3HBK2FVD.js +0 -2
  395. package/dist/cli/chunks/queen-coordinator-RW3NKO5A.js +0 -2
  396. package/dist/cli/chunks/real-embeddings-GK63VF35.js +0 -2
  397. package/dist/cli/chunks/router-RJGHWDQ3.js +0 -2
  398. package/dist/cli/chunks/routing-feedback-ZXBXFKX6.js +0 -2
  399. package/dist/cli/chunks/ruvector-commands-2TLNHC3A.js +0 -8
  400. package/dist/cli/chunks/rvf-dual-writer-MQW2SJLT.js +0 -2
  401. package/dist/cli/chunks/rvf-native-adapter-LKFKTMUN.js +0 -2
  402. package/dist/cli/chunks/safe-db-G22E5ROA.js +0 -2
  403. package/dist/cli/chunks/schedule-Y7VVCPYV.js +0 -2
  404. package/dist/cli/chunks/scheduler-AUQIFQB7.js +0 -2
  405. package/dist/cli/chunks/shared-rvf-dual-writer-BVSCQAFS.js +0 -2
  406. package/dist/cli/chunks/sqlite-persistence-JAVHUGGL.js +0 -2
  407. package/dist/cli/chunks/task-handlers-P5DSUKND.js +0 -2
  408. package/dist/cli/chunks/token-bootstrap-4VJKGVMK.js +0 -2
  409. package/dist/cli/chunks/transformers-GY7SIKEU.js +0 -2
  410. package/dist/cli/chunks/types-QJGNBKP2.js +0 -2
  411. package/dist/cli/chunks/unified-memory-XYGENQUT.js +0 -2
  412. package/dist/cli/chunks/unified-memory-hnsw-MVEGQBF3.js +0 -2
  413. package/dist/cli/chunks/unified-persistence-PFRCWEUG.js +0 -2
  414. package/dist/cli/chunks/visual-security-V47BLGJM.js +0 -2
  415. package/dist/cli/chunks/witness-chain-BR63P4A7.js +0 -2
  416. package/dist/cli/chunks/workflow-orchestrator-7PZMX3JZ.js +0 -2
@@ -1,3 +1,3 @@
1
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
- import{a as L}from"./chunk-3ZOONQG6.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.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.2");process.exit(0)}
2
+ import{a as L}from"./chunk-BIVIPF4O.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
@@ -1,5 +1,5 @@
1
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
- import{a as U,b as j,c as B,d as G}from"./chunk-YPFOCNOE.js";import{d as _}from"./chunk-VSVXUTJN.js";import{a as H}from"./chunk-3NZLZHJI.js";import{a as q,e as C,f as z}from"./chunk-AFLLQ5PP.js";import{a as I}from"./chunk-TLHP5EII.js";import{a as A,b as W,f as N,i as O}from"./chunk-4YS3IJ45.js";import{b as v,d as L,f as M,g as P}from"./chunk-YW2THB5Q.js";import{b as f,c as h}from"./chunk-3ZOONQG6.js";import{f as T}from"./chunk-SUSEVMZT.js";import{a as K}from"./chunk-3JPRUND5.js";import{c as D}from"./chunk-4VUPRTVX.js";import{b as w,d as Y}from"./chunk-WGMPEW2T.js";import{a as Q,b,c as J}from"./chunk-JZSDOIXA.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=_(this.qeConfig.sqlite),this.asymmetricEngine=new H}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-56YWVXFE.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
+ import{a as G}from"./chunk-J4BS6IWE.js";import{a as q,e as C,f as z}from"./chunk-Q4A72ZTV.js";import{a as I}from"./chunk-7NOIIC7G.js";import{a as H,b as _,c as U,d as j}from"./chunk-4UH25U4O.js";import{a as A,b as W,f as N,i as O}from"./chunk-TKF447CW.js";import{d as B}from"./chunk-5L6AU3QK.js";import{b as v,d as L,f as M,g as P}from"./chunk-563PJBDM.js";import{a as K}from"./chunk-XIBVVZGB.js";import{c as D}from"./chunk-JOVINE23.js";import{b as w,d as Y}from"./chunk-N3F3CX4V.js";import{b as f,c as h}from"./chunk-BIVIPF4O.js";import{a as Q,b,c as J}from"./chunk-SDTVHR63.js";import{f as T}from"./chunk-E25S5E2D.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-WICYCU5U.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -12,7 +12,7 @@ import{a as U,b as j,c as B,d as G}from"./chunk-YPFOCNOE.js";import{d as _}from"
12
12
  {{assertCode}}
13
13
  });
14
14
  });
15
- });`,variables:[{name:"className",type:"string",required:!0},{name:"methodName",type:"string",required:!0},{name:"expectedBehavior",type:"string",required:!0}]},context:{testType:"unit",tags:["unit-test","aaa","best-practice"]}},{patternType:"coverage-strategy",name:"Risk-Based Coverage",description:"Prioritize coverage by code risk and complexity",template:{type:"prompt",content:"Analyze coverage gaps focusing on critical business logic, error handling, and high-complexity functions.",variables:[]},context:{tags:["coverage","risk-based"]}}];for(let t of e)try{await this.storeQEPattern(t)}catch(i){o.warn("Failed to load foundational pattern",{name:t.name,error:i})}o.info("Loaded foundational patterns",{count:e.length})}async storeQEPattern(e){try{let t=`${e.name} ${e.description||""} ${e.context?.tags?.join(" ")||""}`,i=await v(t,this.qeConfig.embeddings),n=A(t)||"test-generation";if(q())try{let r=z(e.name,{description:e.description,template:e.template,patternType:e.patternType},n,{tags:e.context?.tags}),c=await C.evaluateWrite(r);if(!c.allowed&&(o.warn("Pattern blocked by MemoryWriteGate",{name:e.name,reason:c.reason,conflicts:c.conflictingPatterns?.join(", ")||"none"}),c.reason?.includes("strict")))return h(new Error(`Pattern blocked by governance: ${c.reason}`))}catch(r){o.warn("MemoryWriteGate check error (continuing)",{error:r})}let a=T(),s={id:a,patternType:e.patternType,qeDomain:n,domain:n,name:e.name,description:e.description||"",confidence:.5,usageCount:0,successRate:0,qualityScore:0,tier:"short-term",template:e.template,context:{tags:[],...e.context},createdAt:new Date,lastUsedAt:new Date,successfulUses:0,embedding:i,reusable:!1,reuseCount:0,averageTokenSavings:0};if(this.sqliteStore.storePattern(s,i),this.hnswIndex){let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(i,r),this.patternIdMap.set(r,a)}if(q())try{C.registerPattern({key:a,value:{name:s.name,description:s.description,patternType:s.patternType},domain:s.domain})}catch(r){o.warn("Pattern registration with MemoryWriteGate failed",{error:r})}return f(s)}catch(t){return h(b(t))}}async searchQEPatterns(e,t={}){let i=performance.now();try{if(!this.hnswIndex)return h(new Error("HNSW index not available"));let n=await v(e,this.qeConfig.embeddings),a=t.limit||10,s=this.hnswIndex.searchKnn(n,a*2),r=[];for(let m=0;m<s.neighbors.length&&r.length<a;m++){let p=s.neighbors[m],d=1-s.distances[m];if(t.minSimilarity&&d<t.minSimilarity)continue;let u=this.patternIdMap.get(p);if(!u)continue;let g=this.sqliteStore.getPattern(u);g&&(t.domain&&g.qeDomain!==t.domain||r.push({pattern:g,similarity:d}))}let c=performance.now()-i;return c>10&&o.warn("Slow search",{searchTimeMs:Number(c.toFixed(1))}),f(r)}catch(n){return h(b(n))}}async routeTask(e){let t=performance.now();this.stats.routingRequests++;try{let i=e.domain?[e.domain]:W(e.task);i.length===0&&i.push("test-generation");let n=await this.searchQEPatterns(e.task,{limit:10,domain:i[0]}),a=n.success?n.value.map(l=>l.pattern):[],s=[];for(let[l,d]of Object.entries(this.agentCapabilities)){let u=0,g=[],x=i.filter(y=>d.domains.includes(y)).length,S=x>0?x/i.length*.4:0;if(u+=S*this.qeConfig.routingWeights.similarity,S>0&&g.push(`Domain: ${(S*100).toFixed(0)}%`),e.capabilities&&e.capabilities.length>0){let y=e.capabilities.filter(F=>d.capabilities.some($=>$.toLowerCase().includes(F.toLowerCase()))).length,E=y>0?y/e.capabilities.length*.3:0;u+=E*this.qeConfig.routingWeights.capabilities,E>0&&g.push(`Caps: ${(E*100).toFixed(0)}%`)}else u+=.15*this.qeConfig.routingWeights.capabilities;u+=d.performanceScore*.3*this.qeConfig.routingWeights.performance,g.push(`Perf: ${(d.performanceScore*100).toFixed(0)}%`),s.push({agent:l,score:u,reasoning:g})}s.sort((l,d)=>d.score-l.score);let r=s[0],c=s.slice(1,4),m=[];if(this.qeConfig.enableGuidance&&i.length>0){let l=j(i[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});m.push(...l.slice(0,5))}let p=performance.now()-t;return this.stats.totalRoutingLatency+=p,this.routingLatencies.push(p),f({recommendedAgent:r.agent,confidence:r.score,alternatives:c.map(l=>({agent:l.agent,score:l.score})),domains:i,patterns:a,guidance:m,reasoning:r.reasoning.join("; "),latencyMs:p})}catch(i){return h(b(i))}}async recordOutcome(e){if(!this.qeConfig.enableLearning)return f(void 0);try{this.sqliteStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback),this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++;let t=this.sqliteStore.getPattern(e.patternId);if(t){let i=t.qeDomain,n=this.asymmetricEngine.computeConfidenceUpdate(t.confidence,e.success?"success":"failure",i);this.asymmetricEngine.shouldQuarantine(n,i).shouldQuarantine&&o.info("Pattern quarantined (asymmetric drop)",{name:t.name}),this.sqliteStore.updatePattern(e.patternId,{confidence:n}),await this.checkPatternPromotionWithCoherence(t)&&(this.sqliteStore.promotePattern(e.patternId),o.info("Pattern promoted to long-term",{name:t.name}))}return f(void 0)}catch(t){return h(b(t))}}async checkPatternPromotionWithCoherence(e){let t=N(e);if(!t.meetsUsageCriteria||!t.meetsQualityCriteria)return!1;if(this.coherenceService&&this.coherenceService.isInitialized()){let a=[...await this.getLongTermPatterns(),e].map(r=>({id:r.id,embedding:r.embedding||[],weight:r.confidence,metadata:{name:r.name,domain:r.qeDomain}})),s=await this.coherenceService.checkCoherence(a);if(s.energy>=(this.qeConfig.coherenceThreshold||.4))return o.info("Pattern promotion blocked due to coherence violation",{name:e.name,energy:s.energy}),s.contradictions&&s.contradictions.length>0&&o.info("Conflicts with existing patterns",{conflictingNodeIds:s.contradictions.map(r=>r.nodeIds).flat()}),!1}return!0}async getLongTermPatterns(){return this.sqliteStore.getPatterns({limit:1e3}).filter(t=>t.tier==="long-term")}shouldPromote(e){return e.tier==="short-term"&&e.successfulUses>=3&&e.successRate>=.7&&e.confidence>=.6}getQEGuidance(e){return U(e)}generateQEContext(e,t){return G(e,t||{})}checkQEAntiPatterns(e,t){return B(e,t)}async getQEStats(){let e=this.sqliteStore.getStats(),t=this.routingLatencies.percentile(95)||0,i={};for(let n of O)i[n]=e.byDomain[n]||0;return{totalPatterns:e.totalPatterns,byDomain:i,byTier:e.byTier,routingRequests:this.stats.routingRequests,avgRoutingLatencyMs:this.stats.routingRequests>0?this.stats.totalRoutingLatency/this.stats.routingRequests:0,p95RoutingLatencyMs:t,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,embeddingCacheSize:0,transformerAvailable:M(),embeddingDimension:P(),sqliteDbPath:this.qeConfig.sqlite.dbPath||".agentic-qe/memory.db",asymmetricLearning:{failurePenaltyRatio:"10:1",quarantinedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!0).length,rehabilitatedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!1&&n.quarantinedAt).length,avgConfidenceDelta:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes-.5:0}}}async storeLoopPattern(e){try{let t=await this.storeQEPattern({patternType:"anti-pattern",name:`loop-detection:${e.toolCallSignature}`,description:`Tool call loop detected for agent ${e.agentId} during ${e.taskType}. Steering: ${e.steeringUsed}. Resolved: ${e.resolved}`,template:{type:"prompt",content:e.steeringUsed,variables:[]},context:{tags:["anti-pattern","loop-detection","learning-optimization",e.taskType]}});return t.success?{success:!0,patternId:t.value.id}:{success:!1,error:t.error?.message??"Unknown error"}}catch(t){return{success:!1,error:Q(t)}}}async recordPatternOutcome(e,t,i){let n=this.sqliteStore.getPattern(e);if(!n)return;let a=n.usageCount+1,s=t?n.successfulUses+1:n.successfulUses,r=s/a,c=.3,m=(1-c)*n.qualityScore+c*i,p=Math.min(1,.5+a*.05+r*.3);this.sqliteStore.updatePattern(e,{usageCount:a,successfulUses:s,successRate:r,qualityScore:m,confidence:p})}async checkPatternPromotion(e,t,i,n){let a=this.sqliteStore.getPattern(e);return a?a.tier==="short-term"?t>=3&&i>=.6&&n>=.5:a.tier==="long-term"?t>=10&&i>=.75&&n>=.7:!1:!1}async promotePattern(e){this.sqliteStore.promotePattern(e)}async demotePattern(e){let t=this.sqliteStore.getPattern(e);if(!t)return;let i=["short-term","working","long-term"],n=i.indexOf(t.tier);if(n>0){let a=i[n-1];this.sqliteStore.updatePattern(e,{tier:a}),o.info("Pattern demoted",{name:t.name,newTier:a})}}cleanupPatternIdMap(){if(!this.initialized)return 0;let e=0,t=this.sqliteStore.getPatterns({limit:1e5}),i=new Set(t.map(n=>n.id));for(let[n,a]of Array.from(this.patternIdMap.entries()))i.has(a)||(this.patternIdMap.delete(n),e++);return e>0&&o.info("Cleaned stale patternIdMap entries",{count:e}),e}removePatternFromHNSW(e){for(let[t,i]of Array.from(this.patternIdMap.entries()))if(i===e)return this.patternIdMap.delete(t),o.info("Removed pattern from HNSW mapping",{patternId:e}),!0;return!1}getMemoryStats(){return{patternIdMapSize:this.patternIdMap.size,routingLatenciesSize:this.routingLatencies.length,hnswIndexCount:this.hnswIndex?.getCurrentCount()??0}}async storeTrajectory(e){return this.sqliteStore.getDb().prepare(`
15
+ });`,variables:[{name:"className",type:"string",required:!0},{name:"methodName",type:"string",required:!0},{name:"expectedBehavior",type:"string",required:!0}]},context:{testType:"unit",tags:["unit-test","aaa","best-practice"]}},{patternType:"coverage-strategy",name:"Risk-Based Coverage",description:"Prioritize coverage by code risk and complexity",template:{type:"prompt",content:"Analyze coverage gaps focusing on critical business logic, error handling, and high-complexity functions.",variables:[]},context:{tags:["coverage","risk-based"]}}];for(let t of e)try{await this.storeQEPattern(t)}catch(i){o.warn("Failed to load foundational pattern",{name:t.name,error:i})}o.info("Loaded foundational patterns",{count:e.length})}async storeQEPattern(e){try{let t=`${e.name} ${e.description||""} ${e.context?.tags?.join(" ")||""}`,i=await v(t,this.qeConfig.embeddings),n=A(t)||"test-generation";if(q())try{let r=z(e.name,{description:e.description,template:e.template,patternType:e.patternType},n,{tags:e.context?.tags}),c=await C.evaluateWrite(r);if(!c.allowed&&(o.warn("Pattern blocked by MemoryWriteGate",{name:e.name,reason:c.reason,conflicts:c.conflictingPatterns?.join(", ")||"none"}),c.reason?.includes("strict")))return h(new Error(`Pattern blocked by governance: ${c.reason}`))}catch(r){o.warn("MemoryWriteGate check error (continuing)",{error:r})}let a=T(),s={id:a,patternType:e.patternType,qeDomain:n,domain:n,name:e.name,description:e.description||"",confidence:.5,usageCount:0,successRate:0,qualityScore:0,tier:"short-term",template:e.template,context:{tags:[],...e.context},createdAt:new Date,lastUsedAt:new Date,successfulUses:0,embedding:i,reusable:!1,reuseCount:0,averageTokenSavings:0};if(this.sqliteStore.storePattern(s,i),this.hnswIndex){let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(i,r),this.patternIdMap.set(r,a)}if(q())try{C.registerPattern({key:a,value:{name:s.name,description:s.description,patternType:s.patternType},domain:s.domain})}catch(r){o.warn("Pattern registration with MemoryWriteGate failed",{error:r})}return f(s)}catch(t){return h(b(t))}}async searchQEPatterns(e,t={}){let i=performance.now();try{if(!this.hnswIndex)return h(new Error("HNSW index not available"));let n=await v(e,this.qeConfig.embeddings),a=t.limit||10,s=this.hnswIndex.searchKnn(n,a*2),r=[];for(let m=0;m<s.neighbors.length&&r.length<a;m++){let p=s.neighbors[m],d=1-s.distances[m];if(t.minSimilarity&&d<t.minSimilarity)continue;let u=this.patternIdMap.get(p);if(!u)continue;let g=this.sqliteStore.getPattern(u);g&&(t.domain&&g.qeDomain!==t.domain||r.push({pattern:g,similarity:d}))}let c=performance.now()-i;return c>10&&o.warn("Slow search",{searchTimeMs:Number(c.toFixed(1))}),f(r)}catch(n){return h(b(n))}}async routeTask(e){let t=performance.now();this.stats.routingRequests++;try{let i=e.domain?[e.domain]:W(e.task);i.length===0&&i.push("test-generation");let n=await this.searchQEPatterns(e.task,{limit:10,domain:i[0]}),a=n.success?n.value.map(l=>l.pattern):[],s=[];for(let[l,d]of Object.entries(this.agentCapabilities)){let u=0,g=[],x=i.filter(y=>d.domains.includes(y)).length,S=x>0?x/i.length*.4:0;if(u+=S*this.qeConfig.routingWeights.similarity,S>0&&g.push(`Domain: ${(S*100).toFixed(0)}%`),e.capabilities&&e.capabilities.length>0){let y=e.capabilities.filter(F=>d.capabilities.some($=>$.toLowerCase().includes(F.toLowerCase()))).length,E=y>0?y/e.capabilities.length*.3:0;u+=E*this.qeConfig.routingWeights.capabilities,E>0&&g.push(`Caps: ${(E*100).toFixed(0)}%`)}else u+=.15*this.qeConfig.routingWeights.capabilities;u+=d.performanceScore*.3*this.qeConfig.routingWeights.performance,g.push(`Perf: ${(d.performanceScore*100).toFixed(0)}%`),s.push({agent:l,score:u,reasoning:g})}s.sort((l,d)=>d.score-l.score);let r=s[0],c=s.slice(1,4),m=[];if(this.qeConfig.enableGuidance&&i.length>0){let l=_(i[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});m.push(...l.slice(0,5))}let p=performance.now()-t;return this.stats.totalRoutingLatency+=p,this.routingLatencies.push(p),f({recommendedAgent:r.agent,confidence:r.score,alternatives:c.map(l=>({agent:l.agent,score:l.score})),domains:i,patterns:a,guidance:m,reasoning:r.reasoning.join("; "),latencyMs:p})}catch(i){return h(b(i))}}async recordOutcome(e){if(!this.qeConfig.enableLearning)return f(void 0);try{this.sqliteStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback),this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++;let t=this.sqliteStore.getPattern(e.patternId);if(t){let i=t.qeDomain,n=this.asymmetricEngine.computeConfidenceUpdate(t.confidence,e.success?"success":"failure",i);this.asymmetricEngine.shouldQuarantine(n,i).shouldQuarantine&&o.info("Pattern quarantined (asymmetric drop)",{name:t.name}),this.sqliteStore.updatePattern(e.patternId,{confidence:n}),await this.checkPatternPromotionWithCoherence(t)&&(this.sqliteStore.promotePattern(e.patternId),o.info("Pattern promoted to long-term",{name:t.name}))}return f(void 0)}catch(t){return h(b(t))}}async checkPatternPromotionWithCoherence(e){let t=N(e);if(!t.meetsUsageCriteria||!t.meetsQualityCriteria)return!1;if(this.coherenceService&&this.coherenceService.isInitialized()){let a=[...await this.getLongTermPatterns(),e].map(r=>({id:r.id,embedding:r.embedding||[],weight:r.confidence,metadata:{name:r.name,domain:r.qeDomain}})),s=await this.coherenceService.checkCoherence(a);if(s.energy>=(this.qeConfig.coherenceThreshold||.4))return o.info("Pattern promotion blocked due to coherence violation",{name:e.name,energy:s.energy}),s.contradictions&&s.contradictions.length>0&&o.info("Conflicts with existing patterns",{conflictingNodeIds:s.contradictions.map(r=>r.nodeIds).flat()}),!1}return!0}async getLongTermPatterns(){return this.sqliteStore.getPatterns({limit:1e3}).filter(t=>t.tier==="long-term")}shouldPromote(e){return e.tier==="short-term"&&e.successfulUses>=3&&e.successRate>=.7&&e.confidence>=.6}getQEGuidance(e){return H(e)}generateQEContext(e,t){return j(e,t||{})}checkQEAntiPatterns(e,t){return U(e,t)}async getQEStats(){let e=this.sqliteStore.getStats(),t=this.routingLatencies.percentile(95)||0,i={};for(let n of O)i[n]=e.byDomain[n]||0;return{totalPatterns:e.totalPatterns,byDomain:i,byTier:e.byTier,routingRequests:this.stats.routingRequests,avgRoutingLatencyMs:this.stats.routingRequests>0?this.stats.totalRoutingLatency/this.stats.routingRequests:0,p95RoutingLatencyMs:t,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,embeddingCacheSize:0,transformerAvailable:M(),embeddingDimension:P(),sqliteDbPath:this.qeConfig.sqlite.dbPath||".agentic-qe/memory.db",asymmetricLearning:{failurePenaltyRatio:"10:1",quarantinedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!0).length,rehabilitatedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!1&&n.quarantinedAt).length,avgConfidenceDelta:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes-.5:0}}}async storeLoopPattern(e){try{let t=await this.storeQEPattern({patternType:"anti-pattern",name:`loop-detection:${e.toolCallSignature}`,description:`Tool call loop detected for agent ${e.agentId} during ${e.taskType}. Steering: ${e.steeringUsed}. Resolved: ${e.resolved}`,template:{type:"prompt",content:e.steeringUsed,variables:[]},context:{tags:["anti-pattern","loop-detection","learning-optimization",e.taskType]}});return t.success?{success:!0,patternId:t.value.id}:{success:!1,error:t.error?.message??"Unknown error"}}catch(t){return{success:!1,error:Q(t)}}}async recordPatternOutcome(e,t,i){let n=this.sqliteStore.getPattern(e);if(!n)return;let a=n.usageCount+1,s=t?n.successfulUses+1:n.successfulUses,r=s/a,c=.3,m=(1-c)*n.qualityScore+c*i,p=Math.min(1,.5+a*.05+r*.3);this.sqliteStore.updatePattern(e,{usageCount:a,successfulUses:s,successRate:r,qualityScore:m,confidence:p})}async checkPatternPromotion(e,t,i,n){let a=this.sqliteStore.getPattern(e);return a?a.tier==="short-term"?t>=3&&i>=.6&&n>=.5:a.tier==="long-term"?t>=10&&i>=.75&&n>=.7:!1:!1}async promotePattern(e){this.sqliteStore.promotePattern(e)}async demotePattern(e){let t=this.sqliteStore.getPattern(e);if(!t)return;let i=["short-term","working","long-term"],n=i.indexOf(t.tier);if(n>0){let a=i[n-1];this.sqliteStore.updatePattern(e,{tier:a}),o.info("Pattern demoted",{name:t.name,newTier:a})}}cleanupPatternIdMap(){if(!this.initialized)return 0;let e=0,t=this.sqliteStore.getPatterns({limit:1e5}),i=new Set(t.map(n=>n.id));for(let[n,a]of Array.from(this.patternIdMap.entries()))i.has(a)||(this.patternIdMap.delete(n),e++);return e>0&&o.info("Cleaned stale patternIdMap entries",{count:e}),e}removePatternFromHNSW(e){for(let[t,i]of Array.from(this.patternIdMap.entries()))if(i===e)return this.patternIdMap.delete(t),o.info("Removed pattern from HNSW mapping",{patternId:e}),!0;return!1}getMemoryStats(){return{patternIdMapSize:this.patternIdMap.size,routingLatenciesSize:this.routingLatencies.length,hnswIndexCount:this.hnswIndex?.getCurrentCount()??0}}async storeTrajectory(e){return this.sqliteStore.getDb().prepare(`
16
16
  INSERT OR REPLACE INTO qe_trajectories (
17
17
  id, task, agent, domain, started_at, ended_at, success, steps_json, metadata_json
18
18
  ) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'), ?, ?, ?)
@@ -1,5 +1,5 @@
1
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-JZSDOIXA.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-G7CFNNQV.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.2");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-SDTVHR63.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-KTUK6UE2.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
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-4I2IOUS4.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
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.2");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-YXCU4CJX.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
@@ -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.2");process.exit(0)}
2
+ import{a as oe,b as ae}from"./chunk-727BDQ3K.js";import{S as ie,i as j,p as q}from"./chunk-DBE34QES.js";import{c as g,e as $,g as W}from"./chunk-YXCU4CJX.js";var R,E=g(()=>{"use strict";R={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(V)return k!==null;try{let o=(ae(),W(oe));if(k=o.differentiableSearch,P=o.init,P)try{P()}catch{}return V=!0,!0}catch{return V=!0,!1}}function B(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function U(o,e,t,r){let n=t*r;if(n===0)return 0;let a=0,i=Math.min(o.length,e.length);for(let s=0;s<i;s++)a+=o[s]*e[s];return a/n}function O(o,e){let t=0,r=Math.min(o.length,e.length);for(let n=0;n<r;n++){let a=o[n]-e[n];t+=a*a}return Math.sqrt(t)}function ce(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*r),i=Math.floor((n+1)*r),s=0;for(let c=a;c<i;c++)s+=o[c];t[n]=s/(i-a)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var k,P,V,w,K=g(()=>{"use strict";E();k=null,P=null,V=!1;w=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...R,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:ce(e,this.config.dimensions)}add(e,t,r){this.ensureLoaded();let n=this.normalizeVector(t),a=B(n);if(this.idToIndex.has(e)){let s=this.idToIndex.get(e);this.entries[s]={id:e,vector:n,norm:a,metadata:r};return}let i=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:r}),this.idToIndex.set(e,i)}search(e,t){if(this.ensureLoaded(),this.entries.length===0)return[];let r=this.normalizeVector(e),n=B(r),a=Math.min(t,this.entries.length),i=this.entries.length>0?this.entries[0].vector.length:0,s=r.length===i;if(this.hasRuvector&&s&&k)try{let c=this.entries.map(l=>l.vector);return k(r,c,a,1).indices.map(l=>{let h=this.entries[l],u=this.config.metric==="cosine"?U(r,h.vector,n,h.norm):-O(r,h.vector);return{id:h.id,score:u,metadata:h.metadata}})}catch{}return this.bruteForcSearch(r,n,a)}bruteForcSearch(e,t,r){let n=[];for(let a of this.entries){let i;this.config.metric==="cosine"?i=U(e,a.vector,t,a.norm):i=-O(e,a.vector),n.push({id:a.id,score:i,metadata:a.metadata})}return n.sort((a,i)=>i.score-a.score),n.slice(0,r)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let r=this.entries.length-1;if(t!==r){let n=this.entries[r];this.entries[t]=n,this.idToIndex.set(n.id,t)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}}});import{createRequire as le}from"module";function ue(){if(J){if(A)return A;throw new p(Q??"Unknown load error")}J=!0;try{let o=he("@ruvector/router");if(!o.VectorDb||!o.DistanceMetric)throw new Error("@ruvector/router module missing VectorDb or DistanceMetric exports");return A=o,A}catch(o){let e=o instanceof Error?o.message:String(o);throw Q=e,new p(e)}}function _(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function X(o,e,t,r){let n=t*r;if(n===0)return 0;let a=0,i=Math.min(o.length,e.length);for(let s=0;s<i;s++)a+=o[s]*e[s];return a/n}function de(o,e){if(o.length===e)return o;let t=new Float32Array(e);if(o.length>e){let r=o.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*r),i=Math.floor((n+1)*r),s=0;for(let c=a;c<i;c++)s+=o[c];t[n]=s/(i-a)}}else for(let r=0;r<o.length;r++)t[r]=o[r];return t}var he,p,A,J,Q,H,Y=g(()=>{"use strict";E();he=le(import.meta.url),p=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},A=null,J=!1,Q=null;H=class{config;nativeDb=null;metadataStore=new Map;vectorStore=new Map;normStore=new Map;operationLock=Promise.resolve();highFallbackWarningEmitted=!1;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...R,...e};let t=ue(),r=this.config.metric==="cosine"?t.DistanceMetric.Cosine:t.DistanceMetric.Euclidean;try{this.nativeDb=new t.VectorDb({dimensions:this.config.dimensions,distanceMetric:r,hnswM:this.config.M,hnswEfConstruction:this.config.efConstruction,hnswEfSearch:this.config.efSearch})}catch(n){let a=n instanceof Error?n.message:String(n);throw new p(`VectorDb creation failed: ${a}`)}}add(e,t,r){let n=this.normalizeVector(t),a=_(n);if(this.vectorStore.has(e))try{this.nativeDb.delete(String(e))}catch{}this.nativeDb.insert(String(e),n),this.vectorStore.set(e,n),this.normStore.set(e,a),r&&this.metadataStore.set(e,r),this._metrics.totalAdds++}search(e,t){let r=performance.now();if(this.vectorStore.size===0)return[];let n=this.normalizeVector(e),a=_(n),i=Math.min(t,this.vectorStore.size),s;try{s=this.nativeDb.search(n,i).map(l=>{let h=Number(l.id),u=this.vectorStore.get(h),S=this.normStore.get(h)??0,b;return this.config.metric==="cosine"&&u?b=X(n,u,a,S):b=-l.score,{id:h,score:b,metadata:this.metadataStore.get(h)}}),s.sort((l,h)=>h.score-l.score),this._metrics.nativeSearchCount++}catch{this._metrics.fallbackSearchCount++,this._metrics.bruteForceSearchCount++,console.warn(`[NativeHNSW] FALLBACK: Using brute-force linear scan (@ruvector/router search failed). Index size: ${this.vectorStore.size}`),s=this.bruteForceSearch(n,a,i)}let c=performance.now()-r;return this.updateSearchMetrics(c),this._metrics.fallbackRate=this._metrics.fallbackSearchCount/this._metrics.totalSearches,this._metrics.allSearchesBruteForce=this._metrics.nativeSearchCount===0&&this._metrics.totalSearches>0,!this.highFallbackWarningEmitted&&this._metrics.fallbackRate>.5&&this._metrics.totalSearches>=10&&(this.highFallbackWarningEmitted=!0,console.error(`[NativeHNSW] WARNING: ${(this._metrics.fallbackRate*100).toFixed(0)}% of searches are using brute-force fallback. Native HNSW may not be functioning correctly. Consider rebuilding the index or checking @ruvector/router installation.`)),c>50&&console.warn(`[NativeHNSW] search took ${c.toFixed(1)}ms (k=${t}, results=${s.length})`),s}remove(e){if(!this.vectorStore.has(e))return!1;try{this.nativeDb.delete(String(e))}catch{}return this.vectorStore.delete(e),this.normStore.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.vectorStore.size}dimensions(){return this.config.dimensions}recall(){let e=this.config.efSearch/this.config.M;return e>=10?.99:e>=5?.97:e>=3?.95:.9}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){for(let e of this.vectorStore.keys())try{this.nativeDb.delete(String(e))}catch{}this.vectorStore.clear(),this.normStore.clear(),this.metadataStore.clear()}isNativeAvailable(){return this.nativeDb!==null}normalizeVector(e){return e.length===this.config.dimensions?e:de(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let t=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((t-1)/t)+e/t}bruteForceSearch(e,t,r){let n=[];for(let[a,i]of this.vectorStore){let s=this.normStore.get(a)??_(i),c=this.config.metric==="cosine"?X(e,i,t,s):-(function(){let d=0,l=Math.min(e.length,i.length);for(let h=0;h<l;h++){let u=e[h]-i[h];d+=u*u}return Math.sqrt(d)})();n.push({id:a,score:c,metadata:this.metadataStore.get(a)})}return n.sort((a,i)=>i.score-a.score),n.slice(0,r)}}});function Z(o,e){let t=Array.from({length:e},()=>new Float64Array(e));for(let r=0;r<e;r++){let n=o[r].length;t[r][r]=n;for(let a of o[r])t[r][a]=-1}return t}function F(o,e){let t=e.length,r=new Float64Array(t);for(let n=0;n<t;n++){let a=o[n].length;r[n]=a*e[n];for(let i of o[n])r[n]-=e[i]}return r}function x(o){let e=0;for(let t=0;t<o.length;t++)e+=o[t]*o[t];return Math.sqrt(e)}function I(o){let e=x(o);if(e>0)for(let t=0;t<o.length;t++)o[t]/=e}function v(o,e){let t=0;for(let r=0;r<o.length;r++)t+=o[r]*e[r];for(let r=0;r<o.length;r++)o[r]-=t*e[r]}function y(o,e,t=100,r=1e-6){if(e<=1)return 0;if(e===2)return o[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),I(a);let i=0;for(let l=0;l<30;l++){let h=F(o,a);if(v(h,n),i=x(h),i>0)for(let u=0;u<e;u++)a[u]=h[u]/i}if(i<r)return 0;let s=new Float64Array(e);for(let l=0;l<e;l++)s[l]=Math.random()-.5;v(s,n),I(s);let c=0;for(let l=0;l<t;l++){let h=F(o,s),u=new Float64Array(e);for(let m=0;m<e;m++)u[m]=i*s[m]-h[m];v(u,n);let S=x(u);if(S<r)break;let b=S;for(let m=0;m<e;m++)s[m]=u[m]/S;if(Math.abs(b-c)<r)break;c=b}let d=i-c;return Math.max(0,d)}function C(o,e,t=100,r=1e-6){return y(o,e,t,r)}function N(o,e,t=50,r){if(e<=1)return 0;let n=r??y(o,e);if(n<1e-10)return 1/0;let i=2*Math.max(...o.map(d=>d.length),1),c=2*(Math.log(i/n)/(i-n));return Math.max(0,c)}function M(o,e,t){let r=1-Math.exp(-o/.05),n=1-Math.exp(-e/.5),a=t===1/0?0:1/(1+t/5),i=.4*r+.3*n+.3*a;return Math.max(0,Math.min(1,i))}var D=g(()=>{"use strict"});var re={};$(re,{ALERT_THRESHOLDS:()=>me,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>T,_resetNativeLoader:()=>pe,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>C,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>be,deflateVector:()=>v,estimateEffectiveResistance:()=>N,laplacianMultiply:()=>F,normalizeInPlace:()=>I,vectorNorm:()=>x});function fe(){return z?L:(z=!0,L=null,null)}function pe(){L=null,z=!1}function te(o,e=16,t){let r=o.size();if(r===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:r},()=>[]),a=Math.min(e,r-1);if(a===0)return{adjacency:n,nodeCount:r,adjacencySource:"approximate"};if(t&&t.size>0){let i=Array.from(t.keys()).slice(0,r),s=new Map;for(let c=0;c<i.length;c++)s.set(i[c],c);for(let c=0;c<i.length;c++){let d=t.get(i[c]);if(!d)continue;let l=o.search(d,a+1);for(let h of l){if(h.id===i[c])continue;let u=s.get(h.id);u!==void 0&&(n[c].includes(u)||n[c].push(u),n[u].includes(c)||n[u].push(c))}}return{adjacency:n,nodeCount:r,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let i=0;i<r;i++)for(let s=0;s<a;s++){let c=(i+s+1)%r;n[i].includes(c)||n[i].push(c),n[c].includes(i)||n[c].push(i)}return{adjacency:n,nodeCount:r,adjacencySource:"approximate"}}function be(o){return new T(o)}var ee,me,L,z,T,ne=g(()=>{"use strict";D();D();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},me={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},L=null,z=!1;T=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let t=performance.now(),r=e.size();if(r<this.config.minIndexSize)return this.createSmallIndexReport(r,performance.now()-t);this.nativeChecked||(this.nativeChecked=!0,this.useNative=fe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:i}=te(e),s=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),c=this.generateAlerts(s);this.alerts.length=0,this.alerts.push(...c);let d=performance.now()-t,l={healthy:c.length===0,metrics:s,alerts:c,indexSize:r,usedNativeBackend:this.useNative,adjacencySource:i,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:s.coherenceScore,fiedlerValue:s.fiedlerValue,indexSize:r,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let t=L,r=t.computeFiedlerValue(e),n=t.computeSpectralGap(e),a=t.computeEffectiveResistance(e),i=M(r,n,a);return{fiedlerValue:r,spectralGap:n,effectiveResistance:a,coherenceScore:i}}computeApproximateMetrics(e,t){let r=y(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),n=C(e,t,this.config.maxPowerIterations,this.config.convergenceTolerance),a=N(e,t,this.config.resistanceSampleSize,r),i=M(r,n,a);return{fiedlerValue:r,spectralGap:n,effectiveResistance:a,coherenceScore:i}}generateAlerts(e){let t=[],r=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&t.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:r}),e.spectralGap<this.config.spectralGapThreshold&&t.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:r}),e.effectiveResistance>this.config.resistanceThreshold&&t.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:r}),e.coherenceScore<this.config.coherenceThreshold&&t.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:r}),t}createSmallIndexReport(e,t){let r={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:r,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:t,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:r.coherenceScore,fiedlerValue:r.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve={};$(ve,{HnswAdapter:()=>G});var ge,f,G,ye=g(()=>{K();Y();ie();ge={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},f=new Map,G=class o{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,t){this.indexName=e;let n={...ge[e]??{},...t},{backend:a,isNative:i}=o.createBackend(n);this.backend=a,this._isNativeBackend=i}add(e,t,r){this.backend.add(e,t,r),this.maybeRunHealthCheck()}search(e,t){let r=performance.now(),n=this.backend.search(e,t),a=performance.now()-r;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${t}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,t){let r=this.stringToNumericId.get(e);r!==void 0?this.backend.remove(r):(r=this.nextAutoId++,this.stringToNumericId.set(e,r),this.numericToStringId.set(r,e)),this.backend.add(r,new Float32Array(t))}searchByArray(e,t){return this.backend.search(new Float32Array(e),t).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let t=this.stringToNumericId.get(e);if(t===void 0)return!1;let r=this.backend.remove(t);return r&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(t)),r}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof w?this.backend.isRuvectorAvailable():this.backend instanceof H?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),W(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new H(e),isNative:!0}}catch(t){t instanceof p?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${t.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",t)}return{backend:new w(e),isNative:!1}}static create(e,t){let r=f.get(e);if(r instanceof o)return r;let n=new o(e,t);return f.set(e,n),n}static get(e){let t=f.get(e);return t instanceof o?t:void 0}static close(e){let t=f.get(e);t instanceof o&&t.clear(),f.delete(e)}static closeAll(){for(let[e]of f)o.close(e);f.clear()}static listIndexes(){return Array.from(f.keys())}}});export{G as a,ve as b,ye as c};
@@ -1,3 +1,3 @@
1
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.2");process.exit(0)}
2
2
  import a from"chalk";import{existsSync as m,statSync as V}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var S=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
3
3
  Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,S as j};
@@ -1,2 +1,2 @@
1
- if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.0");process.exit(0)}
2
- import{c as T}from"./chunk-4I2IOUS4.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ 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.2");process.exit(0)}
2
+ import{c as T}from"./chunk-YXCU4CJX.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};