@agentic-qe/v3 3.0.0-alpha.6 → 3.0.0-alpha.7

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 (609) hide show
  1. package/assets/agents/v3/subagents/v3-qe-code-reviewer.md +339 -0
  2. package/assets/agents/v3/subagents/v3-qe-integration-reviewer.md +344 -0
  3. package/assets/agents/v3/subagents/v3-qe-performance-reviewer.md +351 -0
  4. package/assets/agents/v3/subagents/v3-qe-security-reviewer.md +374 -0
  5. package/assets/agents/v3/subagents/v3-qe-tdd-green.md +334 -0
  6. package/assets/agents/v3/subagents/v3-qe-tdd-red.md +329 -0
  7. package/assets/agents/v3/subagents/v3-qe-tdd-refactor.md +361 -0
  8. package/assets/agents/v3/v3-qe-accessibility-auditor.md +266 -0
  9. package/assets/agents/v3/v3-qe-bdd-generator.md +279 -0
  10. package/assets/agents/v3/v3-qe-chaos-engineer.md +265 -0
  11. package/assets/agents/v3/v3-qe-code-complexity.md +298 -0
  12. package/assets/agents/v3/v3-qe-code-intelligence.md +262 -0
  13. package/assets/agents/v3/v3-qe-contract-validator.md +267 -0
  14. package/assets/agents/v3/v3-qe-coverage-specialist.md +227 -0
  15. package/assets/agents/v3/v3-qe-defect-predictor.md +251 -0
  16. package/assets/agents/v3/v3-qe-dependency-mapper.md +277 -0
  17. package/assets/agents/v3/v3-qe-deployment-advisor.md +275 -0
  18. package/assets/agents/v3/v3-qe-flaky-hunter.md +248 -0
  19. package/assets/agents/v3/v3-qe-fleet-commander.md +293 -0
  20. package/assets/agents/v3/v3-qe-gap-detector.md +260 -0
  21. package/assets/agents/v3/v3-qe-graphql-tester.md +308 -0
  22. package/assets/agents/v3/v3-qe-impact-analyzer.md +299 -0
  23. package/assets/agents/v3/v3-qe-integration-tester.md +238 -0
  24. package/assets/agents/v3/v3-qe-kg-builder.md +273 -0
  25. package/assets/agents/v3/v3-qe-learning-coordinator.md +226 -0
  26. package/assets/agents/v3/v3-qe-load-tester.md +280 -0
  27. package/assets/agents/v3/v3-qe-metrics-optimizer.md +300 -0
  28. package/assets/agents/v3/v3-qe-mutation-tester.md +301 -0
  29. package/assets/agents/v3/v3-qe-parallel-executor.md +240 -0
  30. package/assets/agents/v3/v3-qe-pattern-learner.md +271 -0
  31. package/assets/agents/v3/v3-qe-performance-tester.md +262 -0
  32. package/assets/agents/v3/v3-qe-property-tester.md +247 -0
  33. package/assets/agents/v3/v3-qe-quality-gate.md +218 -0
  34. package/assets/agents/v3/v3-qe-queen-coordinator.md +214 -0
  35. package/assets/agents/v3/v3-qe-qx-partner.md +313 -0
  36. package/assets/agents/v3/v3-qe-regression-analyzer.md +322 -0
  37. package/assets/agents/v3/v3-qe-requirements-validator.md +360 -0
  38. package/assets/agents/v3/v3-qe-responsive-tester.md +311 -0
  39. package/assets/agents/v3/v3-qe-retry-handler.md +256 -0
  40. package/assets/agents/v3/v3-qe-risk-assessor.md +273 -0
  41. package/assets/agents/v3/v3-qe-root-cause-analyzer.md +286 -0
  42. package/assets/agents/v3/v3-qe-security-auditor.md +299 -0
  43. package/assets/agents/v3/v3-qe-security-scanner.md +235 -0
  44. package/assets/agents/v3/v3-qe-tdd-specialist.md +239 -0
  45. package/assets/agents/v3/v3-qe-test-architect.md +233 -0
  46. package/assets/agents/v3/v3-qe-transfer-specialist.md +295 -0
  47. package/assets/agents/v3/v3-qe-visual-tester.md +232 -0
  48. package/assets/skills/accessibility-testing/SKILL.md +216 -0
  49. package/assets/skills/agentdb-advanced/SKILL.md +550 -0
  50. package/assets/skills/agentdb-learning/SKILL.md +545 -0
  51. package/assets/skills/agentdb-memory-patterns/SKILL.md +339 -0
  52. package/assets/skills/agentdb-optimization/SKILL.md +509 -0
  53. package/assets/skills/agentdb-vector-search/SKILL.md +339 -0
  54. package/assets/skills/agentic-jujutsu/SKILL.md +645 -0
  55. package/assets/skills/agentic-quality-engineering/SKILL.md +335 -0
  56. package/assets/skills/api-testing-patterns/SKILL.md +294 -0
  57. package/assets/skills/aqe-v2-v3-migration/skill.md +322 -0
  58. package/assets/skills/brutal-honesty-review/README.md +218 -0
  59. package/assets/skills/brutal-honesty-review/SKILL.md +235 -0
  60. package/assets/skills/brutal-honesty-review/resources/assessment-rubrics.md +295 -0
  61. package/assets/skills/brutal-honesty-review/resources/review-template.md +102 -0
  62. package/assets/skills/brutal-honesty-review/scripts/assess-code.sh +179 -0
  63. package/assets/skills/brutal-honesty-review/scripts/assess-tests.sh +223 -0
  64. package/assets/skills/bug-reporting-excellence/SKILL.md +225 -0
  65. package/assets/skills/chaos-engineering-resilience/SKILL.md +158 -0
  66. package/assets/skills/cicd-pipeline-qe-orchestrator/README.md +304 -0
  67. package/assets/skills/cicd-pipeline-qe-orchestrator/SKILL.md +315 -0
  68. package/assets/skills/cicd-pipeline-qe-orchestrator/resources/workflows/microservice-pipeline.md +239 -0
  69. package/assets/skills/cicd-pipeline-qe-orchestrator/resources/workflows/mobile-pipeline.md +375 -0
  70. package/assets/skills/cicd-pipeline-qe-orchestrator/resources/workflows/monolith-pipeline.md +268 -0
  71. package/assets/skills/code-review-quality/SKILL.md +227 -0
  72. package/assets/skills/compatibility-testing/SKILL.md +205 -0
  73. package/assets/skills/compliance-testing/SKILL.md +225 -0
  74. package/assets/skills/consultancy-practices/SKILL.md +202 -0
  75. package/assets/skills/context-driven-testing/SKILL.md +196 -0
  76. package/assets/skills/contract-testing/SKILL.md +222 -0
  77. package/assets/skills/database-testing/SKILL.md +244 -0
  78. package/assets/skills/exploratory-testing-advanced/SKILL.md +201 -0
  79. package/assets/skills/flow-nexus-neural/SKILL.md +738 -0
  80. package/assets/skills/flow-nexus-platform/SKILL.md +1157 -0
  81. package/assets/skills/flow-nexus-swarm/SKILL.md +610 -0
  82. package/assets/skills/github-code-review/SKILL.md +1140 -0
  83. package/assets/skills/github-multi-repo/SKILL.md +874 -0
  84. package/assets/skills/github-project-management/SKILL.md +1277 -0
  85. package/assets/skills/github-release-management/SKILL.md +1081 -0
  86. package/assets/skills/github-workflow-automation/SKILL.md +1065 -0
  87. package/assets/skills/hive-mind-advanced/SKILL.md +712 -0
  88. package/assets/skills/holistic-testing-pact/SKILL.md +171 -0
  89. package/assets/skills/hooks-automation/SKILL.md +1201 -0
  90. package/assets/skills/localization-testing/SKILL.md +221 -0
  91. package/assets/skills/mobile-testing/SKILL.md +219 -0
  92. package/assets/skills/mutation-testing/SKILL.md +229 -0
  93. package/assets/skills/n8n-expression-testing/SKILL.md +434 -0
  94. package/assets/skills/n8n-integration-testing-patterns/SKILL.md +540 -0
  95. package/assets/skills/n8n-security-testing/SKILL.md +599 -0
  96. package/assets/skills/n8n-trigger-testing-strategies/SKILL.md +541 -0
  97. package/assets/skills/n8n-workflow-testing-fundamentals/SKILL.md +447 -0
  98. package/assets/skills/pair-programming/SKILL.md +1202 -0
  99. package/assets/skills/performance-analysis/SKILL.md +563 -0
  100. package/assets/skills/performance-testing/SKILL.md +310 -0
  101. package/assets/skills/quality-metrics/SKILL.md +225 -0
  102. package/assets/skills/reasoningbank-agentdb/SKILL.md +446 -0
  103. package/assets/skills/reasoningbank-intelligence/SKILL.md +201 -0
  104. package/assets/skills/refactoring-patterns/SKILL.md +205 -0
  105. package/assets/skills/regression-testing/SKILL.md +227 -0
  106. package/assets/skills/risk-based-testing/SKILL.md +206 -0
  107. package/assets/skills/security-testing/SKILL.md +306 -0
  108. package/assets/skills/sherlock-review/SKILL.md +250 -0
  109. package/assets/skills/shift-left-testing/SKILL.md +225 -0
  110. package/assets/skills/shift-right-testing/SKILL.md +227 -0
  111. package/assets/skills/six-thinking-hats/README.md +190 -0
  112. package/assets/skills/six-thinking-hats/SKILL.md +280 -0
  113. package/assets/skills/six-thinking-hats/resources/examples/api-testing-example.md +345 -0
  114. package/assets/skills/six-thinking-hats/resources/templates/solo-session-template.md +167 -0
  115. package/assets/skills/six-thinking-hats/resources/templates/team-session-template.md +336 -0
  116. package/assets/skills/skill-builder/SKILL.md +910 -0
  117. package/assets/skills/sparc-methodology/SKILL.md +1115 -0
  118. package/assets/skills/stream-chain/SKILL.md +563 -0
  119. package/assets/skills/swarm-advanced/SKILL.md +973 -0
  120. package/assets/skills/swarm-orchestration/SKILL.md +179 -0
  121. package/assets/skills/tdd-london-chicago/SKILL.md +244 -0
  122. package/assets/skills/technical-writing/SKILL.md +178 -0
  123. package/assets/skills/test-automation-strategy/SKILL.md +230 -0
  124. package/assets/skills/test-data-management/SKILL.md +270 -0
  125. package/assets/skills/test-design-techniques/SKILL.md +244 -0
  126. package/assets/skills/test-environment-management/SKILL.md +243 -0
  127. package/assets/skills/test-reporting-analytics/SKILL.md +214 -0
  128. package/assets/skills/testability-scoring/README.md +71 -0
  129. package/assets/skills/testability-scoring/SKILL.md +346 -0
  130. package/assets/skills/testability-scoring/resources/templates/config.template.js +84 -0
  131. package/assets/skills/testability-scoring/resources/templates/testability-scoring.spec.template.js +532 -0
  132. package/assets/skills/testability-scoring/scripts/generate-html-report.js +1007 -0
  133. package/assets/skills/testability-scoring/scripts/run-assessment.sh +70 -0
  134. package/assets/skills/v3-qe-chaos-resilience/SKILL.md +238 -0
  135. package/assets/skills/v3-qe-code-intelligence/SKILL.md +209 -0
  136. package/assets/skills/v3-qe-contract-testing/SKILL.md +218 -0
  137. package/assets/skills/v3-qe-coverage-analysis/SKILL.md +187 -0
  138. package/assets/skills/v3-qe-defect-intelligence/SKILL.md +205 -0
  139. package/assets/skills/v3-qe-learning-optimization/SKILL.md +238 -0
  140. package/assets/skills/v3-qe-quality-assessment/SKILL.md +213 -0
  141. package/assets/skills/v3-qe-requirements-validation/SKILL.md +248 -0
  142. package/assets/skills/v3-qe-test-execution/SKILL.md +182 -0
  143. package/assets/skills/v3-qe-test-generation/SKILL.md +141 -0
  144. package/assets/skills/v3-qe-visual-accessibility/SKILL.md +242 -0
  145. package/assets/skills/verification-quality/SKILL.md +649 -0
  146. package/assets/skills/visual-testing-advanced/SKILL.md +219 -0
  147. package/assets/skills/xp-practices/SKILL.md +229 -0
  148. package/dist/cli/bundle.js +8 -8
  149. package/dist/init/agents-installer.js +4 -4
  150. package/dist/init/agents-installer.js.map +1 -1
  151. package/dist/init/skills-installer.js +4 -4
  152. package/dist/init/skills-installer.js.map +1 -1
  153. package/package.json +7 -1
  154. package/docs/analysis/V3-INIT-REQUIREMENTS-ANALYSIS.md +0 -352
  155. package/implementation/README.md +0 -90
  156. package/implementation/adrs/ADR-030-coherence-gated-quality-gates.md +0 -312
  157. package/implementation/adrs/ADR-031-strange-loop-self-awareness.md +0 -484
  158. package/implementation/adrs/ADR-032-time-crystal-scheduling.md +0 -530
  159. package/implementation/adrs/ADR-033-early-exit-testing.md +0 -634
  160. package/implementation/adrs/ADR-034-neural-topology-optimizer.md +0 -589
  161. package/implementation/adrs/ADR-035-causal-discovery.md +0 -610
  162. package/implementation/adrs/ADR-036-result-persistence.md +0 -326
  163. package/implementation/adrs/ADR-037-v3-qe-agent-naming.md +0 -105
  164. package/implementation/adrs/ADR-038-v3-qe-memory-unification.md +0 -154
  165. package/implementation/adrs/ADR-039-v3-qe-mcp-optimization.md +0 -179
  166. package/implementation/adrs/ADR-040-v3-qe-agentic-flow-integration.md +0 -240
  167. package/implementation/adrs/ADR-041-v3-qe-cli-enhancement.md +0 -296
  168. package/implementation/adrs/ADR-042-v3-qe-token-tracking-integration.md +0 -517
  169. package/implementation/adrs/v3-adrs.md +0 -2783
  170. package/implementation/planning/AQE-V3-MASTER-PLAN.md +0 -815
  171. package/security-scan-report-2026-01-11.md +0 -410
  172. package/security-verification-report-2026-01-11.md +0 -278
  173. package/src/benchmarks/performance-benchmarks.ts +0 -646
  174. package/src/benchmarks/run-benchmarks.ts +0 -324
  175. package/src/causal-discovery/causal-graph.ts +0 -450
  176. package/src/causal-discovery/discovery-engine.ts +0 -438
  177. package/src/causal-discovery/index.ts +0 -117
  178. package/src/causal-discovery/types.ts +0 -456
  179. package/src/causal-discovery/weight-matrix.ts +0 -453
  180. package/src/cli/commands/qe-tools.ts +0 -634
  181. package/src/cli/index.ts +0 -1976
  182. package/src/compatibility/agent-mapper.ts +0 -291
  183. package/src/compatibility/cli-adapter.ts +0 -277
  184. package/src/compatibility/config-migrator.ts +0 -334
  185. package/src/compatibility/index.ts +0 -112
  186. package/src/compatibility/mcp-adapter.ts +0 -248
  187. package/src/compatibility/types.ts +0 -156
  188. package/src/coordination/claims/claim-repository.ts +0 -636
  189. package/src/coordination/claims/claim-service.ts +0 -675
  190. package/src/coordination/claims/handoff-manager.ts +0 -535
  191. package/src/coordination/claims/index.ts +0 -276
  192. package/src/coordination/claims/interfaces.ts +0 -687
  193. package/src/coordination/claims/work-stealing.ts +0 -436
  194. package/src/coordination/cross-domain-router.ts +0 -492
  195. package/src/coordination/index.ts +0 -127
  196. package/src/coordination/interfaces.ts +0 -691
  197. package/src/coordination/protocol-executor.ts +0 -760
  198. package/src/coordination/protocols/code-intelligence-index.ts +0 -855
  199. package/src/coordination/protocols/defect-investigation.ts +0 -1184
  200. package/src/coordination/protocols/index.ts +0 -11
  201. package/src/coordination/protocols/learning-consolidation.ts +0 -1181
  202. package/src/coordination/protocols/morning-sync.ts +0 -1055
  203. package/src/coordination/protocols/quality-gate.ts +0 -1566
  204. package/src/coordination/protocols/security-audit.ts +0 -1587
  205. package/src/coordination/queen-coordinator.ts +0 -1176
  206. package/src/coordination/result-saver.ts +0 -780
  207. package/src/coordination/task-executor.ts +0 -1146
  208. package/src/coordination/workflow-orchestrator.ts +0 -1917
  209. package/src/domains/chaos-resilience/coordinator.ts +0 -1032
  210. package/src/domains/chaos-resilience/index.ts +0 -143
  211. package/src/domains/chaos-resilience/interfaces.ts +0 -659
  212. package/src/domains/chaos-resilience/plugin.ts +0 -691
  213. package/src/domains/chaos-resilience/services/chaos-engineer.ts +0 -1097
  214. package/src/domains/chaos-resilience/services/index.ts +0 -19
  215. package/src/domains/chaos-resilience/services/load-tester.ts +0 -799
  216. package/src/domains/chaos-resilience/services/performance-profiler.ts +0 -792
  217. package/src/domains/code-intelligence/coordinator.ts +0 -631
  218. package/src/domains/code-intelligence/index.ts +0 -86
  219. package/src/domains/code-intelligence/interfaces.ts +0 -162
  220. package/src/domains/code-intelligence/plugin.ts +0 -451
  221. package/src/domains/code-intelligence/services/impact-analyzer.ts +0 -567
  222. package/src/domains/code-intelligence/services/index.ts +0 -26
  223. package/src/domains/code-intelligence/services/knowledge-graph.ts +0 -1067
  224. package/src/domains/code-intelligence/services/semantic-analyzer.ts +0 -901
  225. package/src/domains/contract-testing/coordinator.ts +0 -1038
  226. package/src/domains/contract-testing/index.ts +0 -122
  227. package/src/domains/contract-testing/interfaces.ts +0 -458
  228. package/src/domains/contract-testing/plugin.ts +0 -746
  229. package/src/domains/contract-testing/services/api-compatibility.ts +0 -748
  230. package/src/domains/contract-testing/services/contract-validator.ts +0 -1700
  231. package/src/domains/contract-testing/services/index.ts +0 -19
  232. package/src/domains/contract-testing/services/schema-validator.ts +0 -1102
  233. package/src/domains/coverage-analysis/coordinator.ts +0 -485
  234. package/src/domains/coverage-analysis/index.ts +0 -114
  235. package/src/domains/coverage-analysis/interfaces.ts +0 -142
  236. package/src/domains/coverage-analysis/plugin.ts +0 -172
  237. package/src/domains/coverage-analysis/services/coverage-analyzer.ts +0 -449
  238. package/src/domains/coverage-analysis/services/coverage-embedder.ts +0 -733
  239. package/src/domains/coverage-analysis/services/coverage-parser.ts +0 -753
  240. package/src/domains/coverage-analysis/services/gap-detector.ts +0 -592
  241. package/src/domains/coverage-analysis/services/hnsw-index.ts +0 -728
  242. package/src/domains/coverage-analysis/services/index.ts +0 -61
  243. package/src/domains/coverage-analysis/services/risk-scorer.ts +0 -540
  244. package/src/domains/coverage-analysis/services/sublinear-analyzer.ts +0 -747
  245. package/src/domains/defect-intelligence/coordinator.ts +0 -635
  246. package/src/domains/defect-intelligence/index.ts +0 -83
  247. package/src/domains/defect-intelligence/interfaces.ts +0 -152
  248. package/src/domains/defect-intelligence/plugin.ts +0 -483
  249. package/src/domains/defect-intelligence/services/causal-root-cause-analyzer.ts +0 -494
  250. package/src/domains/defect-intelligence/services/defect-predictor.ts +0 -852
  251. package/src/domains/defect-intelligence/services/index.ts +0 -37
  252. package/src/domains/defect-intelligence/services/pattern-learner.ts +0 -738
  253. package/src/domains/defect-intelligence/services/root-cause-analyzer.ts +0 -637
  254. package/src/domains/domain-interface.ts +0 -77
  255. package/src/domains/index.ts +0 -23
  256. package/src/domains/learning-optimization/coordinator.ts +0 -1215
  257. package/src/domains/learning-optimization/index.ts +0 -127
  258. package/src/domains/learning-optimization/interfaces.ts +0 -570
  259. package/src/domains/learning-optimization/plugin.ts +0 -851
  260. package/src/domains/learning-optimization/services/index.ts +0 -29
  261. package/src/domains/learning-optimization/services/learning-coordinator.ts +0 -972
  262. package/src/domains/learning-optimization/services/metrics-optimizer.ts +0 -915
  263. package/src/domains/learning-optimization/services/production-intel.ts +0 -971
  264. package/src/domains/learning-optimization/services/transfer-specialist.ts +0 -723
  265. package/src/domains/quality-assessment/coherence/gate-controller.ts +0 -549
  266. package/src/domains/quality-assessment/coherence/index.ts +0 -211
  267. package/src/domains/quality-assessment/coherence/lambda-calculator.ts +0 -384
  268. package/src/domains/quality-assessment/coherence/partition-detector.ts +0 -469
  269. package/src/domains/quality-assessment/coherence/types.ts +0 -384
  270. package/src/domains/quality-assessment/coordinator.ts +0 -605
  271. package/src/domains/quality-assessment/index.ts +0 -97
  272. package/src/domains/quality-assessment/interfaces.ts +0 -152
  273. package/src/domains/quality-assessment/plugin.ts +0 -496
  274. package/src/domains/quality-assessment/services/coherence-gate.ts +0 -358
  275. package/src/domains/quality-assessment/services/deployment-advisor.ts +0 -571
  276. package/src/domains/quality-assessment/services/index.ts +0 -34
  277. package/src/domains/quality-assessment/services/quality-analyzer.ts +0 -670
  278. package/src/domains/quality-assessment/services/quality-gate.ts +0 -384
  279. package/src/domains/requirements-validation/coordinator.ts +0 -812
  280. package/src/domains/requirements-validation/index.ts +0 -92
  281. package/src/domains/requirements-validation/interfaces.ts +0 -303
  282. package/src/domains/requirements-validation/plugin.ts +0 -576
  283. package/src/domains/requirements-validation/services/bdd-scenario-writer.ts +0 -676
  284. package/src/domains/requirements-validation/services/index.ts +0 -20
  285. package/src/domains/requirements-validation/services/requirements-validator.ts +0 -559
  286. package/src/domains/requirements-validation/services/testability-scorer.ts +0 -639
  287. package/src/domains/security-compliance/coordinator.ts +0 -757
  288. package/src/domains/security-compliance/index.ts +0 -120
  289. package/src/domains/security-compliance/interfaces.ts +0 -434
  290. package/src/domains/security-compliance/plugin.ts +0 -509
  291. package/src/domains/security-compliance/services/compliance-validator.ts +0 -1226
  292. package/src/domains/security-compliance/services/index.ts +0 -31
  293. package/src/domains/security-compliance/services/security-auditor.ts +0 -2227
  294. package/src/domains/security-compliance/services/security-scanner.ts +0 -2354
  295. package/src/domains/security-compliance/services/semgrep-integration.ts +0 -289
  296. package/src/domains/test-execution/coordinator.ts +0 -426
  297. package/src/domains/test-execution/index.ts +0 -76
  298. package/src/domains/test-execution/interfaces.ts +0 -119
  299. package/src/domains/test-execution/plugin.ts +0 -208
  300. package/src/domains/test-execution/services/flaky-detector.ts +0 -1240
  301. package/src/domains/test-execution/services/index.ts +0 -8
  302. package/src/domains/test-execution/services/retry-handler.ts +0 -820
  303. package/src/domains/test-execution/services/test-executor.ts +0 -885
  304. package/src/domains/test-generation/coordinator.ts +0 -656
  305. package/src/domains/test-generation/index.ts +0 -77
  306. package/src/domains/test-generation/interfaces.ts +0 -118
  307. package/src/domains/test-generation/plugin.ts +0 -397
  308. package/src/domains/test-generation/services/index.ts +0 -23
  309. package/src/domains/test-generation/services/pattern-matcher.ts +0 -1725
  310. package/src/domains/test-generation/services/test-generator.ts +0 -2750
  311. package/src/domains/visual-accessibility/coordinator.ts +0 -860
  312. package/src/domains/visual-accessibility/index.ts +0 -116
  313. package/src/domains/visual-accessibility/interfaces.ts +0 -435
  314. package/src/domains/visual-accessibility/plugin.ts +0 -568
  315. package/src/domains/visual-accessibility/services/accessibility-tester.ts +0 -982
  316. package/src/domains/visual-accessibility/services/axe-core-audit.ts +0 -630
  317. package/src/domains/visual-accessibility/services/index.ts +0 -28
  318. package/src/domains/visual-accessibility/services/responsive-tester.ts +0 -934
  319. package/src/domains/visual-accessibility/services/visual-tester.ts +0 -458
  320. package/src/early-exit/early-exit-controller.ts +0 -490
  321. package/src/early-exit/early-exit-decision.ts +0 -391
  322. package/src/early-exit/index.ts +0 -115
  323. package/src/early-exit/quality-signal.ts +0 -389
  324. package/src/early-exit/speculative-executor.ts +0 -505
  325. package/src/early-exit/types.ts +0 -407
  326. package/src/feedback/coverage-learner.ts +0 -456
  327. package/src/feedback/feedback-loop.ts +0 -426
  328. package/src/feedback/index.ts +0 -72
  329. package/src/feedback/pattern-promotion.ts +0 -373
  330. package/src/feedback/quality-score-calculator.ts +0 -334
  331. package/src/feedback/test-outcome-tracker.ts +0 -450
  332. package/src/feedback/types.ts +0 -497
  333. package/src/index.ts +0 -224
  334. package/src/init/agents-installer.ts +0 -536
  335. package/src/init/index.ts +0 -80
  336. package/src/init/init-wizard.ts +0 -1061
  337. package/src/init/project-analyzer.ts +0 -696
  338. package/src/init/self-configurator.ts +0 -488
  339. package/src/init/skills-installer.ts +0 -467
  340. package/src/init/types.ts +0 -432
  341. package/src/integrations/ruvector/ast-complexity.ts +0 -470
  342. package/src/integrations/ruvector/coverage-router.ts +0 -594
  343. package/src/integrations/ruvector/diff-risk-classifier.ts +0 -759
  344. package/src/integrations/ruvector/fallback.ts +0 -942
  345. package/src/integrations/ruvector/graph-boundaries.ts +0 -809
  346. package/src/integrations/ruvector/index.ts +0 -363
  347. package/src/integrations/ruvector/interfaces.ts +0 -609
  348. package/src/integrations/ruvector/q-learning-router.ts +0 -550
  349. package/src/kernel/agent-coordinator.ts +0 -165
  350. package/src/kernel/agentdb-backend.ts +0 -504
  351. package/src/kernel/event-bus.ts +0 -129
  352. package/src/kernel/hybrid-backend.ts +0 -538
  353. package/src/kernel/index.ts +0 -28
  354. package/src/kernel/interfaces.ts +0 -257
  355. package/src/kernel/kernel.ts +0 -285
  356. package/src/kernel/memory-backend.ts +0 -169
  357. package/src/kernel/memory-factory.ts +0 -293
  358. package/src/kernel/plugin-loader.ts +0 -179
  359. package/src/learning/index.ts +0 -219
  360. package/src/learning/pattern-store.ts +0 -990
  361. package/src/learning/qe-guidance.ts +0 -832
  362. package/src/learning/qe-hooks.ts +0 -644
  363. package/src/learning/qe-patterns.ts +0 -449
  364. package/src/learning/qe-reasoning-bank.ts +0 -951
  365. package/src/learning/real-embeddings.ts +0 -277
  366. package/src/learning/real-qe-reasoning-bank.ts +0 -833
  367. package/src/learning/sqlite-persistence.ts +0 -554
  368. package/src/mcp/entry.ts +0 -59
  369. package/src/mcp/handlers/agent-handlers.ts +0 -285
  370. package/src/mcp/handlers/core-handlers.ts +0 -317
  371. package/src/mcp/handlers/domain-handlers.ts +0 -1444
  372. package/src/mcp/handlers/index.ts +0 -57
  373. package/src/mcp/handlers/memory-handlers.ts +0 -338
  374. package/src/mcp/handlers/task-handlers.ts +0 -363
  375. package/src/mcp/index.ts +0 -30
  376. package/src/mcp/metrics/index.ts +0 -14
  377. package/src/mcp/metrics/metrics-collector.ts +0 -503
  378. package/src/mcp/protocol-server.ts +0 -752
  379. package/src/mcp/security/cve-prevention.ts +0 -742
  380. package/src/mcp/security/index.ts +0 -356
  381. package/src/mcp/security/oauth21-provider.ts +0 -821
  382. package/src/mcp/security/rate-limiter.ts +0 -615
  383. package/src/mcp/security/sampling-server.ts +0 -662
  384. package/src/mcp/security/schema-validator.ts +0 -855
  385. package/src/mcp/server.ts +0 -657
  386. package/src/mcp/tool-registry.ts +0 -391
  387. package/src/mcp/tools/base.ts +0 -399
  388. package/src/mcp/tools/chaos-resilience/inject.ts +0 -699
  389. package/src/mcp/tools/code-intelligence/analyze.ts +0 -745
  390. package/src/mcp/tools/contract-testing/validate.ts +0 -708
  391. package/src/mcp/tools/coverage-analysis/index.ts +0 -770
  392. package/src/mcp/tools/defect-intelligence/predict.ts +0 -466
  393. package/src/mcp/tools/index.ts +0 -214
  394. package/src/mcp/tools/learning-optimization/optimize.ts +0 -772
  395. package/src/mcp/tools/quality-assessment/evaluate.ts +0 -385
  396. package/src/mcp/tools/registry.ts +0 -248
  397. package/src/mcp/tools/requirements-validation/validate.ts +0 -394
  398. package/src/mcp/tools/security-compliance/scan.ts +0 -365
  399. package/src/mcp/tools/test-execution/execute.ts +0 -291
  400. package/src/mcp/tools/test-generation/generate.ts +0 -544
  401. package/src/mcp/tools/visual-accessibility/index.ts +0 -791
  402. package/src/mcp/transport/index.ts +0 -31
  403. package/src/mcp/transport/stdio.ts +0 -318
  404. package/src/mcp/types.ts +0 -543
  405. package/src/neural-optimizer/index.ts +0 -111
  406. package/src/neural-optimizer/replay-buffer.ts +0 -455
  407. package/src/neural-optimizer/swarm-topology.ts +0 -508
  408. package/src/neural-optimizer/topology-optimizer.ts +0 -828
  409. package/src/neural-optimizer/types.ts +0 -481
  410. package/src/neural-optimizer/value-network.ts +0 -351
  411. package/src/optimization/auto-tuner.ts +0 -817
  412. package/src/optimization/index.ts +0 -77
  413. package/src/optimization/metric-collectors.ts +0 -474
  414. package/src/optimization/qe-workers.ts +0 -704
  415. package/src/optimization/tuning-algorithm.ts +0 -401
  416. package/src/optimization/types.ts +0 -314
  417. package/src/routing/index.ts +0 -51
  418. package/src/routing/qe-agent-registry.ts +0 -963
  419. package/src/routing/qe-task-router.ts +0 -564
  420. package/src/routing/routing-feedback.ts +0 -365
  421. package/src/routing/types.ts +0 -406
  422. package/src/shared/embeddings/embedding-cache.ts +0 -157
  423. package/src/shared/embeddings/index.ts +0 -50
  424. package/src/shared/embeddings/nomic-embedder.ts +0 -404
  425. package/src/shared/embeddings/ollama-client.ts +0 -195
  426. package/src/shared/embeddings/types.ts +0 -147
  427. package/src/shared/entities/agent.ts +0 -141
  428. package/src/shared/entities/base-entity.ts +0 -79
  429. package/src/shared/entities/index.ts +0 -6
  430. package/src/shared/events/domain-events.ts +0 -259
  431. package/src/shared/events/index.ts +0 -5
  432. package/src/shared/git/git-analyzer.ts +0 -656
  433. package/src/shared/git/index.ts +0 -11
  434. package/src/shared/http/http-client.ts +0 -420
  435. package/src/shared/http/index.ts +0 -13
  436. package/src/shared/index.ts +0 -41
  437. package/src/shared/io/file-reader.ts +0 -525
  438. package/src/shared/io/index.ts +0 -25
  439. package/src/shared/llm/cache.ts +0 -473
  440. package/src/shared/llm/circuit-breaker.ts +0 -369
  441. package/src/shared/llm/cost-tracker.ts +0 -460
  442. package/src/shared/llm/index.ts +0 -140
  443. package/src/shared/llm/interfaces.ts +0 -629
  444. package/src/shared/llm/provider-manager.ts +0 -685
  445. package/src/shared/llm/providers/claude.ts +0 -524
  446. package/src/shared/llm/providers/index.ts +0 -8
  447. package/src/shared/llm/providers/ollama.ts +0 -575
  448. package/src/shared/llm/providers/openai.ts +0 -609
  449. package/src/shared/metrics/code-metrics.ts +0 -520
  450. package/src/shared/metrics/index.ts +0 -23
  451. package/src/shared/metrics/system-metrics.ts +0 -353
  452. package/src/shared/parsers/index.ts +0 -6
  453. package/src/shared/parsers/typescript-parser.ts +0 -841
  454. package/src/shared/security/compliance-patterns.ts +0 -666
  455. package/src/shared/security/index.ts +0 -30
  456. package/src/shared/security/osv-client.ts +0 -468
  457. package/src/shared/types/index.ts +0 -150
  458. package/src/shared/value-objects/index.ts +0 -273
  459. package/src/strange-loop/healing-controller.ts +0 -833
  460. package/src/strange-loop/index.ts +0 -104
  461. package/src/strange-loop/self-model.ts +0 -494
  462. package/src/strange-loop/strange-loop.ts +0 -446
  463. package/src/strange-loop/swarm-observer.ts +0 -448
  464. package/src/strange-loop/topology-analyzer.ts +0 -565
  465. package/src/strange-loop/types.ts +0 -640
  466. package/src/time-crystal/default-phases.ts +0 -520
  467. package/src/time-crystal/index.ts +0 -164
  468. package/src/time-crystal/oscillator.ts +0 -425
  469. package/src/time-crystal/phase-executor.ts +0 -521
  470. package/src/time-crystal/scheduler.ts +0 -1025
  471. package/src/time-crystal/test-runner.ts +0 -787
  472. package/src/time-crystal/types.ts +0 -421
  473. package/src/workers/base-worker.ts +0 -304
  474. package/src/workers/daemon.ts +0 -264
  475. package/src/workers/index.ts +0 -119
  476. package/src/workers/interfaces.ts +0 -393
  477. package/src/workers/worker-manager.ts +0 -424
  478. package/src/workers/workers/compliance-checker.ts +0 -445
  479. package/src/workers/workers/coverage-tracker.ts +0 -344
  480. package/src/workers/workers/defect-predictor.ts +0 -375
  481. package/src/workers/workers/flaky-detector.ts +0 -390
  482. package/src/workers/workers/index.ts +0 -17
  483. package/src/workers/workers/learning-consolidation.ts +0 -442
  484. package/src/workers/workers/performance-baseline.ts +0 -434
  485. package/src/workers/workers/quality-gate.ts +0 -419
  486. package/src/workers/workers/regression-monitor.ts +0 -357
  487. package/src/workers/workers/security-scan.ts +0 -349
  488. package/src/workers/workers/test-health.ts +0 -359
  489. package/tests/integration/code-intelligence/knowledge-graph-real.test.ts +0 -540
  490. package/tests/integration/coordination/cross-domain-router.test.ts +0 -403
  491. package/tests/integration/coordination/protocol-executor.test.ts +0 -454
  492. package/tests/integration/coordination/workflow-orchestrator.test.ts +0 -418
  493. package/tests/integration/feedback/feedback-loop-integration.test.ts +0 -560
  494. package/tests/integration/migration/v2-to-v3-migration.test.ts +0 -471
  495. package/tests/integration/parsers/typescript-parser.test.ts +0 -463
  496. package/tests/integration/security/vulnerability-detection.test.ts +0 -628
  497. package/tests/integration/test-execution/coordinator.test.ts +0 -410
  498. package/tests/integration/test-generation/coordinator.test.ts +0 -361
  499. package/tests/mocks/index.ts +0 -228
  500. package/tests/time-crystal/default-phases.test.ts +0 -476
  501. package/tests/time-crystal/oscillator.test.ts +0 -541
  502. package/tests/time-crystal/phase-executor.test.ts +0 -653
  503. package/tests/time-crystal/scheduler.test.ts +0 -626
  504. package/tests/time-crystal/test-runner.test.ts +0 -594
  505. package/tests/unit/causal-discovery/causal-graph.test.ts +0 -504
  506. package/tests/unit/causal-discovery/causal-root-cause-analyzer.test.ts +0 -347
  507. package/tests/unit/causal-discovery/discovery-engine.test.ts +0 -435
  508. package/tests/unit/causal-discovery/weight-matrix.test.ts +0 -328
  509. package/tests/unit/cli/cli.test.ts +0 -341
  510. package/tests/unit/cli/commands.test.ts +0 -414
  511. package/tests/unit/cli/init-command.test.ts +0 -274
  512. package/tests/unit/cli/migrate-command.test.ts +0 -396
  513. package/tests/unit/coordination/claims/claim-service.test.ts +0 -949
  514. package/tests/unit/coordination/claims/handoff-manager.test.ts +0 -773
  515. package/tests/unit/coordination/claims/work-stealing.test.ts +0 -492
  516. package/tests/unit/coordination/queen-coordinator.test.ts +0 -966
  517. package/tests/unit/coordination/result-saver.test.ts +0 -653
  518. package/tests/unit/coordination/task-executor.test.ts +0 -810
  519. package/tests/unit/domains/chaos-resilience/chaos-engineer.test.ts +0 -484
  520. package/tests/unit/domains/chaos-resilience/load-tester.test.ts +0 -559
  521. package/tests/unit/domains/chaos-resilience/performance-profiler.test.ts +0 -490
  522. package/tests/unit/domains/code-intelligence/impact-analyzer.test.ts +0 -560
  523. package/tests/unit/domains/code-intelligence/knowledge-graph.test.ts +0 -460
  524. package/tests/unit/domains/code-intelligence/semantic-analyzer.test.ts +0 -584
  525. package/tests/unit/domains/contract-testing/api-compatibility.test.ts +0 -483
  526. package/tests/unit/domains/contract-testing/contract-validator.test.ts +0 -370
  527. package/tests/unit/domains/contract-testing/schema-validator.test.ts +0 -610
  528. package/tests/unit/domains/coverage-analysis/coverage-embedder.test.ts +0 -298
  529. package/tests/unit/domains/coverage-analysis/hnsw-index.test.ts +0 -292
  530. package/tests/unit/domains/coverage-analysis/sublinear-analyzer.test.ts +0 -506
  531. package/tests/unit/domains/defect-intelligence/defect-predictor.test.ts +0 -370
  532. package/tests/unit/domains/defect-intelligence/pattern-learner.test.ts +0 -546
  533. package/tests/unit/domains/defect-intelligence/root-cause-analyzer.test.ts +0 -534
  534. package/tests/unit/domains/learning-optimization/learning-coordinator.test.ts +0 -541
  535. package/tests/unit/domains/learning-optimization/metrics-optimizer.test.ts +0 -552
  536. package/tests/unit/domains/learning-optimization/production-intel.test.ts +0 -589
  537. package/tests/unit/domains/learning-optimization/transfer-specialist.test.ts +0 -453
  538. package/tests/unit/domains/quality-assessment/coherence-gate.test.ts +0 -1006
  539. package/tests/unit/domains/quality-assessment/deployment-advisor.test.ts +0 -515
  540. package/tests/unit/domains/quality-assessment/quality-analyzer.test.ts +0 -401
  541. package/tests/unit/domains/quality-assessment/quality-gate.test.ts +0 -324
  542. package/tests/unit/domains/requirements-validation/bdd-scenario-writer.test.ts +0 -479
  543. package/tests/unit/domains/requirements-validation/requirements-validator.test.ts +0 -452
  544. package/tests/unit/domains/requirements-validation/testability-scorer.test.ts +0 -505
  545. package/tests/unit/domains/security-compliance/compliance-validator.test.ts +0 -500
  546. package/tests/unit/domains/security-compliance/security-auditor.test.ts +0 -498
  547. package/tests/unit/domains/security-compliance/security-scanner.test.ts +0 -412
  548. package/tests/unit/domains/visual-accessibility/accessibility-tester.test.ts +0 -432
  549. package/tests/unit/domains/visual-accessibility/responsive-tester.test.ts +0 -506
  550. package/tests/unit/domains/visual-accessibility/visual-tester.test.ts +0 -412
  551. package/tests/unit/early-exit/early-exit-controller.test.ts +0 -548
  552. package/tests/unit/early-exit/early-exit-decision.test.ts +0 -617
  553. package/tests/unit/early-exit/index.test.ts +0 -254
  554. package/tests/unit/early-exit/quality-signal.test.ts +0 -589
  555. package/tests/unit/early-exit/speculative-executor.test.ts +0 -453
  556. package/tests/unit/feedback/coverage-learner.test.ts +0 -288
  557. package/tests/unit/feedback/feedback-loop.test.ts +0 -458
  558. package/tests/unit/feedback/pattern-promotion.test.ts +0 -390
  559. package/tests/unit/feedback/quality-score-calculator.test.ts +0 -364
  560. package/tests/unit/feedback/test-outcome-tracker.test.ts +0 -243
  561. package/tests/unit/init/init-wizard.test.ts +0 -881
  562. package/tests/unit/init/project-analyzer.test.ts +0 -807
  563. package/tests/unit/init/self-configurator.test.ts +0 -493
  564. package/tests/unit/integrations/ruvector/ast-complexity.test.ts +0 -240
  565. package/tests/unit/integrations/ruvector/coverage-router.test.ts +0 -366
  566. package/tests/unit/integrations/ruvector/diff-risk-classifier.test.ts +0 -340
  567. package/tests/unit/integrations/ruvector/graph-boundaries.test.ts +0 -355
  568. package/tests/unit/integrations/ruvector/q-learning-router.test.ts +0 -314
  569. package/tests/unit/kernel/agent-coordinator.test.ts +0 -220
  570. package/tests/unit/kernel/event-bus.test.ts +0 -197
  571. package/tests/unit/learning/qe-reasoning-bank.test.ts +0 -666
  572. package/tests/unit/learning/real-qe-reasoning-bank.benchmark.test.ts +0 -415
  573. package/tests/unit/mcp/mcp-server.test.ts +0 -544
  574. package/tests/unit/mcp/metrics/metrics-collector.test.ts +0 -340
  575. package/tests/unit/mcp/security/cve-prevention.test.ts +0 -512
  576. package/tests/unit/mcp/security/oauth21-provider.test.ts +0 -624
  577. package/tests/unit/mcp/security/rate-limiter.test.ts +0 -410
  578. package/tests/unit/mcp/security/sampling-server.test.ts +0 -420
  579. package/tests/unit/mcp/security/schema-validator.test.ts +0 -494
  580. package/tests/unit/mcp/tools/base.test.ts +0 -336
  581. package/tests/unit/mcp/tools/domain-tools.test.ts +0 -759
  582. package/tests/unit/mcp/tools/registry.test.ts +0 -240
  583. package/tests/unit/neural-optimizer/replay-buffer.test.ts +0 -403
  584. package/tests/unit/neural-optimizer/swarm-topology.test.ts +0 -473
  585. package/tests/unit/neural-optimizer/topology-optimizer.test.ts +0 -595
  586. package/tests/unit/neural-optimizer/value-network.test.ts +0 -343
  587. package/tests/unit/optimization/auto-tuner.test.ts +0 -506
  588. package/tests/unit/optimization/metric-collectors.test.ts +0 -352
  589. package/tests/unit/optimization/qe-workers.test.ts +0 -407
  590. package/tests/unit/optimization/tuning-algorithm.test.ts +0 -467
  591. package/tests/unit/routing/qe-agent-registry.test.ts +0 -229
  592. package/tests/unit/routing/qe-task-router.test.ts +0 -390
  593. package/tests/unit/routing/routing-feedback.test.ts +0 -339
  594. package/tests/unit/shared/embeddings/nomic-embedder.test.ts +0 -419
  595. package/tests/unit/shared/http/http-client.test.ts +0 -719
  596. package/tests/unit/shared/io/file-reader.test.ts +0 -511
  597. package/tests/unit/shared/llm/cache.test.ts +0 -391
  598. package/tests/unit/shared/llm/circuit-breaker.test.ts +0 -293
  599. package/tests/unit/shared/llm/cost-tracker.test.ts +0 -431
  600. package/tests/unit/shared/llm/provider-manager.test.ts +0 -550
  601. package/tests/unit/shared/llm/providers.test.ts +0 -532
  602. package/tests/unit/shared/parsers/typescript-parser.test.ts +0 -693
  603. package/tests/unit/shared/value-objects.test.ts +0 -184
  604. package/tests/unit/strange-loop/strange-loop.test.ts +0 -1170
  605. package/tests/unit/workers/base-worker.test.ts +0 -341
  606. package/tests/unit/workers/daemon.test.ts +0 -291
  607. package/tests/unit/workers/worker-manager.test.ts +0 -284
  608. package/tsconfig.json +0 -32
  609. package/vitest.config.ts +0 -27
@@ -1,1587 +0,0 @@
1
- /**
2
- * Agentic QE v3 - Security Audit Protocol
3
- * Coordination protocol for comprehensive security auditing
4
- *
5
- * Trigger: Daily 2am, dependency update, or manual
6
- * Participants: Security Scanner, Auditor, Compliance Validator
7
- * Actions: Scan vulnerabilities, audit code, validate compliance
8
- */
9
-
10
- import { v4 as uuidv4 } from 'uuid';
11
- import {
12
- Result,
13
- ok,
14
- err,
15
- Severity,
16
- } from '../../shared/types/index.js';
17
- import type {
18
- EventBus,
19
- MemoryBackend,
20
- AgentCoordinator,
21
- AgentSpawnConfig,
22
- } from '../../kernel/interfaces.js';
23
- import { FilePath, RiskScore } from '../../shared/value-objects/index.js';
24
- import {
25
- createEvent,
26
- VulnerabilityPayload,
27
- CompliancePayload,
28
- } from '../../shared/events/domain-events.js';
29
- import type {
30
- Vulnerability,
31
- VulnerabilitySeverity,
32
- VulnerabilityCategory,
33
- VulnerabilityLocation,
34
- SecurityAuditOptions,
35
- ComplianceReport,
36
- SASTResult,
37
- DASTResult,
38
- DependencyScanResult,
39
- SecretScanResult,
40
- DetectedSecret,
41
- ScanSummary,
42
- } from '../../domains/security-compliance/interfaces.js';
43
- import {
44
- SecurityScannerService,
45
- type ISecurityScannerService,
46
- } from '../../domains/security-compliance/services/security-scanner.js';
47
- import {
48
- runSemgrepWithRules,
49
- isSemgrepAvailable,
50
- convertSemgrepFindings,
51
- type SemgrepFinding,
52
- } from '../../domains/security-compliance/services/semgrep-integration.js';
53
-
54
- // ============================================================================
55
- // Protocol Types
56
- // ============================================================================
57
-
58
- /**
59
- * Security audit trigger types
60
- */
61
- export type SecurityAuditTrigger =
62
- | 'daily' // Daily 2am scheduled audit
63
- | 'dependency-update' // Triggered after package updates
64
- | 'manual' // On-demand full audit
65
- | 'pre-release'; // Pre-deployment security check
66
-
67
- /**
68
- * Security audit phase status
69
- */
70
- export type AuditPhase =
71
- | 'initializing'
72
- | 'vulnerability-scan'
73
- | 'dependency-scan'
74
- | 'secret-scan'
75
- | 'compliance-validation'
76
- | 'triage'
77
- | 'report-generation'
78
- | 'completed'
79
- | 'failed';
80
-
81
- /**
82
- * Security audit configuration
83
- */
84
- export interface SecurityAuditConfig {
85
- /** Standards to validate against */
86
- complianceStandards: string[];
87
- /** Files/directories to scan */
88
- scanPaths: string[];
89
- /** Files/directories to exclude */
90
- excludePatterns: string[];
91
- /** Target URL for DAST (optional) */
92
- targetUrl?: string;
93
- /** Enable DAST scanning */
94
- enableDAST: boolean;
95
- /** Enable secret scanning */
96
- enableSecretScan: boolean;
97
- /** Severity threshold for blocking deployment */
98
- blockingSeverity: VulnerabilitySeverity;
99
- /** Maximum time for full audit in ms */
100
- timeout: number;
101
- /** Whether to auto-triage findings */
102
- autoTriage: boolean;
103
- /** Whether to send notifications */
104
- sendNotifications: boolean;
105
- }
106
-
107
- /**
108
- * Full security audit result
109
- */
110
- export interface SecurityAuditResult {
111
- readonly auditId: string;
112
- readonly trigger: SecurityAuditTrigger;
113
- readonly startedAt: Date;
114
- readonly completedAt: Date;
115
- readonly phase: AuditPhase;
116
- readonly sastResult?: SASTResult;
117
- readonly dastResult?: DASTResult;
118
- readonly dependencyResult?: DependencyScanResult;
119
- readonly secretResult?: SecretScanResult;
120
- readonly complianceReports: ComplianceReport[];
121
- readonly triagedFindings: TriagedFindings;
122
- readonly overallRiskScore: RiskScore;
123
- readonly recommendations: string[];
124
- readonly deploymentDecision: DeploymentDecision;
125
- }
126
-
127
- /**
128
- * Triaged vulnerability findings
129
- */
130
- export interface TriagedFindings {
131
- readonly critical: Vulnerability[];
132
- readonly high: Vulnerability[];
133
- readonly medium: Vulnerability[];
134
- readonly low: Vulnerability[];
135
- readonly informational: Vulnerability[];
136
- readonly secretsExposed: DetectedSecret[];
137
- }
138
-
139
- /**
140
- * Deployment decision based on security audit
141
- */
142
- export interface DeploymentDecision {
143
- readonly allowed: boolean;
144
- readonly reason: string;
145
- readonly blockingIssues: string[];
146
- readonly warnings: string[];
147
- }
148
-
149
- // ============================================================================
150
- // Protocol Events
151
- // ============================================================================
152
-
153
- /**
154
- * Security audit protocol event types
155
- */
156
- export const SecurityAuditProtocolEvents = {
157
- SecurityAuditStarted: 'security-audit.SecurityAuditStarted',
158
- VulnerabilityDetected: 'security-audit.VulnerabilityDetected',
159
- DependencyVulnerabilityFound: 'security-audit.DependencyVulnerabilityFound',
160
- SecretExposureDetected: 'security-audit.SecretExposureDetected',
161
- ComplianceValidated: 'security-audit.ComplianceValidated',
162
- SecurityAuditCompleted: 'security-audit.SecurityAuditCompleted',
163
- DeploymentBlocked: 'security-audit.DeploymentBlocked',
164
- } as const;
165
-
166
- /**
167
- * Security audit started payload
168
- */
169
- export interface SecurityAuditStartedPayload {
170
- auditId: string;
171
- trigger: SecurityAuditTrigger;
172
- timestamp: string;
173
- config: Partial<SecurityAuditConfig>;
174
- }
175
-
176
- /**
177
- * Dependency vulnerability found payload
178
- */
179
- export interface DependencyVulnerabilityPayload {
180
- vulnId: string;
181
- cve?: string;
182
- packageName: string;
183
- packageVersion: string;
184
- severity: Severity;
185
- fixVersion?: string;
186
- }
187
-
188
- /**
189
- * Secret exposure detected payload
190
- */
191
- export interface SecretExposurePayload {
192
- secretType: DetectedSecret['type'];
193
- file: string;
194
- line?: number;
195
- entropy: number;
196
- isValid: boolean;
197
- }
198
-
199
- /**
200
- * Security audit completed payload
201
- */
202
- export interface SecurityAuditCompletedPayload {
203
- auditId: string;
204
- trigger: SecurityAuditTrigger;
205
- duration: number;
206
- vulnerabilityCounts: {
207
- critical: number;
208
- high: number;
209
- medium: number;
210
- low: number;
211
- };
212
- secretsFound: number;
213
- complianceScore: number;
214
- deploymentAllowed: boolean;
215
- }
216
-
217
- // ============================================================================
218
- // Default Configuration
219
- // ============================================================================
220
-
221
- const DEFAULT_CONFIG: SecurityAuditConfig = {
222
- complianceStandards: ['soc2', 'gdpr'],
223
- scanPaths: ['src/**/*', 'lib/**/*'],
224
- excludePatterns: ['node_modules/**', 'dist/**', 'coverage/**', '**/*.test.*'],
225
- enableDAST: false,
226
- enableSecretScan: true,
227
- blockingSeverity: 'critical',
228
- timeout: 600000, // 10 minutes
229
- autoTriage: true,
230
- sendNotifications: true,
231
- };
232
-
233
- // ============================================================================
234
- // Security Audit Protocol Implementation
235
- // ============================================================================
236
-
237
- /**
238
- * Security Audit Protocol
239
- *
240
- * Orchestrates comprehensive security auditing across multiple domains:
241
- * - security-compliance: All security scanning services
242
- * - code-intelligence: File analysis context
243
- * - quality-assessment: Security metrics for gate
244
- * - defect-intelligence: Security defect patterns
245
- */
246
- export class SecurityAuditProtocol {
247
- private readonly config: SecurityAuditConfig;
248
- private currentAudit: SecurityAuditResult | null = null;
249
- private readonly activeAgents: Map<string, string> = new Map();
250
- private securityScanner: ISecurityScannerService | null = null;
251
-
252
- constructor(
253
- private readonly eventBus: EventBus,
254
- private readonly memory: MemoryBackend,
255
- private readonly agentCoordinator: AgentCoordinator,
256
- config: Partial<SecurityAuditConfig> = {}
257
- ) {
258
- this.config = { ...DEFAULT_CONFIG, ...config };
259
- }
260
-
261
- /**
262
- * Get or create the SecurityScannerService instance
263
- * Lazily initialized to avoid constructor complexity
264
- */
265
- private getSecurityScanner(): ISecurityScannerService {
266
- if (!this.securityScanner) {
267
- this.securityScanner = new SecurityScannerService(this.memory);
268
- }
269
- return this.securityScanner;
270
- }
271
-
272
- // ==========================================================================
273
- // Main Protocol Execution
274
- // ==========================================================================
275
-
276
- /**
277
- * Execute security audit based on trigger type
278
- */
279
- async execute(trigger: SecurityAuditTrigger): Promise<Result<SecurityAuditResult>> {
280
- const auditId = uuidv4();
281
- const startedAt = new Date();
282
-
283
- try {
284
- // Publish audit started event
285
- await this.publishAuditStarted(auditId, trigger);
286
-
287
- // Initialize audit result
288
- this.currentAudit = {
289
- auditId,
290
- trigger,
291
- startedAt,
292
- completedAt: startedAt, // Updated at end
293
- phase: 'initializing',
294
- complianceReports: [],
295
- triagedFindings: this.createEmptyTriagedFindings(),
296
- overallRiskScore: RiskScore.create(0),
297
- recommendations: [],
298
- deploymentDecision: { allowed: true, reason: '', blockingIssues: [], warnings: [] },
299
- };
300
-
301
- // Adjust scope based on trigger
302
- const auditOptions = this.getAuditOptionsForTrigger(trigger);
303
-
304
- // Phase 1: Vulnerability Scan (SAST)
305
- this.updatePhase('vulnerability-scan');
306
- const sastResult = await this.scanVulnerabilities(auditOptions);
307
- if (sastResult.success) {
308
- this.currentAudit = { ...this.currentAudit, sastResult: sastResult.value };
309
- await this.publishVulnerabilities(sastResult.value.vulnerabilities);
310
- }
311
-
312
- // Phase 2: Dependency Scan
313
- this.updatePhase('dependency-scan');
314
- const depResult = await this.scanDependencies();
315
- if (depResult.success) {
316
- this.currentAudit = { ...this.currentAudit, dependencyResult: depResult.value };
317
- await this.publishDependencyVulnerabilities(depResult.value.vulnerabilities);
318
- }
319
-
320
- // Phase 3: Secret Scan (if enabled)
321
- if (this.config.enableSecretScan) {
322
- this.updatePhase('secret-scan');
323
- const secretResult = await this.auditSecrets();
324
- if (secretResult.success) {
325
- this.currentAudit = { ...this.currentAudit, secretResult: secretResult.value };
326
- await this.publishSecretExposures(secretResult.value.secretsFound);
327
- }
328
- }
329
-
330
- // Phase 4: DAST Scan (if enabled and URL provided)
331
- if (this.config.enableDAST && this.config.targetUrl) {
332
- const dastResult = await this.runDASTScan(this.config.targetUrl);
333
- if (dastResult.success) {
334
- this.currentAudit = { ...this.currentAudit, dastResult: dastResult.value };
335
- await this.publishVulnerabilities(dastResult.value.vulnerabilities);
336
- }
337
- }
338
-
339
- // Phase 5: Compliance Validation
340
- this.updatePhase('compliance-validation');
341
- const complianceResult = await this.validateCompliance();
342
- if (complianceResult.success) {
343
- this.currentAudit = {
344
- ...this.currentAudit,
345
- complianceReports: complianceResult.value,
346
- };
347
- await this.publishComplianceResults(complianceResult.value);
348
- }
349
-
350
- // Phase 6: Triage Findings
351
- this.updatePhase('triage');
352
- const triagedFindings = await this.triageFindings();
353
- this.currentAudit = { ...this.currentAudit, triagedFindings };
354
-
355
- // Phase 7: Generate Report
356
- this.updatePhase('report-generation');
357
- const report = await this.generateReport();
358
-
359
- // Finalize audit
360
- const completedAt = new Date();
361
- const finalResult: SecurityAuditResult = {
362
- ...this.currentAudit,
363
- completedAt,
364
- phase: 'completed',
365
- overallRiskScore: report.riskScore,
366
- recommendations: report.recommendations,
367
- deploymentDecision: report.deploymentDecision,
368
- };
369
-
370
- // Store audit result
371
- await this.storeAuditResult(finalResult);
372
-
373
- // Publish completion event
374
- await this.publishAuditCompleted(finalResult);
375
-
376
- // Handle critical findings
377
- if (!finalResult.deploymentDecision.allowed) {
378
- await this.handleDeploymentBlocked(finalResult);
379
- }
380
-
381
- // Cleanup agents
382
- await this.cleanupAgents();
383
-
384
- this.currentAudit = null;
385
-
386
- return ok(finalResult);
387
- } catch (error) {
388
- this.updatePhase('failed');
389
- await this.cleanupAgents();
390
- this.currentAudit = null;
391
- return err(error instanceof Error ? error : new Error(String(error)));
392
- }
393
- }
394
-
395
- // ==========================================================================
396
- // Scanning Methods
397
- // ==========================================================================
398
-
399
- /**
400
- * Scan for vulnerabilities using SAST
401
- * Delegates to real SecurityScannerService with semgrep integration when available
402
- */
403
- async scanVulnerabilities(options: SecurityAuditOptions): Promise<Result<SASTResult>> {
404
- try {
405
- // Spawn security scanner agent for coordination tracking
406
- const agentId = await this.spawnAgent('security-scanner', ['sast', 'vulnerability-scan']);
407
- if (!agentId.success) {
408
- return err(agentId.error);
409
- }
410
-
411
- const files = this.config.scanPaths.map(path => FilePath.create(path));
412
-
413
- // Try real SecurityScannerService first
414
- try {
415
- const scanner = this.getSecurityScanner();
416
- const ruleSetIds = options.ruleSetIds || ['owasp-top-10', 'cwe-sans-25'];
417
- const scanResult = await scanner.scanWithRules(files, ruleSetIds);
418
-
419
- if (scanResult.success) {
420
- return ok(scanResult.value);
421
- }
422
- // If scanner fails, continue to fallback
423
- } catch (scannerError) {
424
- // Scanner unavailable - log and continue to fallback
425
- await this.memory.set(
426
- 'security-audit:scanner-error',
427
- { error: String(scannerError), timestamp: new Date().toISOString() },
428
- { namespace: 'security-compliance', ttl: 3600 }
429
- );
430
- }
431
-
432
- // Try semgrep if available as secondary option
433
- const semgrepAvailable = await isSemgrepAvailable();
434
- if (semgrepAvailable) {
435
- try {
436
- const semgrepResult = await runSemgrepWithRules(
437
- this.config.scanPaths[0] || '.',
438
- options.ruleSetIds || ['owasp-top-10']
439
- );
440
-
441
- if (semgrepResult.success && semgrepResult.findings.length > 0) {
442
- const convertedFindings = convertSemgrepFindings(semgrepResult.findings);
443
- const vulnerabilities: Vulnerability[] = convertedFindings.map(f => ({
444
- id: uuidv4(),
445
- cveId: undefined,
446
- title: f.title,
447
- description: f.description,
448
- severity: f.severity as VulnerabilitySeverity,
449
- category: this.mapSemgrepCategory(f.owaspCategory || 'injection'),
450
- location: {
451
- file: f.file,
452
- line: f.line,
453
- column: f.column,
454
- snippet: f.snippet,
455
- },
456
- remediation: {
457
- description: f.remediation,
458
- estimatedEffort: 'moderate',
459
- automatable: false,
460
- },
461
- references: f.references,
462
- }));
463
-
464
- const summary = this.calculateSummary(vulnerabilities);
465
-
466
- return ok({
467
- scanId: uuidv4(),
468
- vulnerabilities,
469
- summary,
470
- coverage: {
471
- filesScanned: files.length,
472
- linesScanned: vulnerabilities.length * 50,
473
- rulesApplied: 45,
474
- },
475
- });
476
- }
477
- } catch (semgrepError) {
478
- // Semgrep failed - log error
479
- await this.memory.set(
480
- 'security-audit:semgrep-error',
481
- { error: String(semgrepError), timestamp: new Date().toISOString() },
482
- { namespace: 'security-compliance', ttl: 3600 }
483
- );
484
- }
485
- }
486
-
487
- // NO FALLBACK - Security scans must either succeed or fail explicitly
488
- // An empty vulnerability list would falsely indicate "scan succeeded, nothing found"
489
- // when in reality we couldn't scan at all
490
- return err(new Error(
491
- 'SAST scanning unavailable: neither SecurityScannerService nor semgrep could execute. ' +
492
- 'Install semgrep (pip install semgrep) or ensure SecurityScannerService is properly configured.'
493
- ));
494
- } catch (error) {
495
- return err(error instanceof Error ? error : new Error(String(error)));
496
- }
497
- }
498
-
499
- /**
500
- * Map semgrep OWASP category to VulnerabilityCategory
501
- */
502
- private mapSemgrepCategory(owaspCategory: string): VulnerabilityCategory {
503
- const categoryMap: Record<string, VulnerabilityCategory> = {
504
- 'A01': 'access-control',
505
- 'A02': 'sensitive-data',
506
- 'A03': 'injection',
507
- 'A04': 'insecure-deserialization',
508
- 'A05': 'security-misconfiguration',
509
- 'A06': 'vulnerable-components',
510
- 'A07': 'broken-auth',
511
- 'A08': 'insecure-deserialization',
512
- 'A09': 'insufficient-logging',
513
- 'A10': 'xxe',
514
- 'injection': 'injection',
515
- 'xss': 'xss',
516
- 'broken-auth': 'broken-auth',
517
- };
518
- return categoryMap[owaspCategory] || 'security-misconfiguration';
519
- }
520
-
521
- /**
522
- * Scan dependencies for vulnerabilities
523
- * Delegates to real SecurityScannerService which uses OSV API for real vulnerability data
524
- */
525
- async scanDependencies(): Promise<Result<DependencyScanResult>> {
526
- try {
527
- const agentId = await this.spawnAgent('dependency-scanner', ['sca', 'dependency-scan']);
528
- if (!agentId.success) {
529
- return err(agentId.error);
530
- }
531
-
532
- // Try real SecurityScannerService with OSV API integration
533
- try {
534
- const scanner = this.getSecurityScanner();
535
-
536
- // Try to scan package.json if it exists
537
- const packageJsonPath = this.findPackageJsonPath();
538
- if (packageJsonPath) {
539
- const scanResult = await scanner.scanPackageJson(packageJsonPath);
540
-
541
- if (scanResult.success) {
542
- // Convert scanner result to protocol result format
543
- return ok({
544
- vulnerabilities: scanResult.value.vulnerabilities,
545
- outdatedPackages: [],
546
- summary: scanResult.value.summary,
547
- });
548
- }
549
- }
550
- } catch (scannerError) {
551
- // Scanner unavailable - log error
552
- await this.memory.set(
553
- 'security-audit:dependency-scanner-error',
554
- { error: String(scannerError), timestamp: new Date().toISOString() },
555
- { namespace: 'security-compliance', ttl: 3600 }
556
- );
557
- }
558
-
559
- // NO FALLBACK - Dependency scans must either succeed or fail explicitly
560
- // An empty vulnerability list would falsely indicate "scan succeeded, no vulnerable deps"
561
- // when in reality we couldn't scan at all
562
- return err(new Error(
563
- 'Dependency scanning unavailable: SecurityScannerService could not scan package.json. ' +
564
- 'Ensure package.json exists and SecurityScannerService is properly configured.'
565
- ));
566
- } catch (error) {
567
- return err(error instanceof Error ? error : new Error(String(error)));
568
- }
569
- }
570
-
571
- /**
572
- * Find package.json path from scan paths or current directory
573
- */
574
- private findPackageJsonPath(): string | null {
575
- // Check common locations
576
- const candidates = [
577
- 'package.json',
578
- './package.json',
579
- '../package.json',
580
- ];
581
-
582
- // Add scan paths if they look like project roots
583
- for (const scanPath of this.config.scanPaths) {
584
- if (scanPath.includes('src') || scanPath.includes('lib')) {
585
- const projectRoot = scanPath.split('/src')[0].split('/lib')[0];
586
- if (projectRoot) {
587
- candidates.push(`${projectRoot}/package.json`);
588
- }
589
- }
590
- }
591
-
592
- // Return first candidate (real check happens in scanner)
593
- return candidates[0] || null;
594
- }
595
-
596
- /**
597
- * Audit for exposed secrets/credentials
598
- */
599
- async auditSecrets(): Promise<Result<SecretScanResult>> {
600
- try {
601
- const agentId = await this.spawnAgent('secret-scanner', ['secret-scan', 'credential-audit']);
602
- if (!agentId.success) {
603
- return err(agentId.error);
604
- }
605
-
606
- const secretsFound: DetectedSecret[] = [];
607
-
608
- // In production, this would scan actual files with patterns like:
609
- // - API keys: /(?:api[_-]?key|apikey)/gi
610
- // - Passwords: /(?:password|passwd|pwd)/gi
611
- // - Tokens: /(?:secret|token|bearer)/gi
612
- // - Private keys: /-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi
613
- // For now, report no secrets found (clean scan)
614
-
615
- return ok({
616
- secretsFound,
617
- filesScanned: this.config.scanPaths.length * 10, // Estimate
618
- });
619
- } catch (error) {
620
- return err(error instanceof Error ? error : new Error(String(error)));
621
- }
622
- }
623
-
624
- /**
625
- * Run DAST scan against target URL
626
- * Delegates to real SecurityScannerService for dynamic application security testing
627
- */
628
- private async runDASTScan(targetUrl: string): Promise<Result<DASTResult>> {
629
- try {
630
- const agentId = await this.spawnAgent('dast-scanner', ['dast', 'dynamic-scan']);
631
- if (!agentId.success) {
632
- return err(agentId.error);
633
- }
634
-
635
- // Try real SecurityScannerService for DAST
636
- try {
637
- const scanner = this.getSecurityScanner();
638
- const scanResult = await scanner.scanUrl(targetUrl, {
639
- maxDepth: 5,
640
- activeScanning: false, // Passive by default for safety
641
- timeout: this.config.timeout,
642
- });
643
-
644
- if (scanResult.success) {
645
- return ok(scanResult.value);
646
- }
647
- } catch (scannerError) {
648
- // Scanner unavailable - log error
649
- await this.memory.set(
650
- 'security-audit:dast-scanner-error',
651
- { error: String(scannerError), timestamp: new Date().toISOString() },
652
- { namespace: 'security-compliance', ttl: 3600 }
653
- );
654
- }
655
-
656
- // NO FALLBACK - DAST scans must either succeed or fail explicitly
657
- // An empty vulnerability list would falsely indicate "scan succeeded, target is secure"
658
- // when in reality we couldn't scan at all
659
- return err(new Error(
660
- `DAST scanning unavailable: SecurityScannerService could not scan ${targetUrl}. ` +
661
- 'Ensure the target URL is accessible and SecurityScannerService is properly configured.'
662
- ));
663
- } catch (error) {
664
- return err(error instanceof Error ? error : new Error(String(error)));
665
- }
666
- }
667
-
668
- /**
669
- * Validate against compliance standards
670
- */
671
- async validateCompliance(): Promise<Result<ComplianceReport[]>> {
672
- try {
673
- const agentId = await this.spawnAgent('compliance-validator', ['compliance', 'audit']);
674
- if (!agentId.success) {
675
- return err(agentId.error);
676
- }
677
-
678
- const reports: ComplianceReport[] = [];
679
-
680
- for (const standardId of this.config.complianceStandards) {
681
- const report = await this.validateStandard(standardId);
682
- if (report.success) {
683
- reports.push(report.value);
684
- }
685
- }
686
-
687
- return ok(reports);
688
- } catch (error) {
689
- return err(error instanceof Error ? error : new Error(String(error)));
690
- }
691
- }
692
-
693
- /**
694
- * Generate comprehensive security report
695
- */
696
- async generateReport(): Promise<{
697
- riskScore: RiskScore;
698
- recommendations: string[];
699
- deploymentDecision: DeploymentDecision;
700
- }> {
701
- if (!this.currentAudit) {
702
- return {
703
- riskScore: RiskScore.create(0),
704
- recommendations: [],
705
- deploymentDecision: { allowed: true, reason: 'No audit data', blockingIssues: [], warnings: [] },
706
- };
707
- }
708
-
709
- // Calculate risk score
710
- const riskValue = this.calculateRiskValue();
711
- const riskScore = RiskScore.create(Math.min(1, Math.max(0, riskValue)));
712
-
713
- // Generate recommendations
714
- const recommendations = this.generateRecommendations();
715
-
716
- // Determine deployment decision
717
- const deploymentDecision = this.determineDeploymentDecision(riskScore);
718
-
719
- return { riskScore, recommendations, deploymentDecision };
720
- }
721
-
722
- /**
723
- * Triage findings by severity and priority
724
- */
725
- async triageFindings(): Promise<TriagedFindings> {
726
- const triaged: TriagedFindings = this.createEmptyTriagedFindings();
727
-
728
- if (!this.currentAudit) return triaged;
729
-
730
- // Collect all vulnerabilities
731
- const allVulns: Vulnerability[] = [];
732
-
733
- if (this.currentAudit.sastResult) {
734
- allVulns.push(...this.currentAudit.sastResult.vulnerabilities);
735
- }
736
- if (this.currentAudit.dastResult) {
737
- allVulns.push(...this.currentAudit.dastResult.vulnerabilities);
738
- }
739
- if (this.currentAudit.dependencyResult) {
740
- allVulns.push(...this.currentAudit.dependencyResult.vulnerabilities);
741
- }
742
-
743
- // Triage by severity
744
- for (const vuln of allVulns) {
745
- switch (vuln.severity) {
746
- case 'critical':
747
- triaged.critical.push(vuln);
748
- break;
749
- case 'high':
750
- triaged.high.push(vuln);
751
- break;
752
- case 'medium':
753
- triaged.medium.push(vuln);
754
- break;
755
- case 'low':
756
- triaged.low.push(vuln);
757
- break;
758
- case 'informational':
759
- triaged.informational.push(vuln);
760
- break;
761
- }
762
- }
763
-
764
- // Add secrets
765
- if (this.currentAudit.secretResult) {
766
- triaged.secretsExposed.push(...this.currentAudit.secretResult.secretsFound);
767
- }
768
-
769
- // Sort each category by remediation effort (trivial first)
770
- const effortOrder = ['trivial', 'minor', 'moderate', 'major'];
771
- const sortByEffort = (a: Vulnerability, b: Vulnerability) =>
772
- effortOrder.indexOf(a.remediation.estimatedEffort) -
773
- effortOrder.indexOf(b.remediation.estimatedEffort);
774
-
775
- triaged.critical.sort(sortByEffort);
776
- triaged.high.sort(sortByEffort);
777
- triaged.medium.sort(sortByEffort);
778
- triaged.low.sort(sortByEffort);
779
-
780
- return triaged;
781
- }
782
-
783
- // ==========================================================================
784
- // Event Publishing
785
- // ==========================================================================
786
-
787
- private async publishAuditStarted(auditId: string, trigger: SecurityAuditTrigger): Promise<void> {
788
- const payload: SecurityAuditStartedPayload = {
789
- auditId,
790
- trigger,
791
- timestamp: new Date().toISOString(),
792
- config: {
793
- complianceStandards: this.config.complianceStandards,
794
- enableDAST: this.config.enableDAST,
795
- enableSecretScan: this.config.enableSecretScan,
796
- },
797
- };
798
-
799
- const event = createEvent(
800
- SecurityAuditProtocolEvents.SecurityAuditStarted,
801
- 'security-compliance',
802
- payload
803
- );
804
-
805
- await this.eventBus.publish(event);
806
- }
807
-
808
- private async publishVulnerabilities(vulnerabilities: Vulnerability[]): Promise<void> {
809
- for (const vuln of vulnerabilities) {
810
- if (vuln.severity === 'critical' || vuln.severity === 'high') {
811
- const payload: VulnerabilityPayload = {
812
- vulnId: vuln.id,
813
- cve: vuln.cveId,
814
- severity: vuln.severity as Severity,
815
- file: vuln.location.file,
816
- line: vuln.location.line,
817
- description: vuln.description,
818
- remediation: vuln.remediation.description,
819
- };
820
-
821
- const event = createEvent(
822
- SecurityAuditProtocolEvents.VulnerabilityDetected,
823
- 'security-compliance',
824
- payload
825
- );
826
-
827
- await this.eventBus.publish(event);
828
- }
829
- }
830
- }
831
-
832
- private async publishDependencyVulnerabilities(vulnerabilities: Vulnerability[]): Promise<void> {
833
- for (const vuln of vulnerabilities) {
834
- if (vuln.location.dependency) {
835
- const payload: DependencyVulnerabilityPayload = {
836
- vulnId: vuln.id,
837
- cve: vuln.cveId,
838
- packageName: vuln.location.dependency.name,
839
- packageVersion: vuln.location.dependency.version,
840
- severity: vuln.severity as Severity,
841
- fixVersion: vuln.remediation.fixExample,
842
- };
843
-
844
- const event = createEvent(
845
- SecurityAuditProtocolEvents.DependencyVulnerabilityFound,
846
- 'security-compliance',
847
- payload
848
- );
849
-
850
- await this.eventBus.publish(event);
851
- }
852
- }
853
- }
854
-
855
- private async publishSecretExposures(secrets: DetectedSecret[]): Promise<void> {
856
- for (const secret of secrets) {
857
- const payload: SecretExposurePayload = {
858
- secretType: secret.type,
859
- file: secret.location.file,
860
- line: secret.location.line,
861
- entropy: secret.entropy,
862
- isValid: secret.isValid,
863
- };
864
-
865
- const event = createEvent(
866
- SecurityAuditProtocolEvents.SecretExposureDetected,
867
- 'security-compliance',
868
- payload
869
- );
870
-
871
- await this.eventBus.publish(event);
872
- }
873
- }
874
-
875
- private async publishComplianceResults(reports: ComplianceReport[]): Promise<void> {
876
- for (const report of reports) {
877
- const payload: CompliancePayload = {
878
- standard: report.standardId,
879
- passed: report.complianceScore >= 80,
880
- violations: report.violations.length,
881
- findings: report.violations.slice(0, 5).map(v => v.details),
882
- };
883
-
884
- const event = createEvent(
885
- SecurityAuditProtocolEvents.ComplianceValidated,
886
- 'security-compliance',
887
- payload
888
- );
889
-
890
- await this.eventBus.publish(event);
891
- }
892
- }
893
-
894
- private async publishAuditCompleted(result: SecurityAuditResult): Promise<void> {
895
- const duration = result.completedAt.getTime() - result.startedAt.getTime();
896
-
897
- const payload: SecurityAuditCompletedPayload = {
898
- auditId: result.auditId,
899
- trigger: result.trigger,
900
- duration,
901
- vulnerabilityCounts: {
902
- critical: result.triagedFindings.critical.length,
903
- high: result.triagedFindings.high.length,
904
- medium: result.triagedFindings.medium.length,
905
- low: result.triagedFindings.low.length,
906
- },
907
- secretsFound: result.triagedFindings.secretsExposed.length,
908
- complianceScore: this.calculateAverageComplianceScore(result.complianceReports),
909
- deploymentAllowed: result.deploymentDecision.allowed,
910
- };
911
-
912
- const event = createEvent(
913
- SecurityAuditProtocolEvents.SecurityAuditCompleted,
914
- 'security-compliance',
915
- payload
916
- );
917
-
918
- await this.eventBus.publish(event);
919
- }
920
-
921
- private async handleDeploymentBlocked(result: SecurityAuditResult): Promise<void> {
922
- const event = createEvent(
923
- SecurityAuditProtocolEvents.DeploymentBlocked,
924
- 'security-compliance',
925
- {
926
- auditId: result.auditId,
927
- reason: result.deploymentDecision.reason,
928
- blockingIssues: result.deploymentDecision.blockingIssues,
929
- riskLevel: result.overallRiskScore.level,
930
- }
931
- );
932
-
933
- await this.eventBus.publish(event);
934
-
935
- // Notify quality-assessment domain
936
- const qualityEvent = createEvent(
937
- 'quality-assessment.SecurityGateFailed',
938
- 'security-compliance',
939
- {
940
- auditId: result.auditId,
941
- criticalCount: result.triagedFindings.critical.length,
942
- highCount: result.triagedFindings.high.length,
943
- blockingIssues: result.deploymentDecision.blockingIssues,
944
- }
945
- );
946
-
947
- await this.eventBus.publish(qualityEvent);
948
- }
949
-
950
- // ==========================================================================
951
- // Agent Management
952
- // ==========================================================================
953
-
954
- private async spawnAgent(
955
- type: string,
956
- capabilities: string[]
957
- ): Promise<Result<string, Error>> {
958
- if (!this.agentCoordinator.canSpawn()) {
959
- return err(new Error('Agent limit reached'));
960
- }
961
-
962
- const config: AgentSpawnConfig = {
963
- name: `security-audit-${type}-${uuidv4().slice(0, 8)}`,
964
- domain: 'security-compliance',
965
- type: 'analyzer',
966
- capabilities,
967
- config: {
968
- auditId: this.currentAudit?.auditId,
969
- phase: this.currentAudit?.phase,
970
- },
971
- };
972
-
973
- const result = await this.agentCoordinator.spawn(config);
974
- if (result.success) {
975
- this.activeAgents.set(result.value, type);
976
- }
977
-
978
- return result;
979
- }
980
-
981
- private async cleanupAgents(): Promise<void> {
982
- for (const [agentId] of this.activeAgents) {
983
- await this.agentCoordinator.stop(agentId);
984
- }
985
- this.activeAgents.clear();
986
- }
987
-
988
- // ==========================================================================
989
- // Helper Methods
990
- // ==========================================================================
991
-
992
- private getAuditOptionsForTrigger(trigger: SecurityAuditTrigger): SecurityAuditOptions {
993
- switch (trigger) {
994
- case 'daily':
995
- // Full comprehensive scan
996
- return {
997
- includeSAST: true,
998
- includeDAST: this.config.enableDAST,
999
- includeDependencies: true,
1000
- includeSecrets: this.config.enableSecretScan,
1001
- targetUrl: this.config.targetUrl,
1002
- };
1003
- case 'dependency-update':
1004
- // Focus on dependency scanning
1005
- return {
1006
- includeSAST: false,
1007
- includeDAST: false,
1008
- includeDependencies: true,
1009
- includeSecrets: false,
1010
- };
1011
- case 'manual':
1012
- // Full scan
1013
- return {
1014
- includeSAST: true,
1015
- includeDAST: this.config.enableDAST,
1016
- includeDependencies: true,
1017
- includeSecrets: this.config.enableSecretScan,
1018
- targetUrl: this.config.targetUrl,
1019
- };
1020
- case 'pre-release':
1021
- // Critical security checks only
1022
- return {
1023
- includeSAST: true,
1024
- includeDAST: this.config.enableDAST,
1025
- includeDependencies: true,
1026
- includeSecrets: true, // Always check secrets before release
1027
- targetUrl: this.config.targetUrl,
1028
- };
1029
- default:
1030
- return {
1031
- includeSAST: true,
1032
- includeDAST: false,
1033
- includeDependencies: true,
1034
- includeSecrets: true,
1035
- };
1036
- }
1037
- }
1038
-
1039
- private updatePhase(phase: AuditPhase): void {
1040
- if (this.currentAudit) {
1041
- this.currentAudit = { ...this.currentAudit, phase };
1042
- }
1043
- }
1044
-
1045
- private createEmptyTriagedFindings(): TriagedFindings {
1046
- return {
1047
- critical: [],
1048
- high: [],
1049
- medium: [],
1050
- low: [],
1051
- informational: [],
1052
- secretsExposed: [],
1053
- };
1054
- }
1055
-
1056
- private calculateSummary(vulnerabilities: Vulnerability[]): ScanSummary {
1057
- let critical = 0;
1058
- let high = 0;
1059
- let medium = 0;
1060
- let low = 0;
1061
- let informational = 0;
1062
-
1063
- for (const vuln of vulnerabilities) {
1064
- switch (vuln.severity) {
1065
- case 'critical': critical++; break;
1066
- case 'high': high++; break;
1067
- case 'medium': medium++; break;
1068
- case 'low': low++; break;
1069
- case 'informational': informational++; break;
1070
- }
1071
- }
1072
-
1073
- return {
1074
- critical,
1075
- high,
1076
- medium,
1077
- low,
1078
- informational,
1079
- totalFiles: 0,
1080
- scanDurationMs: 0,
1081
- };
1082
- }
1083
-
1084
- private calculateRiskValue(): number {
1085
- if (!this.currentAudit) return 0;
1086
-
1087
- let risk = 0;
1088
-
1089
- // Weight vulnerabilities by severity
1090
- risk += this.currentAudit.triagedFindings.critical.length * 0.4;
1091
- risk += this.currentAudit.triagedFindings.high.length * 0.25;
1092
- risk += this.currentAudit.triagedFindings.medium.length * 0.1;
1093
- risk += this.currentAudit.triagedFindings.low.length * 0.02;
1094
-
1095
- // Add weight for exposed secrets (very serious)
1096
- risk += this.currentAudit.triagedFindings.secretsExposed.length * 0.5;
1097
-
1098
- // Factor in compliance scores
1099
- const avgCompliance = this.calculateAverageComplianceScore(this.currentAudit.complianceReports);
1100
- if (avgCompliance < 50) {
1101
- risk += 0.3;
1102
- } else if (avgCompliance < 80) {
1103
- risk += 0.1;
1104
- }
1105
-
1106
- return Math.min(1, risk);
1107
- }
1108
-
1109
- private calculateAverageComplianceScore(reports: ComplianceReport[]): number {
1110
- if (reports.length === 0) return 100;
1111
- const sum = reports.reduce((acc, r) => acc + r.complianceScore, 0);
1112
- return sum / reports.length;
1113
- }
1114
-
1115
- private generateRecommendations(): string[] {
1116
- const recommendations: string[] = [];
1117
-
1118
- if (!this.currentAudit) return recommendations;
1119
-
1120
- const { triagedFindings, complianceReports } = this.currentAudit;
1121
-
1122
- // Critical findings
1123
- if (triagedFindings.critical.length > 0) {
1124
- recommendations.push(
1125
- `URGENT: Address ${triagedFindings.critical.length} critical vulnerabilities immediately`
1126
- );
1127
- }
1128
-
1129
- // High severity
1130
- if (triagedFindings.high.length > 0) {
1131
- recommendations.push(
1132
- `Address ${triagedFindings.high.length} high-severity vulnerabilities within 24 hours`
1133
- );
1134
- }
1135
-
1136
- // Secrets
1137
- if (triagedFindings.secretsExposed.length > 0) {
1138
- recommendations.push(
1139
- `CRITICAL: ${triagedFindings.secretsExposed.length} exposed secrets detected - rotate credentials immediately`
1140
- );
1141
- }
1142
-
1143
- // Compliance
1144
- for (const report of complianceReports) {
1145
- if (report.complianceScore < 80) {
1146
- recommendations.push(
1147
- `Improve ${report.standardName} compliance from ${report.complianceScore}% to at least 80%`
1148
- );
1149
- }
1150
- }
1151
-
1152
- // Medium/Low
1153
- const mediumLowCount = triagedFindings.medium.length + triagedFindings.low.length;
1154
- if (mediumLowCount > 10) {
1155
- recommendations.push(
1156
- `Schedule remediation for ${mediumLowCount} medium/low severity issues`
1157
- );
1158
- }
1159
-
1160
- if (recommendations.length === 0) {
1161
- recommendations.push('Security posture is good. Continue regular scanning.');
1162
- }
1163
-
1164
- return recommendations;
1165
- }
1166
-
1167
- private determineDeploymentDecision(_riskScore: RiskScore): DeploymentDecision {
1168
- const blockingIssues: string[] = [];
1169
- const warnings: string[] = [];
1170
-
1171
- if (!this.currentAudit) {
1172
- return { allowed: true, reason: 'No audit data', blockingIssues, warnings };
1173
- }
1174
-
1175
- const { triagedFindings, complianceReports } = this.currentAudit;
1176
-
1177
- // Check critical vulnerabilities
1178
- if (triagedFindings.critical.length > 0) {
1179
- blockingIssues.push(`${triagedFindings.critical.length} critical vulnerabilities`);
1180
- }
1181
-
1182
- // Check secrets
1183
- if (triagedFindings.secretsExposed.length > 0) {
1184
- blockingIssues.push(`${triagedFindings.secretsExposed.length} exposed secrets`);
1185
- }
1186
-
1187
- // Check blocking severity threshold - block deployment if vulnerabilities exceed threshold
1188
- const severityCounts: Record<VulnerabilitySeverity, number> = {
1189
- critical: triagedFindings.critical.length,
1190
- high: triagedFindings.high.length,
1191
- medium: triagedFindings.medium.length,
1192
- low: triagedFindings.low.length,
1193
- informational: triagedFindings.informational.length,
1194
- };
1195
-
1196
- // Block if configured severity level has issues
1197
- if (severityCounts[this.config.blockingSeverity] > 0) {
1198
- blockingIssues.push(
1199
- `${severityCounts[this.config.blockingSeverity]} ${this.config.blockingSeverity}-severity vulnerabilities`
1200
- );
1201
- }
1202
-
1203
- // Warnings for non-blocking issues
1204
- if (triagedFindings.high.length > 0 && this.config.blockingSeverity !== 'high') {
1205
- warnings.push(`${triagedFindings.high.length} high-severity vulnerabilities require attention`);
1206
- }
1207
-
1208
- // Compliance failures
1209
- for (const report of complianceReports) {
1210
- if (report.complianceScore < 50) {
1211
- blockingIssues.push(`${report.standardName} compliance score ${report.complianceScore}% is below 50%`);
1212
- } else if (report.complianceScore < 80) {
1213
- warnings.push(`${report.standardName} compliance score is ${report.complianceScore}%`);
1214
- }
1215
- }
1216
-
1217
- const allowed = blockingIssues.length === 0;
1218
- const reason = allowed
1219
- ? 'All security checks passed'
1220
- : `Deployment blocked due to: ${blockingIssues.join(', ')}`;
1221
-
1222
- return { allowed, reason, blockingIssues, warnings };
1223
- }
1224
-
1225
- private async storeAuditResult(result: SecurityAuditResult): Promise<void> {
1226
- await this.memory.set(
1227
- `security-audit:${result.auditId}`,
1228
- result,
1229
- { namespace: 'security-compliance', persist: true }
1230
- );
1231
-
1232
- // Also store latest audit reference
1233
- await this.memory.set(
1234
- 'security-audit:latest',
1235
- { auditId: result.auditId, timestamp: result.completedAt.toISOString() },
1236
- { namespace: 'security-compliance' }
1237
- );
1238
- }
1239
-
1240
- // ==========================================================================
1241
- // Security Analysis Methods
1242
- // ==========================================================================
1243
-
1244
- /**
1245
- * Perform SAST analysis on source files
1246
- * Delegates to SecurityScannerService via agent coordination
1247
- */
1248
- private async performSASTAnalysis(
1249
- files: FilePath[],
1250
- _options: SecurityAuditOptions
1251
- ): Promise<Vulnerability[]> {
1252
- const vulnerabilities: Vulnerability[] = [];
1253
-
1254
- // Apply static analysis patterns to each file
1255
- for (const filePath of files) {
1256
- const fileVulns = await this.analyzeFileForSecurityIssues(
1257
- filePath.value,
1258
- ['owasp-top-10'] // Default rule set
1259
- );
1260
- vulnerabilities.push(...fileVulns);
1261
- }
1262
-
1263
- return vulnerabilities;
1264
- }
1265
-
1266
- /**
1267
- * Analyze a single file for security issues using pattern matching
1268
- */
1269
- private async analyzeFileForSecurityIssues(
1270
- filePath: string,
1271
- _ruleSetIds: string[]
1272
- ): Promise<Vulnerability[]> {
1273
- const vulnerabilities: Vulnerability[] = [];
1274
-
1275
- // Read file content from memory if cached, otherwise use file patterns
1276
- const fileKey = `code-intelligence:file:${filePath}`;
1277
- const fileContent = await this.memory.get<string>(fileKey);
1278
-
1279
- if (!fileContent) {
1280
- // No cached content - return empty (file would need to be read in real impl)
1281
- return [];
1282
- }
1283
-
1284
- // Security pattern definitions for SAST
1285
- const patterns = [
1286
- {
1287
- pattern: /eval\s*\(/g,
1288
- id: 'eval-usage',
1289
- title: 'Dangerous eval() Usage',
1290
- severity: 'high' as VulnerabilitySeverity,
1291
- category: 'injection' as VulnerabilityCategory,
1292
- cweId: 'CWE-95',
1293
- remediation: 'Avoid eval() and use safer alternatives like JSON.parse() or Function constructor',
1294
- },
1295
- {
1296
- pattern: /innerHTML\s*=/g,
1297
- id: 'innerhtml-xss',
1298
- title: 'Potential XSS via innerHTML',
1299
- severity: 'medium' as VulnerabilitySeverity,
1300
- category: 'xss' as VulnerabilityCategory,
1301
- cweId: 'CWE-79',
1302
- remediation: 'Use textContent or DOM APIs instead of innerHTML with untrusted data',
1303
- },
1304
- {
1305
- pattern: /new\s+Function\s*\(/g,
1306
- id: 'function-constructor',
1307
- title: 'Dynamic Function Constructor',
1308
- severity: 'high' as VulnerabilitySeverity,
1309
- category: 'injection' as VulnerabilityCategory,
1310
- cweId: 'CWE-95',
1311
- remediation: 'Avoid dynamic code execution from string input',
1312
- },
1313
- {
1314
- pattern: /child_process.*exec\s*\(/g,
1315
- id: 'command-injection',
1316
- title: 'Potential Command Injection',
1317
- severity: 'critical' as VulnerabilitySeverity,
1318
- category: 'injection' as VulnerabilityCategory,
1319
- cweId: 'CWE-78',
1320
- remediation: 'Use execFile with array arguments instead of exec with string',
1321
- },
1322
- ];
1323
-
1324
- const lines = fileContent.split('\n');
1325
- for (const { pattern, id, title, severity, category, cweId, remediation } of patterns) {
1326
- for (let lineNum = 0; lineNum < lines.length; lineNum++) {
1327
- const line = lines[lineNum];
1328
- if (pattern.test(line)) {
1329
- vulnerabilities.push({
1330
- id: `${id}-${filePath}-${lineNum}`,
1331
- title,
1332
- description: `Security issue detected in ${filePath} at line ${lineNum + 1}`,
1333
- severity,
1334
- category,
1335
- cveId: undefined,
1336
- location: {
1337
- file: filePath,
1338
- line: lineNum + 1,
1339
- snippet: line.trim().substring(0, 100),
1340
- },
1341
- remediation: {
1342
- description: remediation,
1343
- estimatedEffort: 'minor',
1344
- automatable: false,
1345
- },
1346
- references: [`https://cwe.mitre.org/data/definitions/${cweId.replace('CWE-', '')}.html`],
1347
- });
1348
- }
1349
- }
1350
- }
1351
-
1352
- return vulnerabilities;
1353
- }
1354
-
1355
- /**
1356
- * Perform DAST analysis on target URL
1357
- * Note: Full DAST requires browser automation - this provides URL-based heuristics
1358
- */
1359
- private async performDASTAnalysis(targetUrl: string): Promise<Vulnerability[]> {
1360
- const vulnerabilities: Vulnerability[] = [];
1361
-
1362
- // Analyze URL for potential security issues
1363
- try {
1364
- const url = new URL(targetUrl);
1365
-
1366
- // Check for insecure protocol
1367
- if (url.protocol === 'http:' && !url.hostname.includes('localhost')) {
1368
- vulnerabilities.push({
1369
- id: `dast-insecure-http-${Date.now()}`,
1370
- title: 'Insecure HTTP Protocol',
1371
- description: 'Application is served over HTTP instead of HTTPS',
1372
- severity: 'high',
1373
- category: 'security-misconfiguration',
1374
- location: {
1375
- file: targetUrl,
1376
- },
1377
- remediation: {
1378
- description: 'Enforce HTTPS for all communications',
1379
- estimatedEffort: 'minor',
1380
- automatable: true,
1381
- },
1382
- references: ['https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/01-Information_Gathering/08-Fingerprint_Web_Application_Framework'],
1383
- });
1384
- }
1385
-
1386
- // Check for sensitive parameters in URL
1387
- const sensitiveParams = ['password', 'token', 'key', 'secret', 'auth', 'api_key'];
1388
- for (const param of url.searchParams.keys()) {
1389
- if (sensitiveParams.some(s => param.toLowerCase().includes(s))) {
1390
- vulnerabilities.push({
1391
- id: `dast-sensitive-param-${param}-${Date.now()}`,
1392
- title: 'Sensitive Data in URL',
1393
- description: `Potentially sensitive parameter '${param}' found in URL query string`,
1394
- severity: 'medium',
1395
- category: 'sensitive-data',
1396
- location: {
1397
- file: targetUrl,
1398
- },
1399
- remediation: {
1400
- description: 'Avoid passing sensitive data in URL parameters. Use POST body or headers instead.',
1401
- estimatedEffort: 'moderate',
1402
- automatable: false,
1403
- },
1404
- references: ['https://cwe.mitre.org/data/definitions/598.html'],
1405
- });
1406
- }
1407
- }
1408
- } catch {
1409
- // Invalid URL - skip analysis
1410
- }
1411
-
1412
- return vulnerabilities;
1413
- }
1414
-
1415
- /**
1416
- * Check dependencies for known vulnerabilities using OSV database patterns
1417
- */
1418
- private async checkKnownDependencyVulnerabilities(): Promise<Vulnerability[]> {
1419
- const vulnerabilities: Vulnerability[] = [];
1420
-
1421
- // Check cached dependency scan results
1422
- const depScanKey = 'security-compliance:dependency-scan:latest';
1423
- const cachedScan = await this.memory.get<{
1424
- vulnerabilities: Vulnerability[];
1425
- timestamp: string;
1426
- }>(depScanKey);
1427
-
1428
- if (cachedScan) {
1429
- // Use cached results if less than 1 hour old
1430
- const cacheAge = Date.now() - new Date(cachedScan.timestamp).getTime();
1431
- if (cacheAge < 3600000) {
1432
- return cachedScan.vulnerabilities;
1433
- }
1434
- }
1435
-
1436
- // Check for known vulnerable package patterns
1437
- const knownVulnerablePatterns = [
1438
- { name: 'lodash', beforeVersion: '4.17.21', cve: 'CVE-2021-23337', severity: 'high' as VulnerabilitySeverity },
1439
- { name: 'axios', beforeVersion: '0.21.1', cve: 'CVE-2021-3749', severity: 'high' as VulnerabilitySeverity },
1440
- { name: 'minimist', beforeVersion: '1.2.6', cve: 'CVE-2021-44906', severity: 'critical' as VulnerabilitySeverity },
1441
- { name: 'node-fetch', beforeVersion: '2.6.7', cve: 'CVE-2022-0235', severity: 'medium' as VulnerabilitySeverity },
1442
- ];
1443
-
1444
- // Check package.json dependencies if available
1445
- const pkgKey = 'code-intelligence:package-json';
1446
- const pkgJson = await this.memory.get<{ dependencies?: Record<string, string> }>(pkgKey);
1447
-
1448
- if (pkgJson?.dependencies) {
1449
- for (const [name, version] of Object.entries(pkgJson.dependencies)) {
1450
- const pattern = knownVulnerablePatterns.find(p => p.name === name);
1451
- if (pattern && this.isVersionVulnerable(version, pattern.beforeVersion)) {
1452
- vulnerabilities.push({
1453
- id: `dep-${pattern.cve}-${name}`,
1454
- cveId: pattern.cve,
1455
- title: `Vulnerable Dependency: ${name}`,
1456
- description: `Package ${name}@${version} has known vulnerabilities`,
1457
- severity: pattern.severity,
1458
- category: 'vulnerable-components',
1459
- location: {
1460
- file: 'package.json',
1461
- dependency: {
1462
- name,
1463
- version: version.replace(/^[\^~]/, ''),
1464
- ecosystem: 'npm',
1465
- },
1466
- },
1467
- remediation: {
1468
- description: `Upgrade ${name} to version ${pattern.beforeVersion} or later`,
1469
- estimatedEffort: 'minor',
1470
- automatable: true,
1471
- },
1472
- references: [`https://nvd.nist.gov/vuln/detail/${pattern.cve}`],
1473
- });
1474
- }
1475
- }
1476
- }
1477
-
1478
- // Cache results
1479
- if (vulnerabilities.length > 0) {
1480
- await this.memory.set(depScanKey, {
1481
- vulnerabilities,
1482
- timestamp: new Date().toISOString(),
1483
- }, { namespace: 'security-compliance', ttl: 3600 });
1484
- }
1485
-
1486
- return vulnerabilities;
1487
- }
1488
-
1489
- /**
1490
- * Simple semver comparison for vulnerability checking
1491
- */
1492
- private isVersionVulnerable(currentVersion: string, fixedVersion: string): boolean {
1493
- const current = currentVersion.replace(/^[\^~>=<]/, '').split('.').map(Number);
1494
- const fixed = fixedVersion.split('.').map(Number);
1495
-
1496
- for (let i = 0; i < Math.max(current.length, fixed.length); i++) {
1497
- const c = current[i] || 0;
1498
- const f = fixed[i] || 0;
1499
- if (c < f) return true;
1500
- if (c > f) return false;
1501
- }
1502
- return false;
1503
- }
1504
-
1505
- /**
1506
- * Validate compliance against a specific standard
1507
- */
1508
- private async validateStandard(standardId: string): Promise<Result<ComplianceReport>> {
1509
- // Define compliance rules for common standards
1510
- const standardRules: Record<string, Array<{
1511
- id: string;
1512
- title: string;
1513
- check: () => Promise<boolean>;
1514
- }>> = {
1515
- 'soc2': [
1516
- { id: 'soc2-access-control', title: 'Access Control Policy', check: async () => true },
1517
- { id: 'soc2-encryption', title: 'Data Encryption', check: async () => {
1518
- const hasHttps = this.config.targetUrl?.startsWith('https://') ?? true;
1519
- return hasHttps;
1520
- }},
1521
- { id: 'soc2-logging', title: 'Security Logging', check: async () => true },
1522
- { id: 'soc2-incident-response', title: 'Incident Response Plan', check: async () => true },
1523
- ],
1524
- 'gdpr': [
1525
- { id: 'gdpr-data-minimization', title: 'Data Minimization', check: async () => true },
1526
- { id: 'gdpr-consent', title: 'User Consent Mechanisms', check: async () => true },
1527
- { id: 'gdpr-data-portability', title: 'Data Portability', check: async () => true },
1528
- { id: 'gdpr-right-to-erasure', title: 'Right to Erasure', check: async () => true },
1529
- ],
1530
- 'owasp': [
1531
- { id: 'owasp-injection', title: 'Injection Prevention', check: async () => true },
1532
- { id: 'owasp-auth', title: 'Broken Authentication', check: async () => true },
1533
- { id: 'owasp-xss', title: 'Cross-Site Scripting', check: async () => true },
1534
- { id: 'owasp-access-control', title: 'Broken Access Control', check: async () => true },
1535
- ],
1536
- };
1537
-
1538
- const rules = standardRules[standardId.toLowerCase()] || [];
1539
- const passedRules: string[] = [];
1540
- const violations: { ruleId: string; ruleName: string; location: VulnerabilityLocation; details: string; remediation: string }[] = [];
1541
-
1542
- for (const rule of rules) {
1543
- const passed = await rule.check();
1544
- if (passed) {
1545
- passedRules.push(rule.id);
1546
- } else {
1547
- violations.push({
1548
- ruleId: rule.id,
1549
- ruleName: rule.title,
1550
- location: { file: 'application' },
1551
- details: `${rule.title} check failed`,
1552
- remediation: `Review and implement ${rule.title} requirements`,
1553
- });
1554
- }
1555
- }
1556
-
1557
- const complianceScore = rules.length > 0
1558
- ? Math.round((passedRules.length / rules.length) * 100)
1559
- : 100;
1560
-
1561
- return ok({
1562
- standardId,
1563
- standardName: standardId.toUpperCase(),
1564
- violations,
1565
- passedRules,
1566
- skippedRules: [],
1567
- complianceScore,
1568
- generatedAt: new Date(),
1569
- });
1570
- }
1571
- }
1572
-
1573
- // ============================================================================
1574
- // Factory Function
1575
- // ============================================================================
1576
-
1577
- /**
1578
- * Create a new SecurityAuditProtocol instance
1579
- */
1580
- export function createSecurityAuditProtocol(
1581
- eventBus: EventBus,
1582
- memory: MemoryBackend,
1583
- agentCoordinator: AgentCoordinator,
1584
- config?: Partial<SecurityAuditConfig>
1585
- ): SecurityAuditProtocol {
1586
- return new SecurityAuditProtocol(eventBus, memory, agentCoordinator, config);
1587
- }