Files
Profa 2b71ae4eb8 release: v1.3.6 - Security, Quality & Documentation Overhaul
## 🔒 Security Fixes

### eval() Removal - Critical Security Vulnerability Fixed
- **File**: `src/agents/TestDataArchitectAgent.ts`
- **Impact**: Eliminated arbitrary code execution risk
- **Solution**: Implemented safe expression evaluator with parser-based approach
- **Supports**:
  - Comparison operators: `===`, `!==`, `==`, `!=`, `>`, `<`, `>=`, `<=`
  - Logical operators: `&&`, `||`
  - Boolean values: `true`, `false`
  - Number and string comparisons
- **Lines**: 102 lines added (safeEvaluateExpression + parseValue methods)

## ✨ UX Enhancements

### CLAUDE.md Append Strategy - User-Requested Feature
- **File**: `src/cli/commands/init.ts`
- **User Feedback**: "AQE instructions should append by default, not prepend"
- **Interactive Mode**: Prompts user to choose prepend or append
- **--yes Mode**: Defaults to append (less disruptive to existing configs)
- **Features**:
  - Auto-backup existing CLAUDE.md to CLAUDE.md.backup
  - Clear visual separator (---) between sections
  - User confirmation messages
- **Lines**: 49 lines modified

### CLI Skills Count Fix - Accurate Display
- **File**: `src/cli/commands/skills/index.ts`
- **Before**: Showed "8/17" (hardcoded, incorrect)
- **After**: Shows "34/34" (dynamic, accurate)
- **Solution**: Added `getTotalQESkillsCount()` method using `QE_SKILLS.flatMap()`
- **Future-proof**: Auto-updates when skills added
- **Lines**: 11 lines modified

## 🎓 New Agent - Cherry-Picked from PR #22

### CodeComplexityAnalyzerAgent Integration
- **Author**: @mondweep (PR #22)
- **Purpose**: Educational code complexity analysis and refactoring recommendations
- **Files**: 7 files, 2,758 lines of code
- **Capabilities**:
  - Cyclomatic complexity calculation
  - Cognitive complexity analysis
  - AI-powered refactoring suggestions
  - Quality scoring (0-100 scale)
  - Memory integration (`aqe/complexity/*`)
- **Test Coverage**: 529 lines, 13+ test scenarios
- **Documentation**: 754 lines (README + Claude agent definition)
- **Examples**: 871 lines (3 interactive examples)

## 🔧 Code Quality Improvements

### Agent Enhancements
- **BaseAgent.ts**: 136 lines modified
  - Improved property access patterns
  - Better encapsulation with public accessors
  - Enhanced lifecycle management

- **TestGeneratorAgent.ts**: 377 lines added
  - Comprehensive null safety improvements
  - Enhanced error handling
  - Better context validation

- **QualityGateAgent.ts**: 64 lines modified
  - Improved context handling
  - Better validation logic

### MCP Handler Improvements
- **test-generate.ts**: 33 lines modified (better parameter handling)
- **quality-analyze.ts**: 28 lines modified (context fix)
- **regression-risk-analyze.ts**: 85 lines modified (parameter aliasing fix)

### Infrastructure Additions
- **AgentLifecycleManager.ts**: 274 new lines (lifecycle coordination)
- **SwarmMemoryManager.ts**: 3 lines modified (improved coordination)
- **AgentRegistry.ts**: 20 lines added (better agent registration)

## 🧪 Testing Enhancements

### New Integration Tests (5 Test Suites)
- **fleet-management.integration.test.ts**: 491 lines
- **parameter-validation.integration.test.ts**: 606 lines
- **quality-analyze.integration.test.ts**: 393 lines
- **regression-risk.integration.test.ts**: 505 lines
- **test-execution.integration.test.ts**: 536 lines
- **test-harness.ts**: 289 lines (shared test utilities)
- **Total**: 2,820 lines of integration test coverage

### Enhanced Unit Tests
- **BaseAgent.enhanced.test.ts**: 909 lines (comprehensive BaseAgent testing)
- **TestGeneratorAgent.null-safety.test.ts**: 1,511 lines (null safety validation)
- **Total**: 2,420 lines of new unit test coverage

### Test Improvements
- **PredictionTools.test.ts**: 118 lines modified
- **Agent.test.ts**: 11 lines modified

## 📚 Documentation Expansion (27,439 insertions)

### Release Documentation (7 documents)
- **RELEASE-1.3.6-PREPARATION.md**: 443 lines (complete release checklist)
- **SECURITY-SCAN-RELEASE-1.3.6.md**: 422 lines (security validation)
- **THREE-ISSUE-FIXES-SUMMARY.md**: 196 lines (user-reported fixes)
- **CHERRY-PICK-PR22-SUMMARY.md**: 412 lines (integration details)
- **FINAL-STATUS-REPORT-2025-10-30.md**: 403 lines (status summary)
- **FINAL-MCP-VERIFICATION-SUMMARY.md**: 338 lines (MCP validation)
- **MCP-PRODUCTION-READINESS-REPORT.md**: 318 lines (production readiness)

### Technical Documentation (7 documents)
- **MCP-TOOLS-REFERENCE.md**: 1,555 lines (complete MCP API reference)
- **MCP-TOOLS-USER-GUIDE.md**: 626 lines (user guide)
- **MCP-TOOLS-AUTO-GENERATED.md**: 934 lines (auto-generated docs)
- **MCP-TOOLS-MIGRATION.md**: 437 lines (migration guide)
- **complexity-mitigation-plan.md**: 537 lines (code quality roadmap)
- **swarm-execution-report.md**: 985 lines (execution analysis)
- **HONEST-IMPLEMENTATION-ANALYSIS.md**: 62 lines (transparency report)

### Fix Documentation (7 documents)
- **MCP-TOOLS-COMPLETE-FIX-REPORT.md**: 619 lines (comprehensive fix report)
- **three-issue-fixes.md**: 345 lines (user-reported fixes)
- **quality-analyze-context-fix.md**: 195 lines
- **regression-risk-parameter-aliasing.md**: 303 lines
- **test-generator-agent-null-safety-fixes.md**: 422 lines
- **typescript-compilation-errors-fixed-2025-10-30.md**: 273 lines
- **MCP-TOOLS-FIX-SUMMARY.md**: 272 lines

### Refactoring Plans (4 documents)
- **swarm-memory-manager-refactoring-plan.md**: 796 lines
- **base-agent-refactoring-plan.md**: 658 lines
- **refactoring-summary.md**: 404 lines
- **REFACTORING_STATUS.md**: 210 lines

### Testing Documentation (6 documents)
- **mcp-tools-test-report.md**: 1,260 lines (comprehensive test report)
- **testing-workflow.md**: 691 lines (MCP testing guide)
- **TestGeneratorAgent-test-plan.md**: 318 lines (test plan)
- **coverage-analysis-2025-10-30.md**: 661 lines (coverage report)
- **regression-validation-report-2025-10-30.md**: 450 lines (regression validation)
- **README.md** (tests/integration/mcp): 277 lines (integration test guide)

### CI/CD Documentation (3 documents)
- **mcp-cicd-pipeline.md**: 402 lines (pipeline architecture)
- **mcp-pipeline-setup-summary.md**: 343 lines (setup guide)
- **mcp-cicd-implementation-notes.md**: 280 lines (implementation notes)

### MCP Verification (2 documents)
- **MCP-VERIFICATION-SUMMARY.md**: 286 lines
- **PR-22-ANALYSIS.md**: 373 lines

### Coverage Analysis (2 documents)
- **coverage-analysis-2025-10-30.md**: 661 lines
- **coverage-analysis-summary.json**: 417 lines (structured data)

## 🛠️ Scripts & Automation (5 Scripts, 2,117 Lines)

### New Utility Scripts
- **validate-mcp-tools.js**: 280 lines (MCP tool validation)
- **generate-mcp-report.js**: 252 lines (report generation)
- **generate-mcp-docs.js**: 270 lines (documentation generation)
- **verify-mcp-production-readiness.js**: 564 lines (production checks)
- **test-issue-fixes.js**: 224 lines (fix verification)
- **mcp-tools-summary.json**: 344 lines (structured summary)

## 📊 Examples & Guides

### MCP Integration Examples (2 Examples)
- **basic-test-generation.js**: 200 lines (starter example)
- **quality-analysis-pipeline.js**: 360 lines (advanced workflow)

## ⚙️ CI/CD Enhancements

### GitHub Actions Workflow
- **.github/workflows/mcp-tools-test.yml**: 197 lines
  - Automated MCP tool testing
  - Multi-environment validation
  - Production readiness checks

### Git Hooks
- **.husky/pre-commit**: 14 lines (pre-commit validation)

## 📦 Configuration Updates

### Version & Dependencies
- **package.json**: Version bumped to 1.3.6
- **package-lock.json**: Dependency lock updated
- **README.md**: Version references updated (27 lines modified)
- **.claude/settings.json**: 4 lines modified

### CHANGELOG
- **CHANGELOG.md**: 37 lines added
  - Complete v1.3.6 changelog entry
  - Security fixes documented
  - UX enhancements documented
  - Testing improvements documented

## 📈 Statistics Summary

### Code Changes
- **78 files changed**
- **27,439 insertions** (+)
- **181 deletions** (-)
- **Net change**: +27,258 lines

### Breakdown by Category
- **Source Code**: ~1,200 lines (agents, handlers, infrastructure)
- **Tests**: ~5,240 lines (integration + unit tests)
- **Documentation**: ~18,000 lines (guides, reports, plans)
- **Scripts**: ~2,117 lines (automation utilities)
- **Examples**: ~560 lines (MCP examples)
- **CI/CD**: ~211 lines (workflows + hooks)

### Quality Metrics
- ✅ **TypeScript Compilation**: 0 errors (16 errors fixed)
- ✅ **Security Vulnerabilities**: 0 critical (1 fixed)
- ✅ **Integration Tests**: 5 new test suites, 2,820 lines
- ✅ **Unit Tests**: 2,420 new lines
- ✅ **Documentation**: 100% comprehensive coverage
- ✅ **Backward Compatibility**: 100% maintained

## 🎯 User Impact

### Immediate Benefits
1. **Security**: Eliminates arbitrary code execution vulnerability
2. **UX**: Less disruptive CLAUDE.md initialization
3. **Accuracy**: Correct skills count display (34/34)
4. **Quality**: CodeComplexityAnalyzerAgent for refactoring guidance
5. **Reliability**: 16 TypeScript errors resolved

### Developer Experience
1. **Better Documentation**: 18,000+ lines of guides and references
2. **Better Testing**: 5,240 new lines of test coverage
3. **Better Tooling**: 2,117 lines of automation scripts
4. **Better Examples**: MCP integration examples
5. **Better CI/CD**: Automated testing and validation

## 🔄 Migration & Compatibility

### Breaking Changes
- **NONE** - Fully backward compatible

### Deprecations
- **NONE**

### New Features (Opt-in)
- CodeComplexityAnalyzerAgent (available via Claude Code or MCP)
- Interactive CLAUDE.md placement (interactive mode only)

## ✅ Verification

### Pre-Release Checks
- ✅ TypeScript compilation: 0 errors
- ✅ All three user-reported fixes verified
- ✅ Integration tests passing
- ✅ Documentation complete
- ✅ CHANGELOG updated
- ✅ Version numbers updated (package.json, README.md)
- ✅ Security scan: No vulnerabilities
- ✅ Backward compatibility verified

### Production Readiness
- ✅ MCP tools validated (54 tools)
- ✅ Agent registry verified (17 agents)
- ✅ Skills library verified (34 skills)
- ✅ CI/CD pipeline configured
- ✅ Pre-commit hooks installed

## 🙏 Acknowledgments

- **@mondweep**: CodeComplexityAnalyzerAgent contribution (PR #22)
- **User Feedback**: CLAUDE.md append strategy request
- **User Feedback**: CLI skills count display bug report
- **User Feedback**: eval() security concern

## 📝 Release Notes

**Version**: 1.3.6
**Date**: 2025-10-30
**Type**: Security & Quality Patch Release
**Status**: Production Ready

**Upgrade Recommendation**: 🔴 **HIGH PRIORITY**
- Security vulnerability fixed (eval() removal)
- User experience improvements
- Enhanced stability (16 TypeScript errors fixed)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 18:23:09 +00:00

17 KiB

Complete Testing Workflow with MCP Tools

Comprehensive guide to building end-to-end testing workflows using Agentic QE MCP tools.


Table of Contents

  1. Overview
  2. Basic Workflow
  3. Advanced Patterns
  4. CI/CD Integration
  5. Error Handling
  6. Performance Optimization

Overview

A complete testing workflow typically involves:

  1. Fleet Initialization - Setup agent coordination
  2. Agent Spawning - Create specialized agents
  3. Test Generation - AI-powered test creation
  4. Test Execution - Parallel test running
  5. Coverage Analysis - Gap detection and optimization
  6. Quality Analysis - Comprehensive metrics
  7. Reporting - Generate reports for stakeholders

Basic Workflow

Step 1: Initialize Fleet

const fleet = await mcp__agentic_qe__fleet_init({
  config: {
    topology: 'hierarchical',
    maxAgents: 10,
    testingFocus: ['unit', 'integration'],
    environments: ['development'],
    frameworks: ['jest']
  },
  projectContext: {
    repositoryUrl: 'https://github.com/company/project',
    language: 'typescript',
    buildSystem: 'npm'
  }
});

console.log(`Fleet initialized: ${fleet.fleetId}`);
console.log(`Capacity: ${fleet.maxAgents} agents`);

Step 2: Spawn Specialized Agents

// Test generator for creating tests
const testGen = await mcp__agentic_qe__agent_spawn({
  spec: {
    type: 'test-generator',
    name: 'test-gen-001',
    capabilities: [
      'unit-tests',
      'integration-tests',
      'data-synthesis'
    ]
  },
  fleetId: fleet.fleetId
});

// Coverage analyzer for gap detection
const coverageAnalyzer = await mcp__agentic_qe__agent_spawn({
  spec: {
    type: 'coverage-analyzer',
    name: 'coverage-001',
    capabilities: [
      'gap-detection',
      'sublinear-analysis',
      'recommendations'
    ]
  },
  fleetId: fleet.fleetId
});

// Quality gate for validation
const qualityGate = await mcp__agentic_qe__agent_spawn({
  spec: {
    type: 'quality-gate',
    name: 'qg-001',
    capabilities: [
      'policy-enforcement',
      'risk-assessment',
      'decision-making'
    ]
  },
  fleetId: fleet.fleetId
});

console.log('Agents ready:', [testGen.name, coverageAnalyzer.name, qualityGate.name]);

Step 3: Generate Tests

// Generate comprehensive test suite
const generation = await mcp__agentic_qe__test_generate({
  spec: {
    type: 'unit',
    sourceCode: {
      repositoryUrl: 'https://github.com/company/project',
      branch: 'develop',
      language: 'typescript',
      testPatterns: [
        'src/**/*.ts',
        '!src/**/*.test.ts',
        '!src/**/*.spec.ts'
      ]
    },
    coverageTarget: 85,
    frameworks: ['jest'],
    synthesizeData: true
  },
  agentId: testGen.agentId
});

console.log(`Generated ${generation.generatedTests} tests`);
console.log(`Test files: ${generation.testFiles.length}`);
console.log(`Estimated coverage: ${generation.estimatedCoverage}%`);

// Store test plan in memory for other agents
await mcp__agentic_qe__memory_store({
  key: 'aqe/test-plan/generated',
  value: {
    testFiles: generation.testFiles,
    metadata: generation.metadata,
    timestamp: Date.now()
  },
  namespace: 'coordination',
  ttl: 86400 // 24 hours
});

Step 4: Execute Tests

// Execute tests with parallel execution
const execution = await mcp__agentic_qe__test_execute({
  spec: {
    testSuites: generation.testFiles.map(f => f.path),
    environments: ['development'],
    parallelExecution: true,
    retryCount: 3,
    timeoutSeconds: 300,
    reportFormat: 'json'
  },
  fleetId: fleet.fleetId
});

console.log(`Tests completed: ${execution.results.passed}/${execution.results.total}`);
console.log(`Duration: ${execution.results.duration}ms`);
console.log(`Success rate: ${(execution.results.passed / execution.results.total * 100).toFixed(2)}%`);

// Store results for coverage analysis
await mcp__agentic_qe__memory_store({
  key: 'aqe/test-results/latest',
  value: execution.results,
  namespace: 'coordination',
  ttl: 86400
});

Step 5: Analyze Coverage

// Retrieve test results from memory
const testResults = await mcp__agentic_qe__memory_retrieve({
  key: 'aqe/test-results/latest',
  namespace: 'coordination'
});

// Analyze coverage with sublinear algorithms
const coverageAnalysis = await mcp__agentic_qe__coverage_analyze_sublinear({
  sourceFiles: generation.testFiles.map(f => f.path.replace('.test.', '.')),
  coverageThreshold: 0.85,
  useJohnsonLindenstrauss: true,
  includeUncoveredLines: true
});

console.log(`Coverage: ${coverageAnalysis.coverage.overall}%`);
console.log(`Gaps detected: ${coverageAnalysis.gaps.length}`);

// Detect gaps and prioritize
const gaps = await mcp__agentic_qe__coverage_gaps_detect({
  coverageData: coverageAnalysis.coverage,
  prioritization: 'criticality'
});

console.log('Top priority gaps:');
gaps.prioritizedGaps.slice(0, 5).forEach(gap => {
  console.log(`  - ${gap.file}: ${gap.uncoveredLines.length} lines (priority: ${gap.priority})`);
});

Step 6: Quality Analysis

// Comprehensive quality analysis
const qualityAnalysis = await mcp__agentic_qe__quality_analyze({
  params: {
    scope: 'all',
    metrics: [
      'coverage',
      'test-quality',
      'code-complexity',
      'maintainability'
    ],
    thresholds: {
      coverage: 85,
      'test-quality': 80,
      'code-complexity': 10,
      maintainability: 70
    },
    generateRecommendations: true,
    historicalComparison: true
  },
  dataSource: {
    testResults: execution.report,
    codeMetrics: './reports/code-metrics.json'
  }
});

console.log(`Overall quality score: ${qualityAnalysis.analysis.overallScore}/100`);

if (qualityAnalysis.recommendations) {
  console.log('\nRecommendations:');
  qualityAnalysis.recommendations.forEach(rec => {
    console.log(`  - ${rec}`);
  });
}

Step 7: Generate Report

// Generate comprehensive HTML report
const report = await mcp__agentic_qe__test_report_comprehensive({
  results: execution.results,
  format: 'html',
  includeCharts: true,
  includeTrends: true,
  includeSummary: true,
  includeDetails: true,
  historicalData: [] // Add historical data if available
});

// Save report
const fs = require('fs');
fs.writeFileSync('test-report.html', report.report);

console.log('Report generated: test-report.html');

Advanced Patterns

Pattern 1: Streaming Execution for Large Suites

// Use streaming for real-time progress on large test suites
const stream = await mcp__agentic_qe__test_execute_stream({
  spec: {
    testSuites: largeTestSuite,
    parallelExecution: true,
    retryCount: 3
  },
  enableRealtimeUpdates: true
});

let currentProgress = 0;
for await (const event of stream) {
  if (event.type === 'progress') {
    if (event.percent > currentProgress + 5) {
      currentProgress = event.percent;
      console.log(`Progress: ${event.percent}% - ${event.message}`);
      console.log(`  Current: ${event.currentTest}`);
      console.log(`  ETA: ${Math.round(event.estimatedTimeRemaining / 1000)}s`);
    }
  } else if (event.type === 'result') {
    console.log('Completed!');
    console.log(`Final results: ${event.data.results.passed}/${event.data.results.total}`);
  }
}

Pattern 2: Agent Coordination with Memory

// Coordinator agent creates test plan
await mcp__agentic_qe__memory_store({
  key: 'aqe/coordination/test-plan',
  value: {
    phase: 'generation',
    target: { unit: 80, integration: 70, e2e: 60 },
    priority: 'high'
  },
  namespace: 'coordination'
});

// Share with all agents
await mcp__agentic_qe__memory_share({
  sourceKey: 'aqe/coordination/test-plan',
  sourceNamespace: 'coordination',
  targetAgents: [testGen.agentId, coverageAnalyzer.agentId, qualityGate.agentId],
  permissions: ['read']
});

// Post progress to blackboard
await mcp__agentic_qe__blackboard_post({
  topic: 'test-generation',
  message: 'Unit tests completed, starting integration tests',
  priority: 'medium',
  agentId: testGen.agentId,
  metadata: {
    completed: 150,
    total: 200,
    coverage: 82
  }
});

// Agents read from blackboard
const hints = await mcp__agentic_qe__blackboard_read({
  topic: 'test-generation',
  agentId: coverageAnalyzer.agentId,
  minPriority: 'medium',
  limit: 10
});

console.log(`Received ${hints.hints.length} coordination hints`);

Pattern 3: Workflow with Checkpoints

// Create workflow with checkpoints
const workflow = await mcp__agentic_qe__workflow_create({
  name: 'comprehensive-testing',
  description: 'Full testing workflow with checkpoints',
  steps: [
    {
      id: 'generate',
      name: 'Generate Tests',
      type: 'test-generation',
      dependencies: [],
      config: { coverageTarget: 85 }
    },
    {
      id: 'execute',
      name: 'Execute Tests',
      type: 'test-execution',
      dependencies: ['generate'],
      config: { parallelExecution: true }
    },
    {
      id: 'analyze',
      name: 'Analyze Quality',
      type: 'quality-analysis',
      dependencies: ['execute'],
      config: { generateRecommendations: true }
    }
  ],
  checkpoints: {
    enabled: true,
    frequency: 'after-each-step'
  }
});

// Execute workflow
const workflowExec = await mcp__agentic_qe__workflow_execute({
  workflowId: workflow.workflowId,
  oodaEnabled: true,
  autoCheckpoint: true
});

// If execution fails, resume from checkpoint
if (!workflowExec.success) {
  const checkpoint = workflowExec.lastCheckpoint;
  console.log(`Resuming from checkpoint: ${checkpoint.stepId}`);

  const resumed = await mcp__agentic_qe__workflow_resume({
    checkpointId: checkpoint.checkpointId,
    context: {
      skipFailedSteps: false
    }
  });
}

Pattern 4: Consensus-Based Quality Gate

// Create proposal for deployment
const proposal = await mcp__agentic_qe__consensus_propose({
  proposalId: 'deploy-v2.1.0',
  topic: 'deployment-approval',
  proposal: {
    version: 'v2.1.0',
    environment: 'production',
    metrics: qualityAnalysis.metrics
  },
  votingAgents: [testGen.agentId, coverageAnalyzer.agentId, qualityGate.agentId],
  quorum: 0.67, // 67% approval required
  timeout: 300
});

// Each agent votes based on their analysis
const votes = await Promise.all([
  mcp__agentic_qe__consensus_vote({
    proposalId: proposal.proposalId,
    agentId: testGen.agentId,
    vote: 'approve',
    rationale: 'All tests generated and passing'
  }),
  mcp__agentic_qe__consensus_vote({
    proposalId: proposal.proposalId,
    agentId: coverageAnalyzer.agentId,
    vote: 'approve',
    rationale: 'Coverage exceeds threshold'
  }),
  mcp__agentic_qe__consensus_vote({
    proposalId: proposal.proposalId,
    agentId: qualityGate.agentId,
    vote: qualityAnalysis.analysis.overallScore >= 80 ? 'approve' : 'reject',
    rationale: `Quality score: ${qualityAnalysis.analysis.overallScore}`
  })
]);

const finalVote = votes[votes.length - 1];
if (finalVote.consensusReached && finalVote.approved) {
  console.log('✅ Deployment approved by consensus');
} else {
  console.log('❌ Deployment rejected');
}

CI/CD Integration

GitHub Actions Example

# .github/workflows/test.yml
name: AQE Testing Workflow

on:
  pull_request:
    branches: [main, develop]
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: Install dependencies
        run: npm ci

      - name: Start MCP Server
        run: npm run mcp:start &

      - name: Run AQE Workflow
        run: node scripts/aqe-workflow.js
        env:
          FLEET_TOPOLOGY: hierarchical
          MAX_AGENTS: 10
          COVERAGE_TARGET: 85

      - name: Upload Reports
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: test-reports
          path: |
            test-report.html
            coverage/
// scripts/aqe-workflow.js
async function runCIWorkflow() {
  // Initialize fleet
  const fleet = await mcp__agentic_qe__fleet_init({
    config: {
      topology: process.env.FLEET_TOPOLOGY || 'hierarchical',
      maxAgents: parseInt(process.env.MAX_AGENTS) || 10,
      testingFocus: ['unit', 'integration'],
      frameworks: ['jest']
    }
  });

  // Orchestrate full testing
  const orchestration = await mcp__agentic_qe__task_orchestrate({
    task: {
      type: 'comprehensive-testing',
      priority: 'high',
      strategy: 'adaptive'
    },
    context: {
      project: process.env.GITHUB_REPOSITORY,
      branch: process.env.GITHUB_REF,
      environment: 'ci'
    },
    fleetId: fleet.fleetId
  });

  // Wait for completion
  let status;
  do {
    await new Promise(resolve => setTimeout(resolve, 5000));
    status = await mcp__agentic_qe__task_status({
      taskId: orchestration.orchestrationId,
      includeDetails: true
    });
    console.log(`Status: ${status.status} (${status.progress}%)`);
  } while (status.status === 'running');

  // Check quality gate
  if (status.status === 'completed') {
    console.log('✅ All tests passed');
    process.exit(0);
  } else {
    console.log('❌ Tests failed');
    process.exit(1);
  }
}

runCIWorkflow().catch(err => {
  console.error('Workflow failed:', err);
  process.exit(1);
});

Error Handling

Retry Pattern

async function executeWithRetry(operation, maxAttempts = 3) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt === maxAttempts) throw error;

      if (error.retryable) {
        const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
        console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
        if (error.suggestion) {
          console.log(`Suggestion: ${error.suggestion}`);
        }
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        throw error; // Don't retry non-retryable errors
      }
    }
  }
}

// Usage
const result = await executeWithRetry(() =>
  mcp__agentic_qe__test_execute({
    spec: { testSuites: ['tests/'], parallelExecution: true }
  })
);

Graceful Degradation

async function executewithFallback() {
  try {
    // Try parallel execution first
    return await mcp__agentic_qe__test_execute({
      spec: {
        testSuites: ['tests/'],
        parallelExecution: true,
        retryCount: 3
      }
    });
  } catch (error) {
    if (error.code === 'INSUFFICIENT_AGENTS') {
      console.log('Falling back to sequential execution...');
      // Fall back to sequential
      return await mcp__agentic_qe__test_execute({
        spec: {
          testSuites: ['tests/'],
          parallelExecution: false,
          retryCount: 1
        }
      });
    }
    throw error;
  }
}

Performance Optimization

Optimize Test Suite

// 1. Analyze current suite
const analysis = await mcp__agentic_qe__coverage_analyze_sublinear({
  sourceFiles: glob.sync('tests/**/*.test.ts'),
  coverageThreshold: 0.85,
  useJohnsonLindenstrauss: true
});

// 2. Optimize with sublinear algorithms
const optimized = await mcp__agentic_qe__test_optimize_sublinear({
  testSuite: {
    tests: analysis.tests
  },
  algorithm: 'johnson-lindenstrauss',
  targetReduction: 0.4, // Reduce to 40%
  maintainCoverage: 0.90, // Keep 90% coverage
  preserveCritical: true
});

console.log(`Reduced from ${optimized.metrics.originalSize} to ${optimized.metrics.optimizedSize} tests`);
console.log(`Time savings: ${optimized.metrics.estimatedTimeReduction}%`);

// 3. Execute optimized suite
const result = await mcp__agentic_qe__test_execute({
  spec: {
    testSuites: optimized.optimizedSuite.tests.map(t => t.path),
    parallelExecution: true
  }
});

Parallel Agent Coordination

// Spawn agents in parallel
const agents = await Promise.all([
  mcp__agentic_qe__agent_spawn({
    spec: { type: 'test-generator', capabilities: ['unit'] }
  }),
  mcp__agentic_qe__agent_spawn({
    spec: { type: 'coverage-analyzer', capabilities: ['analysis'] }
  }),
  mcp__agentic_qe__agent_spawn({
    spec: { type: 'quality-gate', capabilities: ['validation'] }
  })
]);

// Execute tasks in parallel
const results = await Promise.all([
  mcp__agentic_qe__test_generate({ agentId: agents[0].agentId, spec: { ... } }),
  mcp__agentic_qe__coverage_analyze_sublinear({ ... }),
  mcp__agentic_qe__quality_analyze({ ... })
]);

Complete Example

See examples/mcp/complete-workflow.js for a runnable example.


Next Steps: