agentic-qe 3.2.3 → 3.3.0

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 (340) hide show
  1. package/.claude/agents/v3/qe-accessibility-auditor.md +90 -0
  2. package/README.md +43 -5
  3. package/package.json +3 -2
  4. package/scripts/cloud-db-config.json +37 -0
  5. package/scripts/cloud-db-connect.sh +37 -0
  6. package/scripts/cloud-db-tunnel.sh +23 -0
  7. package/v3/CHANGELOG.md +165 -0
  8. package/v3/README.md +59 -1
  9. package/v3/assets/agents/v3/qe-accessibility-auditor.md +90 -0
  10. package/v3/dist/adapters/claude-flow/index.d.ts +54 -0
  11. package/v3/dist/adapters/claude-flow/index.d.ts.map +1 -0
  12. package/v3/dist/adapters/claude-flow/index.js +79 -0
  13. package/v3/dist/adapters/claude-flow/index.js.map +1 -0
  14. package/v3/dist/adapters/claude-flow/model-router-bridge.d.ts +70 -0
  15. package/v3/dist/adapters/claude-flow/model-router-bridge.d.ts.map +1 -0
  16. package/v3/dist/adapters/claude-flow/model-router-bridge.js +203 -0
  17. package/v3/dist/adapters/claude-flow/model-router-bridge.js.map +1 -0
  18. package/v3/dist/adapters/claude-flow/pretrain-bridge.d.ts +73 -0
  19. package/v3/dist/adapters/claude-flow/pretrain-bridge.d.ts.map +1 -0
  20. package/v3/dist/adapters/claude-flow/pretrain-bridge.js +276 -0
  21. package/v3/dist/adapters/claude-flow/pretrain-bridge.js.map +1 -0
  22. package/v3/dist/adapters/claude-flow/trajectory-bridge.d.ts +70 -0
  23. package/v3/dist/adapters/claude-flow/trajectory-bridge.d.ts.map +1 -0
  24. package/v3/dist/adapters/claude-flow/trajectory-bridge.js +205 -0
  25. package/v3/dist/adapters/claude-flow/trajectory-bridge.js.map +1 -0
  26. package/v3/dist/adapters/claude-flow/types.d.ts +99 -0
  27. package/v3/dist/adapters/claude-flow/types.d.ts.map +1 -0
  28. package/v3/dist/adapters/claude-flow/types.js +6 -0
  29. package/v3/dist/adapters/claude-flow/types.js.map +1 -0
  30. package/v3/dist/causal-discovery/causal-graph.d.ts +80 -1
  31. package/v3/dist/causal-discovery/causal-graph.d.ts.map +1 -1
  32. package/v3/dist/causal-discovery/causal-graph.js +111 -1
  33. package/v3/dist/causal-discovery/causal-graph.js.map +1 -1
  34. package/v3/dist/cli/bundle.js +11612 -4929
  35. package/v3/dist/cli/commands/claude-flow-setup.d.ts +82 -0
  36. package/v3/dist/cli/commands/claude-flow-setup.d.ts.map +1 -0
  37. package/v3/dist/cli/commands/claude-flow-setup.js +334 -0
  38. package/v3/dist/cli/commands/claude-flow-setup.js.map +1 -0
  39. package/v3/dist/cli/commands/hooks.d.ts +2 -0
  40. package/v3/dist/cli/commands/hooks.d.ts.map +1 -1
  41. package/v3/dist/cli/commands/hooks.js +13 -2
  42. package/v3/dist/cli/commands/hooks.js.map +1 -1
  43. package/v3/dist/cli/commands/init.d.ts +19 -0
  44. package/v3/dist/cli/commands/init.d.ts.map +1 -0
  45. package/v3/dist/cli/commands/init.js +345 -0
  46. package/v3/dist/cli/commands/init.js.map +1 -0
  47. package/v3/dist/cli/index.js +110 -2
  48. package/v3/dist/cli/index.js.map +1 -1
  49. package/v3/dist/coordination/mincut/interfaces.d.ts +8 -2
  50. package/v3/dist/coordination/mincut/interfaces.d.ts.map +1 -1
  51. package/v3/dist/coordination/mincut/interfaces.js.map +1 -1
  52. package/v3/dist/coordination/mincut/mincut-health-monitor.d.ts +5 -0
  53. package/v3/dist/coordination/mincut/mincut-health-monitor.d.ts.map +1 -1
  54. package/v3/dist/coordination/mincut/mincut-health-monitor.js +22 -4
  55. package/v3/dist/coordination/mincut/mincut-health-monitor.js.map +1 -1
  56. package/v3/dist/coordination/mincut/queen-integration.d.ts +4 -0
  57. package/v3/dist/coordination/mincut/queen-integration.d.ts.map +1 -1
  58. package/v3/dist/coordination/mincut/queen-integration.js +14 -1
  59. package/v3/dist/coordination/mincut/queen-integration.js.map +1 -1
  60. package/v3/dist/coordination/queen-coordinator.d.ts +5 -0
  61. package/v3/dist/coordination/queen-coordinator.d.ts.map +1 -1
  62. package/v3/dist/coordination/queen-coordinator.js +45 -7
  63. package/v3/dist/coordination/queen-coordinator.js.map +1 -1
  64. package/v3/dist/domains/learning-optimization/coordinator.d.ts +5 -0
  65. package/v3/dist/domains/learning-optimization/coordinator.d.ts.map +1 -1
  66. package/v3/dist/domains/learning-optimization/coordinator.js +79 -0
  67. package/v3/dist/domains/learning-optimization/coordinator.js.map +1 -1
  68. package/v3/dist/domains/test-generation/coherence-gate.d.ts +245 -0
  69. package/v3/dist/domains/test-generation/coherence-gate.d.ts.map +1 -0
  70. package/v3/dist/domains/test-generation/coherence-gate.js +454 -0
  71. package/v3/dist/domains/test-generation/coherence-gate.js.map +1 -0
  72. package/v3/dist/domains/test-generation/coordinator.d.ts +32 -1
  73. package/v3/dist/domains/test-generation/coordinator.d.ts.map +1 -1
  74. package/v3/dist/domains/test-generation/coordinator.js +70 -1
  75. package/v3/dist/domains/test-generation/coordinator.js.map +1 -1
  76. package/v3/dist/domains/test-generation/index.d.ts +1 -0
  77. package/v3/dist/domains/test-generation/index.d.ts.map +1 -1
  78. package/v3/dist/domains/test-generation/index.js +4 -0
  79. package/v3/dist/domains/test-generation/index.js.map +1 -1
  80. package/v3/dist/domains/test-generation/services/index.d.ts +1 -0
  81. package/v3/dist/domains/test-generation/services/index.d.ts.map +1 -1
  82. package/v3/dist/domains/test-generation/services/index.js +2 -0
  83. package/v3/dist/domains/test-generation/services/index.js.map +1 -1
  84. package/v3/dist/domains/visual-accessibility/index.d.ts +2 -1
  85. package/v3/dist/domains/visual-accessibility/index.d.ts.map +1 -1
  86. package/v3/dist/domains/visual-accessibility/index.js +1 -0
  87. package/v3/dist/domains/visual-accessibility/index.js.map +1 -1
  88. package/v3/dist/domains/visual-accessibility/interfaces.d.ts +131 -0
  89. package/v3/dist/domains/visual-accessibility/interfaces.d.ts.map +1 -1
  90. package/v3/dist/domains/visual-accessibility/plugin.d.ts +26 -0
  91. package/v3/dist/domains/visual-accessibility/plugin.d.ts.map +1 -1
  92. package/v3/dist/domains/visual-accessibility/plugin.js +151 -0
  93. package/v3/dist/domains/visual-accessibility/plugin.js.map +1 -1
  94. package/v3/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +42 -1
  95. package/v3/dist/domains/visual-accessibility/services/accessibility-tester.d.ts.map +1 -1
  96. package/v3/dist/domains/visual-accessibility/services/accessibility-tester.js +69 -0
  97. package/v3/dist/domains/visual-accessibility/services/accessibility-tester.js.map +1 -1
  98. package/v3/dist/domains/visual-accessibility/services/eu-compliance.d.ts +138 -0
  99. package/v3/dist/domains/visual-accessibility/services/eu-compliance.d.ts.map +1 -0
  100. package/v3/dist/domains/visual-accessibility/services/eu-compliance.js +830 -0
  101. package/v3/dist/domains/visual-accessibility/services/eu-compliance.js.map +1 -0
  102. package/v3/dist/domains/visual-accessibility/services/index.d.ts +1 -0
  103. package/v3/dist/domains/visual-accessibility/services/index.d.ts.map +1 -1
  104. package/v3/dist/domains/visual-accessibility/services/index.js +1 -0
  105. package/v3/dist/domains/visual-accessibility/services/index.js.map +1 -1
  106. package/v3/dist/init/enhancements/claude-flow-adapter.d.ts +84 -0
  107. package/v3/dist/init/enhancements/claude-flow-adapter.d.ts.map +1 -0
  108. package/v3/dist/init/enhancements/claude-flow-adapter.js +250 -0
  109. package/v3/dist/init/enhancements/claude-flow-adapter.js.map +1 -0
  110. package/v3/dist/init/enhancements/detector.d.ts +10 -0
  111. package/v3/dist/init/enhancements/detector.d.ts.map +1 -0
  112. package/v3/dist/init/enhancements/detector.js +87 -0
  113. package/v3/dist/init/enhancements/detector.js.map +1 -0
  114. package/v3/dist/init/enhancements/index.d.ts +13 -0
  115. package/v3/dist/init/enhancements/index.d.ts.map +1 -0
  116. package/v3/dist/init/enhancements/index.js +25 -0
  117. package/v3/dist/init/enhancements/index.js.map +1 -0
  118. package/v3/dist/init/enhancements/types.d.ts +93 -0
  119. package/v3/dist/init/enhancements/types.d.ts.map +1 -0
  120. package/v3/dist/init/enhancements/types.js +6 -0
  121. package/v3/dist/init/enhancements/types.js.map +1 -0
  122. package/v3/dist/init/index.d.ts +8 -0
  123. package/v3/dist/init/index.d.ts.map +1 -1
  124. package/v3/dist/init/index.js +4 -0
  125. package/v3/dist/init/index.js.map +1 -1
  126. package/v3/dist/init/migration/config-migrator.d.ts +31 -0
  127. package/v3/dist/init/migration/config-migrator.d.ts.map +1 -0
  128. package/v3/dist/init/migration/config-migrator.js +133 -0
  129. package/v3/dist/init/migration/config-migrator.js.map +1 -0
  130. package/v3/dist/init/migration/data-migrator.d.ts +72 -0
  131. package/v3/dist/init/migration/data-migrator.d.ts.map +1 -0
  132. package/v3/dist/init/migration/data-migrator.js +233 -0
  133. package/v3/dist/init/migration/data-migrator.js.map +1 -0
  134. package/v3/dist/init/migration/detector.d.ts +44 -0
  135. package/v3/dist/init/migration/detector.d.ts.map +1 -0
  136. package/v3/dist/init/migration/detector.js +106 -0
  137. package/v3/dist/init/migration/detector.js.map +1 -0
  138. package/v3/dist/init/migration/index.d.ts +8 -0
  139. package/v3/dist/init/migration/index.d.ts.map +1 -0
  140. package/v3/dist/init/migration/index.js +8 -0
  141. package/v3/dist/init/migration/index.js.map +1 -0
  142. package/v3/dist/init/orchestrator.d.ts +68 -0
  143. package/v3/dist/init/orchestrator.d.ts.map +1 -0
  144. package/v3/dist/init/orchestrator.js +239 -0
  145. package/v3/dist/init/orchestrator.js.map +1 -0
  146. package/v3/dist/init/phases/01-detection.d.ts +30 -0
  147. package/v3/dist/init/phases/01-detection.d.ts.map +1 -0
  148. package/v3/dist/init/phases/01-detection.js +143 -0
  149. package/v3/dist/init/phases/01-detection.js.map +1 -0
  150. package/v3/dist/init/phases/02-analysis.d.ts +18 -0
  151. package/v3/dist/init/phases/02-analysis.d.ts.map +1 -0
  152. package/v3/dist/init/phases/02-analysis.js +28 -0
  153. package/v3/dist/init/phases/02-analysis.js.map +1 -0
  154. package/v3/dist/init/phases/03-configuration.d.ts +26 -0
  155. package/v3/dist/init/phases/03-configuration.d.ts.map +1 -0
  156. package/v3/dist/init/phases/03-configuration.js +98 -0
  157. package/v3/dist/init/phases/03-configuration.js.map +1 -0
  158. package/v3/dist/init/phases/04-database.d.ts +22 -0
  159. package/v3/dist/init/phases/04-database.d.ts.map +1 -0
  160. package/v3/dist/init/phases/04-database.js +88 -0
  161. package/v3/dist/init/phases/04-database.js.map +1 -0
  162. package/v3/dist/init/phases/05-learning.d.ts +28 -0
  163. package/v3/dist/init/phases/05-learning.d.ts.map +1 -0
  164. package/v3/dist/init/phases/05-learning.js +98 -0
  165. package/v3/dist/init/phases/05-learning.js.map +1 -0
  166. package/v3/dist/init/phases/06-code-intelligence.d.ts +33 -0
  167. package/v3/dist/init/phases/06-code-intelligence.d.ts.map +1 -0
  168. package/v3/dist/init/phases/06-code-intelligence.js +115 -0
  169. package/v3/dist/init/phases/06-code-intelligence.js.map +1 -0
  170. package/v3/dist/init/phases/07-hooks.d.ts +27 -0
  171. package/v3/dist/init/phases/07-hooks.d.ts.map +1 -0
  172. package/v3/dist/init/phases/07-hooks.js +209 -0
  173. package/v3/dist/init/phases/07-hooks.js.map +1 -0
  174. package/v3/dist/init/phases/08-mcp.d.ts +22 -0
  175. package/v3/dist/init/phases/08-mcp.d.ts.map +1 -0
  176. package/v3/dist/init/phases/08-mcp.js +62 -0
  177. package/v3/dist/init/phases/08-mcp.js.map +1 -0
  178. package/v3/dist/init/phases/09-assets.d.ts +23 -0
  179. package/v3/dist/init/phases/09-assets.d.ts.map +1 -0
  180. package/v3/dist/init/phases/09-assets.js +82 -0
  181. package/v3/dist/init/phases/09-assets.js.map +1 -0
  182. package/v3/dist/init/phases/10-workers.d.ts +23 -0
  183. package/v3/dist/init/phases/10-workers.d.ts.map +1 -0
  184. package/v3/dist/init/phases/10-workers.js +111 -0
  185. package/v3/dist/init/phases/10-workers.js.map +1 -0
  186. package/v3/dist/init/phases/11-claude-md.d.ts +26 -0
  187. package/v3/dist/init/phases/11-claude-md.d.ts.map +1 -0
  188. package/v3/dist/init/phases/11-claude-md.js +121 -0
  189. package/v3/dist/init/phases/11-claude-md.js.map +1 -0
  190. package/v3/dist/init/phases/12-verification.d.ts +38 -0
  191. package/v3/dist/init/phases/12-verification.d.ts.map +1 -0
  192. package/v3/dist/init/phases/12-verification.js +187 -0
  193. package/v3/dist/init/phases/12-verification.js.map +1 -0
  194. package/v3/dist/init/phases/index.d.ts +46 -0
  195. package/v3/dist/init/phases/index.d.ts.map +1 -0
  196. package/v3/dist/init/phases/index.js +64 -0
  197. package/v3/dist/init/phases/index.js.map +1 -0
  198. package/v3/dist/init/phases/phase-interface.d.ts +193 -0
  199. package/v3/dist/init/phases/phase-interface.d.ts.map +1 -0
  200. package/v3/dist/init/phases/phase-interface.js +119 -0
  201. package/v3/dist/init/phases/phase-interface.js.map +1 -0
  202. package/v3/dist/integrations/coherence/coherence-service.d.ts +323 -0
  203. package/v3/dist/integrations/coherence/coherence-service.d.ts.map +1 -0
  204. package/v3/dist/integrations/coherence/coherence-service.js +799 -0
  205. package/v3/dist/integrations/coherence/coherence-service.js.map +1 -0
  206. package/v3/dist/integrations/coherence/engines/category-adapter.d.ts +170 -0
  207. package/v3/dist/integrations/coherence/engines/category-adapter.d.ts.map +1 -0
  208. package/v3/dist/integrations/coherence/engines/category-adapter.js +403 -0
  209. package/v3/dist/integrations/coherence/engines/category-adapter.js.map +1 -0
  210. package/v3/dist/integrations/coherence/engines/causal-adapter.d.ts +159 -0
  211. package/v3/dist/integrations/coherence/engines/causal-adapter.d.ts.map +1 -0
  212. package/v3/dist/integrations/coherence/engines/causal-adapter.js +348 -0
  213. package/v3/dist/integrations/coherence/engines/causal-adapter.js.map +1 -0
  214. package/v3/dist/integrations/coherence/engines/cohomology-adapter.d.ts +174 -0
  215. package/v3/dist/integrations/coherence/engines/cohomology-adapter.d.ts.map +1 -0
  216. package/v3/dist/integrations/coherence/engines/cohomology-adapter.js +401 -0
  217. package/v3/dist/integrations/coherence/engines/cohomology-adapter.js.map +1 -0
  218. package/v3/dist/integrations/coherence/engines/homotopy-adapter.d.ts +201 -0
  219. package/v3/dist/integrations/coherence/engines/homotopy-adapter.d.ts.map +1 -0
  220. package/v3/dist/integrations/coherence/engines/homotopy-adapter.js +324 -0
  221. package/v3/dist/integrations/coherence/engines/homotopy-adapter.js.map +1 -0
  222. package/v3/dist/integrations/coherence/engines/index.d.ts +20 -0
  223. package/v3/dist/integrations/coherence/engines/index.d.ts.map +1 -0
  224. package/v3/dist/integrations/coherence/engines/index.js +26 -0
  225. package/v3/dist/integrations/coherence/engines/index.js.map +1 -0
  226. package/v3/dist/integrations/coherence/engines/spectral-adapter.d.ts +193 -0
  227. package/v3/dist/integrations/coherence/engines/spectral-adapter.d.ts.map +1 -0
  228. package/v3/dist/integrations/coherence/engines/spectral-adapter.js +476 -0
  229. package/v3/dist/integrations/coherence/engines/spectral-adapter.js.map +1 -0
  230. package/v3/dist/integrations/coherence/engines/witness-adapter.d.ts +175 -0
  231. package/v3/dist/integrations/coherence/engines/witness-adapter.d.ts.map +1 -0
  232. package/v3/dist/integrations/coherence/engines/witness-adapter.js +377 -0
  233. package/v3/dist/integrations/coherence/engines/witness-adapter.js.map +1 -0
  234. package/v3/dist/integrations/coherence/index.d.ts +84 -0
  235. package/v3/dist/integrations/coherence/index.d.ts.map +1 -0
  236. package/v3/dist/integrations/coherence/index.js +114 -0
  237. package/v3/dist/integrations/coherence/index.js.map +1 -0
  238. package/v3/dist/integrations/coherence/threshold-tuner.d.ts +396 -0
  239. package/v3/dist/integrations/coherence/threshold-tuner.d.ts.map +1 -0
  240. package/v3/dist/integrations/coherence/threshold-tuner.js +538 -0
  241. package/v3/dist/integrations/coherence/threshold-tuner.js.map +1 -0
  242. package/v3/dist/integrations/coherence/types.d.ts +879 -0
  243. package/v3/dist/integrations/coherence/types.d.ts.map +1 -0
  244. package/v3/dist/integrations/coherence/types.js +134 -0
  245. package/v3/dist/integrations/coherence/types.js.map +1 -0
  246. package/v3/dist/integrations/coherence/wasm-loader.d.ts +351 -0
  247. package/v3/dist/integrations/coherence/wasm-loader.d.ts.map +1 -0
  248. package/v3/dist/integrations/coherence/wasm-loader.js +842 -0
  249. package/v3/dist/integrations/coherence/wasm-loader.js.map +1 -0
  250. package/v3/dist/integrations/embeddings/index/HNSWIndex.d.ts.map +1 -1
  251. package/v3/dist/integrations/embeddings/index/HNSWIndex.js +4 -1
  252. package/v3/dist/integrations/embeddings/index/HNSWIndex.js.map +1 -1
  253. package/v3/dist/kernel/interfaces.d.ts +8 -1
  254. package/v3/dist/kernel/interfaces.d.ts.map +1 -1
  255. package/v3/dist/learning/aqe-learning-engine.d.ts +272 -0
  256. package/v3/dist/learning/aqe-learning-engine.d.ts.map +1 -0
  257. package/v3/dist/learning/aqe-learning-engine.js +708 -0
  258. package/v3/dist/learning/aqe-learning-engine.js.map +1 -0
  259. package/v3/dist/learning/causal-verifier.d.ts +244 -0
  260. package/v3/dist/learning/causal-verifier.d.ts.map +1 -0
  261. package/v3/dist/learning/causal-verifier.js +300 -0
  262. package/v3/dist/learning/causal-verifier.js.map +1 -0
  263. package/v3/dist/learning/experience-capture.d.ts +266 -0
  264. package/v3/dist/learning/experience-capture.d.ts.map +1 -0
  265. package/v3/dist/learning/experience-capture.js +647 -0
  266. package/v3/dist/learning/experience-capture.js.map +1 -0
  267. package/v3/dist/learning/index.d.ts +8 -0
  268. package/v3/dist/learning/index.d.ts.map +1 -1
  269. package/v3/dist/learning/index.js +16 -0
  270. package/v3/dist/learning/index.js.map +1 -1
  271. package/v3/dist/learning/memory-auditor.d.ts +235 -0
  272. package/v3/dist/learning/memory-auditor.d.ts.map +1 -0
  273. package/v3/dist/learning/memory-auditor.js +478 -0
  274. package/v3/dist/learning/memory-auditor.js.map +1 -0
  275. package/v3/dist/learning/pattern-store.d.ts.map +1 -1
  276. package/v3/dist/learning/pattern-store.js +27 -6
  277. package/v3/dist/learning/pattern-store.js.map +1 -1
  278. package/v3/dist/learning/qe-patterns.d.ts +15 -1
  279. package/v3/dist/learning/qe-patterns.d.ts.map +1 -1
  280. package/v3/dist/learning/qe-patterns.js +26 -5
  281. package/v3/dist/learning/qe-patterns.js.map +1 -1
  282. package/v3/dist/learning/qe-reasoning-bank.d.ts +38 -2
  283. package/v3/dist/learning/qe-reasoning-bank.d.ts.map +1 -1
  284. package/v3/dist/learning/qe-reasoning-bank.js +86 -4
  285. package/v3/dist/learning/qe-reasoning-bank.js.map +1 -1
  286. package/v3/dist/learning/real-qe-reasoning-bank.d.ts +32 -2
  287. package/v3/dist/learning/real-qe-reasoning-bank.d.ts.map +1 -1
  288. package/v3/dist/learning/real-qe-reasoning-bank.js +61 -6
  289. package/v3/dist/learning/real-qe-reasoning-bank.js.map +1 -1
  290. package/v3/dist/mcp/bundle.js +6303 -266
  291. package/v3/dist/mcp/tools/coherence/audit.d.ts +107 -0
  292. package/v3/dist/mcp/tools/coherence/audit.d.ts.map +1 -0
  293. package/v3/dist/mcp/tools/coherence/audit.js +236 -0
  294. package/v3/dist/mcp/tools/coherence/audit.js.map +1 -0
  295. package/v3/dist/mcp/tools/coherence/check.d.ts +106 -0
  296. package/v3/dist/mcp/tools/coherence/check.d.ts.map +1 -0
  297. package/v3/dist/mcp/tools/coherence/check.js +205 -0
  298. package/v3/dist/mcp/tools/coherence/check.js.map +1 -0
  299. package/v3/dist/mcp/tools/coherence/collapse.d.ts +123 -0
  300. package/v3/dist/mcp/tools/coherence/collapse.d.ts.map +1 -0
  301. package/v3/dist/mcp/tools/coherence/collapse.js +279 -0
  302. package/v3/dist/mcp/tools/coherence/collapse.js.map +1 -0
  303. package/v3/dist/mcp/tools/coherence/consensus.d.ts +100 -0
  304. package/v3/dist/mcp/tools/coherence/consensus.d.ts.map +1 -0
  305. package/v3/dist/mcp/tools/coherence/consensus.js +201 -0
  306. package/v3/dist/mcp/tools/coherence/consensus.js.map +1 -0
  307. package/v3/dist/mcp/tools/coherence/index.d.ts +31 -0
  308. package/v3/dist/mcp/tools/coherence/index.d.ts.map +1 -0
  309. package/v3/dist/mcp/tools/coherence/index.js +42 -0
  310. package/v3/dist/mcp/tools/coherence/index.js.map +1 -0
  311. package/v3/dist/mcp/tools/index.d.ts +6 -1
  312. package/v3/dist/mcp/tools/index.d.ts.map +1 -1
  313. package/v3/dist/mcp/tools/index.js +9 -1
  314. package/v3/dist/mcp/tools/index.js.map +1 -1
  315. package/v3/dist/mcp/tools/mincut/index.d.ts +1 -1
  316. package/v3/dist/mcp/tools/mincut/index.d.ts.map +1 -1
  317. package/v3/dist/mcp/tools/mincut/index.js.map +1 -1
  318. package/v3/dist/mcp/tools/registry.d.ts +4 -0
  319. package/v3/dist/mcp/tools/registry.d.ts.map +1 -1
  320. package/v3/dist/mcp/tools/registry.js +5 -0
  321. package/v3/dist/mcp/tools/registry.js.map +1 -1
  322. package/v3/dist/mcp/types.d.ts +1 -1
  323. package/v3/dist/mcp/types.d.ts.map +1 -1
  324. package/v3/dist/strange-loop/belief-reconciler.d.ts +357 -0
  325. package/v3/dist/strange-loop/belief-reconciler.d.ts.map +1 -0
  326. package/v3/dist/strange-loop/belief-reconciler.js +696 -0
  327. package/v3/dist/strange-loop/belief-reconciler.js.map +1 -0
  328. package/v3/dist/strange-loop/index.d.ts +1 -0
  329. package/v3/dist/strange-loop/index.d.ts.map +1 -1
  330. package/v3/dist/strange-loop/index.js +2 -0
  331. package/v3/dist/strange-loop/index.js.map +1 -1
  332. package/v3/dist/strange-loop/strange-loop.d.ts +177 -5
  333. package/v3/dist/strange-loop/strange-loop.d.ts.map +1 -1
  334. package/v3/dist/strange-loop/strange-loop.js +452 -9
  335. package/v3/dist/strange-loop/strange-loop.js.map +1 -1
  336. package/v3/dist/strange-loop/types.d.ts +205 -1
  337. package/v3/dist/strange-loop/types.d.ts.map +1 -1
  338. package/v3/dist/strange-loop/types.js +5 -0
  339. package/v3/dist/strange-loop/types.js.map +1 -1
  340. package/v3/package.json +5 -1
@@ -0,0 +1,799 @@
1
+ /**
2
+ * Agentic QE v3 - Coherence Service
3
+ *
4
+ * Main facade that wraps all 6 Prime Radiant engines for coherence verification.
5
+ * Provides mathematical coherence gates for multi-agent coordination.
6
+ *
7
+ * **Architecture Overview:**
8
+ * ```
9
+ * ┌─────────────────────────────────────────────────────────────────────┐
10
+ * │ AQE v3 COHERENCE ARCHITECTURE │
11
+ * ├─────────────────────────────────────────────────────────────────────┤
12
+ * │ │
13
+ * │ ┌────────────────┐ ┌─────────────────────┐ ┌────────────┐ │
14
+ * │ │ QE Agent │────▶│ COHERENCE GATE │────▶│ Execution │ │
15
+ * │ │ Decision │ │ (Prime Radiant) │ │ Layer │ │
16
+ * │ └────────────────┘ └─────────────────────┘ └────────────┘ │
17
+ * │ │ │
18
+ * │ ┌───────────┼───────────┐ │
19
+ * │ ▼ ▼ ▼ │
20
+ * │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
21
+ * │ │ REFLEX │ │ RETRIEVAL│ │ ESCALATE │ │
22
+ * │ │ E < 0.1 │ │ E: 0.1-0.4│ │ E > 0.4 │ │
23
+ * │ │ <1ms │ │ ~10ms │ │ Queen │ │
24
+ * │ └──────────┘ └──────────┘ └──────────┘ │
25
+ * │ │
26
+ * └─────────────────────────────────────────────────────────────────────┘
27
+ * ```
28
+ *
29
+ * @module integrations/coherence/coherence-service
30
+ */
31
+ import { DEFAULT_COHERENCE_CONFIG, DEFAULT_COHERENCE_LOGGER, WasmNotLoadedError, CoherenceError, } from './types';
32
+ import { CohomologyAdapter, SpectralAdapter, CausalAdapter, CategoryAdapter, HomotopyAdapter, WitnessAdapter, } from './engines';
33
+ // ============================================================================
34
+ // Coherence Service Implementation
35
+ // ============================================================================
36
+ /**
37
+ * Main Coherence Service implementation
38
+ *
39
+ * Provides a unified interface to all 6 Prime Radiant engines:
40
+ * 1. CohomologyEngine - Sheaf cohomology for contradiction detection
41
+ * 2. SpectralEngine - Spectral analysis for collapse prediction
42
+ * 3. CausalEngine - Causal inference for spurious correlation detection
43
+ * 4. CategoryEngine - Category theory for type verification
44
+ * 5. HomotopyEngine - HoTT for formal verification
45
+ * 6. WitnessEngine - Blake3 witness chains for audit trails
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const service = new CoherenceService(wasmLoader);
50
+ * await service.initialize();
51
+ *
52
+ * // Check coherence
53
+ * const result = await service.checkCoherence(nodes);
54
+ * if (!result.isCoherent) {
55
+ * console.log('Contradictions found:', result.contradictions);
56
+ * }
57
+ *
58
+ * // Route based on lane
59
+ * switch (result.lane) {
60
+ * case 'reflex': return executeImmediately();
61
+ * case 'retrieval': return fetchContextAndRetry();
62
+ * case 'heavy': return deepAnalysis();
63
+ * case 'human': return escalateToQueen();
64
+ * }
65
+ * ```
66
+ */
67
+ export class CoherenceService {
68
+ wasmLoader;
69
+ config;
70
+ logger;
71
+ // Engine adapters
72
+ cohomologyAdapter = null;
73
+ spectralAdapter = null;
74
+ causalAdapter = null;
75
+ categoryAdapter = null;
76
+ homotopyAdapter = null;
77
+ witnessAdapter = null;
78
+ initialized = false;
79
+ // Statistics
80
+ stats = {
81
+ totalChecks: 0,
82
+ coherentCount: 0,
83
+ incoherentCount: 0,
84
+ averageEnergy: 0,
85
+ averageDurationMs: 0,
86
+ totalContradictions: 0,
87
+ laneDistribution: { reflex: 0, retrieval: 0, heavy: 0, human: 0 },
88
+ fallbackCount: 0,
89
+ wasmAvailable: false,
90
+ };
91
+ totalEnergySum = 0;
92
+ totalDurationSum = 0;
93
+ /**
94
+ * Create a new CoherenceService
95
+ *
96
+ * @param wasmLoader - WASM module loader (dependency injection)
97
+ * @param config - Optional service configuration
98
+ * @param logger - Optional logger for diagnostics
99
+ */
100
+ constructor(wasmLoader, config = {}, logger) {
101
+ this.wasmLoader = wasmLoader;
102
+ this.config = { ...DEFAULT_COHERENCE_CONFIG, ...config };
103
+ this.logger = logger || DEFAULT_COHERENCE_LOGGER;
104
+ }
105
+ /**
106
+ * Initialize the service by loading all WASM modules
107
+ */
108
+ async initialize() {
109
+ if (this.initialized)
110
+ return;
111
+ this.logger.info('Initializing CoherenceService');
112
+ const isAvailable = await this.wasmLoader.isAvailable();
113
+ if (!isAvailable && !this.config.fallbackEnabled) {
114
+ throw new WasmNotLoadedError('WASM module is not available and fallback is disabled. ' +
115
+ 'Enable fallbackEnabled in config to use TypeScript fallback.');
116
+ }
117
+ this.stats.wasmAvailable = isAvailable;
118
+ if (isAvailable) {
119
+ // Initialize all adapters
120
+ try {
121
+ this.cohomologyAdapter = new CohomologyAdapter(this.wasmLoader, this.logger);
122
+ this.spectralAdapter = new SpectralAdapter(this.wasmLoader, this.logger);
123
+ this.causalAdapter = new CausalAdapter(this.wasmLoader, this.logger);
124
+ this.categoryAdapter = new CategoryAdapter(this.wasmLoader, this.logger);
125
+ this.homotopyAdapter = new HomotopyAdapter(this.wasmLoader, this.logger);
126
+ this.witnessAdapter = new WitnessAdapter(this.wasmLoader, this.logger);
127
+ // Initialize all adapters in parallel
128
+ await Promise.all([
129
+ this.cohomologyAdapter.initialize(),
130
+ this.spectralAdapter.initialize(),
131
+ this.causalAdapter.initialize(),
132
+ this.categoryAdapter.initialize(),
133
+ this.homotopyAdapter.initialize(),
134
+ this.witnessAdapter.initialize(),
135
+ ]);
136
+ this.logger.info('All coherence engine adapters initialized');
137
+ }
138
+ catch (error) {
139
+ if (!this.config.fallbackEnabled) {
140
+ throw error;
141
+ }
142
+ this.logger.warn('WASM initialization failed, using fallback', {
143
+ error: error instanceof Error ? error.message : 'Unknown error',
144
+ });
145
+ this.stats.wasmAvailable = false;
146
+ }
147
+ }
148
+ else {
149
+ this.logger.info('WASM not available, using TypeScript fallback');
150
+ }
151
+ this.initialized = true;
152
+ this.logger.info('CoherenceService initialized', {
153
+ wasmAvailable: this.stats.wasmAvailable,
154
+ fallbackEnabled: this.config.fallbackEnabled,
155
+ });
156
+ }
157
+ /**
158
+ * Check if the service is initialized
159
+ */
160
+ isInitialized() {
161
+ return this.initialized;
162
+ }
163
+ /**
164
+ * Ensure the service is initialized
165
+ */
166
+ ensureInitialized() {
167
+ if (!this.initialized) {
168
+ throw new CoherenceError('CoherenceService not initialized. Call initialize() first.', 'NOT_INITIALIZED');
169
+ }
170
+ }
171
+ /**
172
+ * Check coherence of a set of nodes
173
+ */
174
+ async checkCoherence(nodes) {
175
+ this.ensureInitialized();
176
+ const startTime = Date.now();
177
+ try {
178
+ // Use WASM adapter if available
179
+ const adapterInitialized = this.cohomologyAdapter?.isInitialized();
180
+ if (adapterInitialized) {
181
+ return await this.checkCoherenceWithWasm(nodes, startTime);
182
+ }
183
+ // Fallback to TypeScript implementation
184
+ return this.checkCoherenceWithFallback(nodes, startTime);
185
+ }
186
+ catch (error) {
187
+ this.logger.error('Coherence check failed', error instanceof Error ? error : new Error(String(error)));
188
+ // Return safe fallback result
189
+ return {
190
+ energy: 1.0, // High energy = incoherent
191
+ isCoherent: false,
192
+ lane: 'human',
193
+ contradictions: [],
194
+ recommendations: ['Coherence check failed. Manual review recommended.'],
195
+ durationMs: Date.now() - startTime,
196
+ usedFallback: true,
197
+ };
198
+ }
199
+ }
200
+ /**
201
+ * Check coherence using WASM adapter
202
+ */
203
+ async checkCoherenceWithWasm(nodes, startTime) {
204
+ // Clear and rebuild graph
205
+ this.cohomologyAdapter.clear();
206
+ // Add all nodes
207
+ for (const node of nodes) {
208
+ this.cohomologyAdapter.addNode(node);
209
+ }
210
+ // Add edges based on similarity
211
+ this.buildEdgesFromNodes(nodes);
212
+ // Compute energy and detect contradictions
213
+ const energy = this.cohomologyAdapter.computeEnergy();
214
+ const contradictions = this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold);
215
+ const lane = this.computeLane(energy);
216
+ const durationMs = Date.now() - startTime;
217
+ // Update statistics
218
+ this.updateStats(energy, durationMs, contradictions.length, lane, false);
219
+ return {
220
+ energy,
221
+ isCoherent: energy < this.config.coherenceThreshold,
222
+ lane,
223
+ contradictions,
224
+ recommendations: this.generateRecommendations(energy, lane, contradictions),
225
+ durationMs,
226
+ usedFallback: false,
227
+ };
228
+ }
229
+ /**
230
+ * Check coherence using TypeScript fallback
231
+ */
232
+ checkCoherenceWithFallback(nodes, startTime) {
233
+ this.stats.fallbackCount++;
234
+ // Simple fallback: compute average pairwise distance
235
+ let totalDistance = 0;
236
+ let comparisons = 0;
237
+ const contradictions = [];
238
+ for (let i = 0; i < nodes.length; i++) {
239
+ for (let j = i + 1; j < nodes.length; j++) {
240
+ const distance = this.euclideanDistance(nodes[i].embedding, nodes[j].embedding);
241
+ totalDistance += distance;
242
+ comparisons++;
243
+ // Detect contradictions based on distance
244
+ if (distance > 1.5) {
245
+ contradictions.push({
246
+ nodeIds: [nodes[i].id, nodes[j].id],
247
+ severity: distance > 2 ? 'critical' : 'high',
248
+ description: `High distance (${distance.toFixed(2)}) between nodes`,
249
+ confidence: Math.min(1, distance / 2),
250
+ });
251
+ }
252
+ }
253
+ }
254
+ const energy = comparisons > 0 ? totalDistance / comparisons : 0;
255
+ const lane = this.computeLane(energy);
256
+ const durationMs = Date.now() - startTime;
257
+ this.updateStats(energy, durationMs, contradictions.length, lane, true);
258
+ return {
259
+ energy,
260
+ isCoherent: energy < this.config.coherenceThreshold,
261
+ lane,
262
+ contradictions,
263
+ recommendations: this.generateRecommendations(energy, lane, contradictions),
264
+ durationMs,
265
+ usedFallback: true,
266
+ };
267
+ }
268
+ /**
269
+ * Build edges between nodes based on similarity
270
+ */
271
+ buildEdgesFromNodes(nodes) {
272
+ for (let i = 0; i < nodes.length; i++) {
273
+ for (let j = i + 1; j < nodes.length; j++) {
274
+ const similarity = this.cosineSimilarity(nodes[i].embedding, nodes[j].embedding);
275
+ // Only add edges for sufficiently similar nodes
276
+ if (similarity > 0.3) {
277
+ this.cohomologyAdapter.addEdge({
278
+ source: nodes[i].id,
279
+ target: nodes[j].id,
280
+ weight: similarity,
281
+ });
282
+ }
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * Detect contradictions in beliefs
288
+ */
289
+ async detectContradictions(beliefs) {
290
+ this.ensureInitialized();
291
+ // Convert beliefs to coherence nodes
292
+ const nodes = beliefs.map(belief => ({
293
+ id: belief.id,
294
+ embedding: belief.embedding,
295
+ weight: belief.confidence,
296
+ metadata: {
297
+ statement: belief.statement,
298
+ source: belief.source,
299
+ },
300
+ }));
301
+ const result = await this.checkCoherence(nodes);
302
+ return result.contradictions;
303
+ }
304
+ /**
305
+ * Predict collapse risk for a swarm
306
+ */
307
+ async predictCollapse(state) {
308
+ this.ensureInitialized();
309
+ if (this.spectralAdapter?.isInitialized()) {
310
+ return this.spectralAdapter.analyzeSwarmState(state);
311
+ }
312
+ // Fallback implementation
313
+ return this.predictCollapseWithFallback(state);
314
+ }
315
+ /**
316
+ * Fallback collapse prediction using simple heuristics
317
+ */
318
+ predictCollapseWithFallback(state) {
319
+ const startTime = Date.now();
320
+ // Simple heuristics
321
+ const avgHealth = state.agents.reduce((sum, a) => sum + a.health, 0) /
322
+ Math.max(state.agents.length, 1);
323
+ const avgSuccessRate = state.agents.reduce((sum, a) => sum + a.successRate, 0) /
324
+ Math.max(state.agents.length, 1);
325
+ // Risk factors
326
+ let risk = 0;
327
+ risk += (1 - avgHealth) * 0.3;
328
+ risk += (1 - avgSuccessRate) * 0.3;
329
+ risk += state.errorRate * 0.2;
330
+ risk += (state.utilization > 0.9 ? 0.2 : state.utilization * 0.1);
331
+ // Identify weak agents
332
+ const weakVertices = state.agents
333
+ .filter(a => a.health < 0.5 || a.successRate < 0.5)
334
+ .map(a => a.agentId);
335
+ return {
336
+ risk: Math.min(1, risk),
337
+ fiedlerValue: avgHealth * avgSuccessRate, // Approximation
338
+ collapseImminent: risk > 0.7,
339
+ weakVertices,
340
+ recommendations: risk > 0.5
341
+ ? ['System health degraded. Consider spawning additional agents.']
342
+ : ['System health is acceptable.'],
343
+ durationMs: Date.now() - startTime,
344
+ usedFallback: true,
345
+ };
346
+ }
347
+ /**
348
+ * Verify a causal relationship
349
+ */
350
+ async verifyCausality(cause, effect, data) {
351
+ this.ensureInitialized();
352
+ if (this.causalAdapter?.isInitialized()) {
353
+ return this.causalAdapter.verifyCausality(cause, effect, data);
354
+ }
355
+ // Fallback: simple correlation analysis
356
+ return this.verifyCausalityWithFallback(cause, effect, data);
357
+ }
358
+ /**
359
+ * Fallback causality verification using correlation
360
+ */
361
+ verifyCausalityWithFallback(cause, effect, data) {
362
+ const startTime = Date.now();
363
+ // Compute correlation coefficient
364
+ const correlation = this.computeCorrelation(data.causeValues, data.effectValues);
365
+ const absCorrelation = Math.abs(correlation);
366
+ return {
367
+ isCausal: absCorrelation > 0.5,
368
+ effectStrength: absCorrelation,
369
+ relationshipType: absCorrelation < 0.2 ? 'none' :
370
+ absCorrelation > 0.5 ? 'causal' : 'spurious',
371
+ confidence: Math.min(0.7, data.sampleSize / 100), // Lower confidence for fallback
372
+ confounders: [],
373
+ explanation: `Correlation-based analysis: r=${correlation.toFixed(3)}. ` +
374
+ 'Note: Correlation does not imply causation. ' +
375
+ 'This is a fallback analysis without full causal inference.',
376
+ durationMs: Date.now() - startTime,
377
+ usedFallback: true,
378
+ };
379
+ }
380
+ /**
381
+ * Verify type consistency in a pipeline
382
+ */
383
+ async verifyTypes(pipeline) {
384
+ this.ensureInitialized();
385
+ if (this.categoryAdapter?.isInitialized()) {
386
+ return this.categoryAdapter.verifyPipeline(pipeline);
387
+ }
388
+ // Fallback: simple type matching
389
+ return this.verifyTypesWithFallback(pipeline);
390
+ }
391
+ /**
392
+ * Fallback type verification using simple matching
393
+ */
394
+ verifyTypesWithFallback(pipeline) {
395
+ const startTime = Date.now();
396
+ const mismatches = [];
397
+ // Check that elements chain correctly
398
+ let currentType = pipeline.inputType;
399
+ for (const element of pipeline.elements) {
400
+ if (element.inputType !== currentType && currentType !== 'any') {
401
+ mismatches.push({
402
+ location: element.name,
403
+ expected: currentType,
404
+ actual: element.inputType,
405
+ severity: 'high',
406
+ });
407
+ }
408
+ currentType = element.outputType;
409
+ }
410
+ // Check final output
411
+ if (currentType !== pipeline.outputType && currentType !== 'any') {
412
+ mismatches.push({
413
+ location: 'pipeline output',
414
+ expected: pipeline.outputType,
415
+ actual: currentType,
416
+ severity: 'critical',
417
+ });
418
+ }
419
+ return {
420
+ isValid: mismatches.length === 0,
421
+ mismatches,
422
+ warnings: ['Using fallback type verification. Full categorical analysis unavailable.'],
423
+ durationMs: Date.now() - startTime,
424
+ usedFallback: true,
425
+ };
426
+ }
427
+ /**
428
+ * Create a witness for a decision
429
+ */
430
+ async createWitness(decision) {
431
+ this.ensureInitialized();
432
+ if (this.witnessAdapter?.isInitialized()) {
433
+ return this.witnessAdapter.createWitness(decision);
434
+ }
435
+ // Fallback: create simple witness
436
+ return {
437
+ witnessId: `witness-fallback-${Date.now()}`,
438
+ decisionId: decision.id,
439
+ hash: this.simpleHash(JSON.stringify(decision)),
440
+ chainPosition: 0,
441
+ timestamp: new Date(),
442
+ };
443
+ }
444
+ /**
445
+ * Replay a decision from a witness
446
+ */
447
+ async replayFromWitness(witnessId) {
448
+ this.ensureInitialized();
449
+ if (this.witnessAdapter?.isInitialized()) {
450
+ return this.witnessAdapter.replayFromWitness(witnessId);
451
+ }
452
+ return {
453
+ success: false,
454
+ decision: {
455
+ id: '',
456
+ type: 'routing',
457
+ inputs: {},
458
+ output: null,
459
+ agents: [],
460
+ timestamp: new Date(),
461
+ },
462
+ matchesOriginal: false,
463
+ differences: ['Replay not available in fallback mode'],
464
+ durationMs: 0,
465
+ };
466
+ }
467
+ /**
468
+ * Check coherence of swarm agents
469
+ */
470
+ async checkSwarmCoherence(agentHealth) {
471
+ this.ensureInitialized();
472
+ // Convert agent health to coherence nodes
473
+ const nodes = [];
474
+ agentHealth.forEach((health, agentId) => {
475
+ // Create embedding from agent state
476
+ const embedding = this.agentHealthToEmbedding(health);
477
+ nodes.push({
478
+ id: agentId,
479
+ embedding,
480
+ weight: health.health,
481
+ metadata: {
482
+ agentType: health.agentType,
483
+ successRate: health.successRate,
484
+ errorCount: health.errorCount,
485
+ },
486
+ });
487
+ });
488
+ return this.checkCoherence(nodes);
489
+ }
490
+ /**
491
+ * Verify multi-agent consensus
492
+ */
493
+ async verifyConsensus(votes) {
494
+ this.ensureInitialized();
495
+ const startTime = Date.now();
496
+ if (this.spectralAdapter?.isInitialized()) {
497
+ // Build spectral graph from votes
498
+ this.spectralAdapter.clear();
499
+ // Add agents as nodes
500
+ for (const vote of votes) {
501
+ this.spectralAdapter.addNode(vote.agentId);
502
+ }
503
+ // Connect agents that agree
504
+ for (let i = 0; i < votes.length; i++) {
505
+ for (let j = i + 1; j < votes.length; j++) {
506
+ if (votes[i].verdict === votes[j].verdict) {
507
+ this.spectralAdapter.addEdge(votes[i].agentId, votes[j].agentId, Math.min(votes[i].confidence, votes[j].confidence));
508
+ }
509
+ }
510
+ }
511
+ const collapseRisk = this.spectralAdapter.predictCollapseRisk();
512
+ const fiedlerValue = this.spectralAdapter.computeFiedlerValue();
513
+ return {
514
+ isValid: collapseRisk < 0.3 && fiedlerValue > 0.1,
515
+ confidence: 1 - collapseRisk,
516
+ isFalseConsensus: fiedlerValue < 0.05,
517
+ fiedlerValue,
518
+ collapseRisk,
519
+ recommendation: collapseRisk > 0.3
520
+ ? 'Spawn independent reviewer'
521
+ : 'Consensus verified',
522
+ durationMs: Date.now() - startTime,
523
+ usedFallback: false,
524
+ };
525
+ }
526
+ // Fallback: simple majority analysis
527
+ return this.verifyConsensusWithFallback(votes, startTime);
528
+ }
529
+ /**
530
+ * Fallback consensus verification
531
+ */
532
+ verifyConsensusWithFallback(votes, startTime) {
533
+ // Count verdicts
534
+ const verdictCounts = new Map();
535
+ for (const vote of votes) {
536
+ const key = String(vote.verdict);
537
+ verdictCounts.set(key, (verdictCounts.get(key) || 0) + 1);
538
+ }
539
+ // Find majority
540
+ let maxCount = 0;
541
+ verdictCounts.forEach(count => {
542
+ maxCount = Math.max(maxCount, count);
543
+ });
544
+ const majorityRatio = maxCount / votes.length;
545
+ const avgConfidence = votes.reduce((sum, v) => sum + v.confidence, 0) / votes.length;
546
+ return {
547
+ isValid: majorityRatio > 0.6,
548
+ confidence: majorityRatio * avgConfidence,
549
+ isFalseConsensus: verdictCounts.size === 1 && votes.length > 2,
550
+ fiedlerValue: majorityRatio, // Approximation
551
+ collapseRisk: 1 - majorityRatio,
552
+ recommendation: majorityRatio < 0.6
553
+ ? 'No clear majority. Consider spawning additional agents.'
554
+ : majorityRatio === 1 && verdictCounts.size === 1
555
+ ? 'Unanimous consensus may indicate false consensus. Consider adding diversity.'
556
+ : 'Majority consensus achieved.',
557
+ durationMs: Date.now() - startTime,
558
+ usedFallback: true,
559
+ };
560
+ }
561
+ /**
562
+ * Filter items to only return coherent ones
563
+ */
564
+ async filterCoherent(items, context) {
565
+ this.ensureInitialized();
566
+ if (items.length === 0)
567
+ return [];
568
+ if (items.length === 1)
569
+ return items;
570
+ // Convert to coherence nodes
571
+ const nodes = items.map(item => ({
572
+ id: item.id,
573
+ embedding: item.embedding,
574
+ }));
575
+ // Check coherence
576
+ const result = await this.checkCoherence(nodes);
577
+ if (result.isCoherent) {
578
+ return items;
579
+ }
580
+ // Filter out items involved in contradictions
581
+ const contradictingIds = new Set();
582
+ for (const contradiction of result.contradictions) {
583
+ contradiction.nodeIds.forEach(id => contradictingIds.add(id));
584
+ }
585
+ // Keep items not involved in critical contradictions
586
+ return items.filter(item => !contradictingIds.has(item.id));
587
+ }
588
+ /**
589
+ * Get service statistics
590
+ */
591
+ getStats() {
592
+ return {
593
+ ...this.stats,
594
+ averageEnergy: this.stats.totalChecks > 0
595
+ ? this.totalEnergySum / this.stats.totalChecks
596
+ : 0,
597
+ averageDurationMs: this.stats.totalChecks > 0
598
+ ? this.totalDurationSum / this.stats.totalChecks
599
+ : 0,
600
+ lastCheckAt: this.stats.lastCheckAt,
601
+ };
602
+ }
603
+ /**
604
+ * Dispose of service resources
605
+ */
606
+ async dispose() {
607
+ this.cohomologyAdapter?.dispose();
608
+ this.spectralAdapter?.dispose();
609
+ this.causalAdapter?.dispose();
610
+ this.categoryAdapter?.dispose();
611
+ this.homotopyAdapter?.dispose();
612
+ this.witnessAdapter?.dispose();
613
+ this.cohomologyAdapter = null;
614
+ this.spectralAdapter = null;
615
+ this.causalAdapter = null;
616
+ this.categoryAdapter = null;
617
+ this.homotopyAdapter = null;
618
+ this.witnessAdapter = null;
619
+ this.initialized = false;
620
+ this.logger.info('CoherenceService disposed');
621
+ }
622
+ // ============================================================================
623
+ // Private Helper Methods
624
+ // ============================================================================
625
+ /**
626
+ * Compute the appropriate compute lane based on energy
627
+ */
628
+ computeLane(energy) {
629
+ const { laneConfig } = this.config;
630
+ if (energy < laneConfig.reflexThreshold)
631
+ return 'reflex';
632
+ if (energy < laneConfig.retrievalThreshold)
633
+ return 'retrieval';
634
+ if (energy < laneConfig.heavyThreshold)
635
+ return 'heavy';
636
+ return 'human';
637
+ }
638
+ /**
639
+ * Update statistics after a coherence check
640
+ */
641
+ updateStats(energy, durationMs, contradictionCount, lane, usedFallback) {
642
+ this.stats.totalChecks++;
643
+ this.totalEnergySum += energy;
644
+ this.totalDurationSum += durationMs;
645
+ this.stats.totalContradictions += contradictionCount;
646
+ this.stats.laneDistribution[lane]++;
647
+ this.stats.lastCheckAt = new Date();
648
+ if (energy < this.config.coherenceThreshold) {
649
+ this.stats.coherentCount++;
650
+ }
651
+ else {
652
+ this.stats.incoherentCount++;
653
+ }
654
+ if (usedFallback) {
655
+ this.stats.fallbackCount++;
656
+ }
657
+ }
658
+ /**
659
+ * Generate recommendations based on coherence result
660
+ */
661
+ generateRecommendations(energy, lane, contradictions) {
662
+ const recommendations = [];
663
+ if (lane === 'reflex') {
664
+ recommendations.push('Low energy detected. Safe to proceed with immediate execution.');
665
+ }
666
+ else if (lane === 'retrieval') {
667
+ recommendations.push('Moderate energy detected. Consider fetching additional context before proceeding.');
668
+ }
669
+ else if (lane === 'heavy') {
670
+ recommendations.push('High energy detected. Deep analysis recommended before proceeding.');
671
+ }
672
+ else {
673
+ recommendations.push('Critical energy level. Escalate to human review (Queen agent).');
674
+ }
675
+ if (contradictions.length > 0) {
676
+ const critical = contradictions.filter(c => c.severity === 'critical');
677
+ if (critical.length > 0) {
678
+ recommendations.push(`Found ${critical.length} critical contradiction(s) that must be resolved.`);
679
+ }
680
+ }
681
+ return recommendations;
682
+ }
683
+ /**
684
+ * Convert agent health to a numerical embedding
685
+ */
686
+ agentHealthToEmbedding(health) {
687
+ // Create a fixed-size embedding from agent state
688
+ return [
689
+ health.health,
690
+ health.successRate,
691
+ Math.min(1, health.errorCount / 10),
692
+ this.agentTypeToNumber(health.agentType),
693
+ health.beliefs.length / 10,
694
+ // Add belief embeddings (first 3 beliefs, padded)
695
+ ...(health.beliefs[0]?.embedding.slice(0, 5) || [0, 0, 0, 0, 0]),
696
+ ...(health.beliefs[1]?.embedding.slice(0, 5) || [0, 0, 0, 0, 0]),
697
+ ...(health.beliefs[2]?.embedding.slice(0, 5) || [0, 0, 0, 0, 0]),
698
+ ];
699
+ }
700
+ /**
701
+ * Convert agent type to a number for embedding
702
+ */
703
+ agentTypeToNumber(type) {
704
+ const types = ['coordinator', 'specialist', 'analyzer', 'generator',
705
+ 'validator', 'tester', 'reviewer', 'optimizer'];
706
+ const index = types.indexOf(type);
707
+ return index >= 0 ? index / types.length : 0.5;
708
+ }
709
+ /**
710
+ * Compute Euclidean distance between two vectors
711
+ */
712
+ euclideanDistance(a, b) {
713
+ if (a.length !== b.length)
714
+ return Infinity;
715
+ let sum = 0;
716
+ for (let i = 0; i < a.length; i++) {
717
+ sum += (a[i] - b[i]) ** 2;
718
+ }
719
+ return Math.sqrt(sum);
720
+ }
721
+ /**
722
+ * Compute cosine similarity between two vectors
723
+ */
724
+ cosineSimilarity(a, b) {
725
+ if (a.length !== b.length || a.length === 0)
726
+ return 0;
727
+ let dotProduct = 0;
728
+ let normA = 0;
729
+ let normB = 0;
730
+ for (let i = 0; i < a.length; i++) {
731
+ dotProduct += a[i] * b[i];
732
+ normA += a[i] * a[i];
733
+ normB += b[i] * b[i];
734
+ }
735
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
736
+ return denominator === 0 ? 0 : dotProduct / denominator;
737
+ }
738
+ /**
739
+ * Compute Pearson correlation coefficient
740
+ */
741
+ computeCorrelation(x, y) {
742
+ if (x.length !== y.length || x.length < 2)
743
+ return 0;
744
+ const n = x.length;
745
+ const meanX = x.reduce((a, b) => a + b, 0) / n;
746
+ const meanY = y.reduce((a, b) => a + b, 0) / n;
747
+ let numerator = 0;
748
+ let denomX = 0;
749
+ let denomY = 0;
750
+ for (let i = 0; i < n; i++) {
751
+ const dx = x[i] - meanX;
752
+ const dy = y[i] - meanY;
753
+ numerator += dx * dy;
754
+ denomX += dx * dx;
755
+ denomY += dy * dy;
756
+ }
757
+ const denominator = Math.sqrt(denomX * denomY);
758
+ return denominator === 0 ? 0 : numerator / denominator;
759
+ }
760
+ /**
761
+ * Simple hash function for fallback
762
+ */
763
+ simpleHash(str) {
764
+ let hash = 0;
765
+ for (let i = 0; i < str.length; i++) {
766
+ const char = str.charCodeAt(i);
767
+ hash = ((hash << 5) - hash) + char;
768
+ hash = hash & hash;
769
+ }
770
+ return (hash >>> 0).toString(16).padStart(8, '0');
771
+ }
772
+ }
773
+ // ============================================================================
774
+ // Factory Function
775
+ // ============================================================================
776
+ /**
777
+ * Create and initialize a CoherenceService
778
+ *
779
+ * @param wasmLoader - WASM module loader
780
+ * @param config - Optional service configuration
781
+ * @param logger - Optional logger
782
+ * @returns Initialized service
783
+ *
784
+ * @example
785
+ * ```typescript
786
+ * const service = await createCoherenceService(wasmLoader);
787
+ *
788
+ * const result = await service.checkCoherence(nodes);
789
+ * if (!result.isCoherent) {
790
+ * console.log('Contradictions:', result.contradictions);
791
+ * }
792
+ * ```
793
+ */
794
+ export async function createCoherenceService(wasmLoader, config, logger) {
795
+ const service = new CoherenceService(wasmLoader, config, logger);
796
+ await service.initialize();
797
+ return service;
798
+ }
799
+ //# sourceMappingURL=coherence-service.js.map