agentic-qe 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/dist/agents/CoverageAnalyzerAgent.d.ts.map +1 -1
  4. package/dist/agents/CoverageAnalyzerAgent.js +53 -27
  5. package/dist/agents/CoverageAnalyzerAgent.js.map +1 -1
  6. package/dist/agents/FlakyTestHunterAgent.d.ts +5 -0
  7. package/dist/agents/FlakyTestHunterAgent.d.ts.map +1 -1
  8. package/dist/agents/FlakyTestHunterAgent.js +20 -5
  9. package/dist/agents/FlakyTestHunterAgent.js.map +1 -1
  10. package/dist/agents/QualityGateAgent.js +44 -6
  11. package/dist/agents/QualityGateAgent.js.map +1 -1
  12. package/dist/cli/index.js +0 -0
  13. package/dist/cli/init/database-init.js +5 -0
  14. package/dist/cli/init/database-init.js.map +1 -1
  15. package/dist/learning/PerformanceTracker.d.ts +9 -0
  16. package/dist/learning/PerformanceTracker.d.ts.map +1 -1
  17. package/dist/learning/PerformanceTracker.js +26 -2
  18. package/dist/learning/PerformanceTracker.js.map +1 -1
  19. package/dist/mcp/server-instructions.d.ts +1 -1
  20. package/dist/mcp/server-instructions.js +1 -1
  21. package/package.json +3 -1
  22. package/scripts/README.md +352 -0
  23. package/scripts/hooks/capture-task-learning.js +191 -0
  24. package/scripts/hooks/emit-task-complete.sh +35 -0
  25. package/scripts/hooks/emit-task-spawn.sh +27 -0
  26. package/.claude/agents/failing-agent.json +0 -9
  27. package/.claude/agents/test-agent.json +0 -9
  28. package/dist/App.d.ts +0 -5
  29. package/dist/App.d.ts.map +0 -1
  30. package/dist/App.js +0 -15
  31. package/dist/App.js.map +0 -1
  32. package/dist/cli/init/utils.d.ts +0 -183
  33. package/dist/cli/init/utils.d.ts.map +0 -1
  34. package/dist/cli/init/utils.js +0 -354
  35. package/dist/cli/init/utils.js.map +0 -1
  36. package/dist/components/Dashboard/Dashboard.d.ts +0 -4
  37. package/dist/components/Dashboard/Dashboard.d.ts.map +0 -1
  38. package/dist/components/Dashboard/Dashboard.js +0 -148
  39. package/dist/components/Dashboard/Dashboard.js.map +0 -1
  40. package/dist/components/Dashboard/DashboardHeader.d.ts +0 -4
  41. package/dist/components/Dashboard/DashboardHeader.d.ts.map +0 -1
  42. package/dist/components/Dashboard/DashboardHeader.js +0 -138
  43. package/dist/components/Dashboard/DashboardHeader.js.map +0 -1
  44. package/dist/contexts/DashboardContext.d.ts +0 -41
  45. package/dist/contexts/DashboardContext.d.ts.map +0 -1
  46. package/dist/contexts/DashboardContext.js +0 -187
  47. package/dist/contexts/DashboardContext.js.map +0 -1
  48. package/dist/core/transport/QUICTransport.d.ts +0 -320
  49. package/dist/core/transport/QUICTransport.d.ts.map +0 -1
  50. package/dist/core/transport/QUICTransport.js +0 -711
  51. package/dist/core/transport/QUICTransport.js.map +0 -1
  52. package/dist/learning/LearningPersistenceAdapter.d.ts +0 -84
  53. package/dist/learning/LearningPersistenceAdapter.d.ts.map +0 -1
  54. package/dist/learning/LearningPersistenceAdapter.js +0 -202
  55. package/dist/learning/LearningPersistenceAdapter.js.map +0 -1
  56. package/dist/learning/algorithms/QLearning.d.ts +0 -68
  57. package/dist/learning/algorithms/QLearning.d.ts.map +0 -1
  58. package/dist/learning/algorithms/QLearning.js +0 -116
  59. package/dist/learning/algorithms/QLearning.js.map +0 -1
  60. package/dist/mcp/handlers/advanced/requirements-generate-bdd.d.ts +0 -7
  61. package/dist/mcp/handlers/advanced/requirements-generate-bdd.d.ts.map +0 -1
  62. package/dist/mcp/handlers/advanced/requirements-generate-bdd.js +0 -267
  63. package/dist/mcp/handlers/advanced/requirements-generate-bdd.js.map +0 -1
  64. package/dist/mcp/handlers/advanced/requirements-validate.d.ts +0 -7
  65. package/dist/mcp/handlers/advanced/requirements-validate.d.ts.map +0 -1
  66. package/dist/mcp/handlers/advanced/requirements-validate.js +0 -175
  67. package/dist/mcp/handlers/advanced/requirements-validate.js.map +0 -1
  68. package/dist/mcp/handlers/analysis/performance-benchmark-run-handler.d.ts +0 -15
  69. package/dist/mcp/handlers/analysis/performance-benchmark-run-handler.d.ts.map +0 -1
  70. package/dist/mcp/handlers/analysis/performance-benchmark-run-handler.js +0 -43
  71. package/dist/mcp/handlers/analysis/performance-benchmark-run-handler.js.map +0 -1
  72. package/dist/mcp/handlers/analysis/performanceBenchmarkRun.d.ts +0 -58
  73. package/dist/mcp/handlers/analysis/performanceBenchmarkRun.d.ts.map +0 -1
  74. package/dist/mcp/handlers/analysis/performanceBenchmarkRun.js +0 -188
  75. package/dist/mcp/handlers/analysis/performanceBenchmarkRun.js.map +0 -1
  76. package/dist/mcp/handlers/optimize-tests.d.ts +0 -219
  77. package/dist/mcp/handlers/optimize-tests.d.ts.map +0 -1
  78. package/dist/mcp/handlers/optimize-tests.js +0 -533
  79. package/dist/mcp/handlers/optimize-tests.js.map +0 -1
  80. package/dist/mcp/handlers/predict-defects.d.ts +0 -194
  81. package/dist/mcp/handlers/predict-defects.d.ts.map +0 -1
  82. package/dist/mcp/handlers/predict-defects.js +0 -722
  83. package/dist/mcp/handlers/predict-defects.js.map +0 -1
  84. package/dist/mcp/handlers/prediction/regression-risk-analyze.d.ts +0 -199
  85. package/dist/mcp/handlers/prediction/regression-risk-analyze.d.ts.map +0 -1
  86. package/dist/mcp/handlers/prediction/regression-risk-analyze.js +0 -471
  87. package/dist/mcp/handlers/prediction/regression-risk-analyze.js.map +0 -1
  88. package/dist/mcp/handlers/quality/quality-decision-make.d.ts +0 -104
  89. package/dist/mcp/handlers/quality/quality-decision-make.d.ts.map +0 -1
  90. package/dist/mcp/handlers/quality/quality-decision-make.js +0 -408
  91. package/dist/mcp/handlers/quality/quality-decision-make.js.map +0 -1
  92. package/dist/mcp/handlers/quality/quality-gate-execute.d.ts +0 -160
  93. package/dist/mcp/handlers/quality/quality-gate-execute.d.ts.map +0 -1
  94. package/dist/mcp/handlers/quality/quality-gate-execute.js +0 -412
  95. package/dist/mcp/handlers/quality/quality-gate-execute.js.map +0 -1
  96. package/dist/mcp/handlers/quality/quality-policy-check.d.ts +0 -163
  97. package/dist/mcp/handlers/quality/quality-policy-check.d.ts.map +0 -1
  98. package/dist/mcp/handlers/quality/quality-policy-check.js +0 -455
  99. package/dist/mcp/handlers/quality/quality-policy-check.js.map +0 -1
  100. package/dist/mcp/handlers/quality/quality-risk-assess.d.ts +0 -123
  101. package/dist/mcp/handlers/quality/quality-risk-assess.d.ts.map +0 -1
  102. package/dist/mcp/handlers/quality/quality-risk-assess.js +0 -522
  103. package/dist/mcp/handlers/quality/quality-risk-assess.js.map +0 -1
  104. package/dist/mcp/handlers/quality/quality-validate-metrics.d.ts +0 -117
  105. package/dist/mcp/handlers/quality/quality-validate-metrics.d.ts.map +0 -1
  106. package/dist/mcp/handlers/quality/quality-validate-metrics.js +0 -288
  107. package/dist/mcp/handlers/quality/quality-validate-metrics.js.map +0 -1
  108. package/dist/mcp/handlers/quality-analyze.d.ts +0 -279
  109. package/dist/mcp/handlers/quality-analyze.d.ts.map +0 -1
  110. package/dist/mcp/handlers/quality-analyze.js +0 -720
  111. package/dist/mcp/handlers/quality-analyze.js.map +0 -1
  112. package/dist/mcp/handlers/security/check-authz.d.ts +0 -152
  113. package/dist/mcp/handlers/security/check-authz.d.ts.map +0 -1
  114. package/dist/mcp/handlers/security/check-authz.js +0 -434
  115. package/dist/mcp/handlers/security/check-authz.js.map +0 -1
  116. package/dist/mcp/handlers/security/scan-dependencies.d.ts +0 -148
  117. package/dist/mcp/handlers/security/scan-dependencies.d.ts.map +0 -1
  118. package/dist/mcp/handlers/security/scan-dependencies.js +0 -354
  119. package/dist/mcp/handlers/security/scan-dependencies.js.map +0 -1
  120. package/dist/mcp/handlers/security/validate-auth.d.ts +0 -128
  121. package/dist/mcp/handlers/security/validate-auth.d.ts.map +0 -1
  122. package/dist/mcp/handlers/security/validate-auth.js +0 -294
  123. package/dist/mcp/handlers/security/validate-auth.js.map +0 -1
  124. package/dist/mcp/handlers/test-generate.d.ts +0 -107
  125. package/dist/mcp/handlers/test-generate.d.ts.map +0 -1
  126. package/dist/mcp/handlers/test-generate.js +0 -454
  127. package/dist/mcp/handlers/test-generate.js.map +0 -1
@@ -1,722 +0,0 @@
1
- "use strict";
2
- /**
3
- * Defect Prediction Handler
4
- *
5
- * Handles AI-driven defect prediction using machine learning models.
6
- * Analyzes code changes and historical patterns to predict potential defects.
7
- *
8
- * @version 1.0.0
9
- * @author Agentic QE Team
10
- */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.PredictDefectsHandler = void 0;
13
- const base_handler_js_1 = require("./base-handler.js");
14
- const SecureRandom_js_1 = require("../../utils/SecureRandom.js");
15
- class PredictDefectsHandler extends base_handler_js_1.BaseHandler {
16
- constructor(registry, hookExecutor) {
17
- super();
18
- this.predictionHistory = new Map();
19
- this.models = new Map();
20
- this.featureExtractors = new Map();
21
- this.registry = registry;
22
- this.hookExecutor = hookExecutor;
23
- this.initializeModels();
24
- this.initializeFeatureExtractors();
25
- }
26
- async handle(args) {
27
- const requestId = this.generateRequestId();
28
- this.log('info', 'Starting defect prediction', { requestId, scope: args.scope });
29
- try {
30
- // Execute pre-task hook
31
- await this.hookExecutor.executePreTask({
32
- description: `Predict defects using ${args.scope.modelType} model for ${args.scope.analysisType} analysis`,
33
- agentType: 'defect-predictor'
34
- });
35
- // Validate required parameters
36
- this.validateRequired(args, ['scope']);
37
- this.validateDefectPredictionScope(args.scope);
38
- // Spawn defect prediction agent via registry
39
- const { id: agentId } = await this.registry.spawnAgent('defect-predictor', {} // Agent config - using defaults
40
- );
41
- const { result: prediction, executionTime } = await this.measureExecutionTime(() => this.predictDefects(args.scope, args.codeChanges));
42
- // Execute post-task hook with results
43
- await this.hookExecutor.executePostTask({
44
- taskId: agentId,
45
- results: {
46
- predictionId: prediction.id,
47
- predictionsCount: prediction.predictions.length,
48
- overallRisk: prediction.riskAssessment.overallRisk,
49
- modelMetrics: prediction.modelMetrics
50
- }
51
- });
52
- this.log('info', `Defect prediction completed in ${executionTime.toFixed(2)}ms`, {
53
- predictionId: prediction.id,
54
- predictionsCount: prediction.predictions.length,
55
- overallRisk: prediction.riskAssessment.overallRisk
56
- });
57
- return this.createSuccessResponse(prediction, requestId);
58
- }
59
- catch (error) {
60
- this.log('error', 'Defect prediction failed', { error: error instanceof Error ? error.message : String(error) });
61
- return this.createErrorResponse(error instanceof Error ? error.message : 'Defect prediction failed', requestId);
62
- }
63
- }
64
- initializeModels() {
65
- // Initialize different model types
66
- this.models.set('neural', {
67
- type: 'deep-neural-network',
68
- architecture: 'lstm-attention',
69
- features: ['code-metrics', 'change-history', 'author-patterns', 'complexity'],
70
- accuracy: 0.87,
71
- trainingData: 10000
72
- });
73
- this.models.set('statistical', {
74
- type: 'ensemble-classifier',
75
- architecture: 'random-forest-gradient-boosting',
76
- features: ['statistical-metrics', 'historical-patterns', 'code-churn'],
77
- accuracy: 0.82,
78
- trainingData: 15000
79
- });
80
- this.models.set('hybrid', {
81
- type: 'neural-statistical-ensemble',
82
- architecture: 'weighted-ensemble',
83
- features: ['neural-features', 'statistical-features', 'domain-knowledge'],
84
- accuracy: 0.91,
85
- trainingData: 20000
86
- });
87
- }
88
- initializeFeatureExtractors() {
89
- // Code complexity features
90
- this.featureExtractors.set('complexity', {
91
- features: ['cyclomatic', 'cognitive', 'nesting-depth', 'function-length'],
92
- weight: 0.25
93
- });
94
- // Change history features
95
- this.featureExtractors.set('change-history', {
96
- features: ['change-frequency', 'lines-changed', 'files-changed', 'commit-size'],
97
- weight: 0.20
98
- });
99
- // Author patterns features
100
- this.featureExtractors.set('author-patterns', {
101
- features: ['author-experience', 'defect-rate', 'code-quality', 'review-feedback'],
102
- weight: 0.15
103
- });
104
- // Code quality features
105
- this.featureExtractors.set('code-quality', {
106
- features: ['duplication', 'coverage', 'technical-debt', 'documentation'],
107
- weight: 0.20
108
- });
109
- // Structural features
110
- this.featureExtractors.set('structural', {
111
- features: ['coupling', 'cohesion', 'inheritance-depth', 'dependencies'],
112
- weight: 0.20
113
- });
114
- }
115
- validateDefectPredictionScope(scope) {
116
- const validAnalysisTypes = ['file', 'function', 'line', 'module'];
117
- if (!validAnalysisTypes.includes(scope.analysisType)) {
118
- throw new Error(`Invalid analysis type: ${scope.analysisType}. Must be one of: ${validAnalysisTypes.join(', ')}`);
119
- }
120
- const validModelTypes = ['neural', 'statistical', 'hybrid'];
121
- if (!validModelTypes.includes(scope.modelType)) {
122
- throw new Error(`Invalid model type: ${scope.modelType}. Must be one of: ${validModelTypes.join(', ')}`);
123
- }
124
- if (scope.confidenceThreshold < 0 || scope.confidenceThreshold > 1) {
125
- throw new Error('Confidence threshold must be between 0 and 1');
126
- }
127
- if (scope.historicalDataDays < 7 || scope.historicalDataDays > 365) {
128
- throw new Error('Historical data days must be between 7 and 365');
129
- }
130
- }
131
- async predictDefects(scope, codeChanges) {
132
- const predictionId = `defect-prediction-${Date.now()}-${SecureRandom_js_1.SecureRandom.generateId(6)}`;
133
- this.log('info', 'Performing defect prediction', {
134
- predictionId,
135
- analysisType: scope.analysisType,
136
- modelType: scope.modelType
137
- });
138
- // Get model for prediction
139
- const model = this.models.get(scope.modelType);
140
- // Extract features from code changes
141
- const features = await this.extractFeatures(scope, codeChanges);
142
- // Make predictions
143
- const predictions = await this.makePredictions(scope, features, model);
144
- // Calculate model metrics
145
- const modelMetrics = this.calculateModelMetrics(model);
146
- // Generate recommendations
147
- const recommendations = await this.generatePreventionRecommendations(predictions);
148
- // Assess overall risk
149
- const riskAssessment = this.assessOverallRisk(predictions);
150
- // Calculate confidence
151
- const confidence = this.calculateOverallConfidence(predictions, model, features);
152
- const defectPrediction = {
153
- id: predictionId,
154
- analysisType: scope.analysisType,
155
- modelType: scope.modelType,
156
- generatedAt: new Date().toISOString(),
157
- predictions,
158
- modelMetrics,
159
- recommendations,
160
- riskAssessment,
161
- confidence
162
- };
163
- // Store prediction
164
- this.predictionHistory.set(predictionId, defectPrediction);
165
- return defectPrediction;
166
- }
167
- async extractFeatures(scope, codeChanges) {
168
- this.log('info', 'Extracting features for prediction');
169
- const allFeatures = new Map();
170
- // Extract features based on scope and available extractors
171
- for (const [extractorName, extractor] of this.featureExtractors.entries()) {
172
- if (!scope.features || scope.features.includes(extractorName)) {
173
- const features = await this.extractFeatureGroup(extractorName, extractor, codeChanges);
174
- allFeatures.set(extractorName, features);
175
- }
176
- }
177
- return allFeatures;
178
- }
179
- async extractFeatureGroup(extractorName, extractor, codeChanges) {
180
- // Simulate feature extraction based on type
181
- await new Promise(resolve => setTimeout(resolve, 50 + SecureRandom_js_1.SecureRandom.randomFloat() * 100));
182
- switch (extractorName) {
183
- case 'complexity':
184
- return this.extractComplexityFeatures(codeChanges);
185
- case 'change-history':
186
- return this.extractChangeHistoryFeatures(codeChanges);
187
- case 'author-patterns':
188
- return this.extractAuthorPatternFeatures(codeChanges);
189
- case 'code-quality':
190
- return this.extractCodeQualityFeatures(codeChanges);
191
- case 'structural':
192
- return this.extractStructuralFeatures(codeChanges);
193
- default:
194
- return this.generateMockFeatures(extractorName);
195
- }
196
- }
197
- extractComplexityFeatures(codeChanges) {
198
- return {
199
- cyclomaticComplexity: SecureRandom_js_1.SecureRandom.randomFloat() * 20 + 5, // 5-25
200
- cognitiveComplexity: SecureRandom_js_1.SecureRandom.randomFloat() * 30 + 10, // 10-40
201
- nestingDepth: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 8 + 1), // 1-8
202
- functionLength: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 200 + 10), // 10-210 lines
203
- parameterCount: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 10 + 1), // 1-10
204
- returnPoints: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 5 + 1) // 1-5
205
- };
206
- }
207
- extractChangeHistoryFeatures(codeChanges) {
208
- return {
209
- changeFrequency: SecureRandom_js_1.SecureRandom.randomFloat() * 10 + 1, // 1-11 changes per month
210
- linesAdded: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 500 + 10), // 10-510
211
- linesDeleted: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 200 + 5), // 5-205
212
- filesChanged: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 20 + 1), // 1-20
213
- commitSize: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 1000 + 50), // 50-1050 lines
214
- timesSinceLastChange: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 30 + 1) // 1-30 days
215
- };
216
- }
217
- extractAuthorPatternFeatures(codeChanges) {
218
- return {
219
- authorExperience: SecureRandom_js_1.SecureRandom.randomFloat() * 5 + 0.5, // 0.5-5.5 years
220
- defectRate: SecureRandom_js_1.SecureRandom.randomFloat() * 0.1 + 0.01, // 1-11% defect rate
221
- codeQualityScore: SecureRandom_js_1.SecureRandom.randomFloat() * 30 + 70, // 70-100
222
- reviewFeedbackScore: SecureRandom_js_1.SecureRandom.randomFloat() * 20 + 75, // 75-95
223
- productivityScore: SecureRandom_js_1.SecureRandom.randomFloat() * 25 + 70, // 70-95
224
- domainKnowledge: SecureRandom_js_1.SecureRandom.randomFloat() * 40 + 60 // 60-100
225
- };
226
- }
227
- extractCodeQualityFeatures(codeChanges) {
228
- return {
229
- duplicationPercentage: SecureRandom_js_1.SecureRandom.randomFloat() * 15 + 2, // 2-17%
230
- testCoverage: SecureRandom_js_1.SecureRandom.randomFloat() * 30 + 65, // 65-95%
231
- technicalDebtRatio: SecureRandom_js_1.SecureRandom.randomFloat() * 0.4 + 0.1, // 10-50%
232
- documentationCoverage: SecureRandom_js_1.SecureRandom.randomFloat() * 40 + 50, // 50-90%
233
- codeSmells: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 20 + 2), // 2-22
234
- securityIssues: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 5) // 0-4
235
- };
236
- }
237
- extractStructuralFeatures(codeChanges) {
238
- return {
239
- couplingBetweenObjects: SecureRandom_js_1.SecureRandom.randomFloat() * 20 + 5, // 5-25
240
- lackOfCohesion: SecureRandom_js_1.SecureRandom.randomFloat() * 0.8 + 0.1, // 0.1-0.9
241
- inheritanceDepth: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 8 + 1), // 1-8
242
- numberOfDependencies: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 50 + 5), // 5-55
243
- fanIn: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 15 + 1), // 1-15
244
- fanOut: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 10 + 1) // 1-10
245
- };
246
- }
247
- generateMockFeatures(extractorName) {
248
- return {
249
- feature1: SecureRandom_js_1.SecureRandom.randomFloat(),
250
- feature2: SecureRandom_js_1.SecureRandom.randomFloat() * 100,
251
- feature3: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 10)
252
- };
253
- }
254
- async makePredictions(scope, features, model) {
255
- this.log('info', 'Making defect predictions', { modelType: scope.modelType });
256
- const predictions = [];
257
- // Generate predictions based on analysis type
258
- const targetCount = this.getTargetCount(scope.analysisType);
259
- for (let i = 0; i < targetCount; i++) {
260
- const prediction = await this.makeSinglePrediction(scope, features, model, i);
261
- // Filter by confidence threshold
262
- if (prediction.confidence >= scope.confidenceThreshold) {
263
- predictions.push(prediction);
264
- }
265
- }
266
- return predictions.sort((a, b) => b.riskScore - a.riskScore);
267
- }
268
- async makeSinglePrediction(scope, features, model, index) {
269
- // Simulate ML model inference
270
- const riskScore = this.calculateRiskScore(features, model);
271
- const confidence = this.calculatePredictionConfidence(features, model, riskScore);
272
- const target = this.generateTarget(scope.analysisType, index);
273
- const defectTypes = this.predictDefectTypes(features, model);
274
- const analyzedFeatures = this.analyzeFeatureImportance(features);
275
- const historicalContext = this.getHistoricalContext(target);
276
- return {
277
- target,
278
- targetType: scope.analysisType,
279
- riskScore: Math.round(riskScore * 1000) / 1000,
280
- confidence: Math.round(confidence * 1000) / 1000,
281
- defectTypes,
282
- features: analyzedFeatures,
283
- historicalContext,
284
- severity: this.calculateSeverity(riskScore),
285
- timeframe: this.estimateTimeframe(riskScore, features)
286
- };
287
- }
288
- calculateRiskScore(features, model) {
289
- // Simulate ML model scoring
290
- let score = 0;
291
- let weightSum = 0;
292
- for (const [featureGroup, featureValues] of features.entries()) {
293
- const extractor = this.featureExtractors.get(featureGroup);
294
- if (extractor) {
295
- const groupScore = this.calculateFeatureGroupScore(featureValues);
296
- score += groupScore * extractor.weight;
297
- weightSum += extractor.weight;
298
- }
299
- }
300
- // Normalize and add model-specific adjustments
301
- const normalizedScore = weightSum > 0 ? score / weightSum : 0;
302
- const modelAdjustment = (model.accuracy - 0.8) * 0.1; // Adjust based on model accuracy
303
- return Math.max(0, Math.min(1, normalizedScore + modelAdjustment));
304
- }
305
- calculateFeatureGroupScore(featureValues) {
306
- // Simple scoring based on feature values
307
- // In a real implementation, this would use trained weights
308
- let score = 0;
309
- let count = 0;
310
- for (const [key, value] of Object.entries(featureValues)) {
311
- if (typeof value === 'number') {
312
- // Normalize different types of features
313
- let normalizedValue = 0;
314
- if (key.includes('complexity') || key.includes('depth') || key.includes('coupling')) {
315
- normalizedValue = Math.min(1, value / 20); // Higher is worse
316
- }
317
- else if (key.includes('coverage') || key.includes('quality')) {
318
- normalizedValue = 1 - Math.min(1, value / 100); // Lower is worse
319
- }
320
- else if (key.includes('frequency') || key.includes('count')) {
321
- normalizedValue = Math.min(1, value / 10); // Higher is worse
322
- }
323
- else {
324
- normalizedValue = Math.min(1, value / 100); // Generic normalization
325
- }
326
- score += normalizedValue;
327
- count++;
328
- }
329
- }
330
- return count > 0 ? score / count : 0;
331
- }
332
- calculatePredictionConfidence(features, model, riskScore) {
333
- // Base confidence on model accuracy
334
- let confidence = model.accuracy;
335
- // Adjust based on feature completeness
336
- const featureCompleteness = features.size / this.featureExtractors.size;
337
- confidence *= featureCompleteness;
338
- // Adjust based on risk score (extreme values may be less reliable)
339
- const extremenessAdjustment = 1 - Math.abs(riskScore - 0.5) * 0.2;
340
- confidence *= extremenessAdjustment;
341
- // Add some variance
342
- confidence += (SecureRandom_js_1.SecureRandom.randomFloat() - 0.5) * 0.1;
343
- return Math.max(0.1, Math.min(1, confidence));
344
- }
345
- predictDefectTypes(features, model) {
346
- const defectTypes = [];
347
- // Common defect types based on features
348
- const typeDefinitions = [
349
- {
350
- type: 'logic-error',
351
- indicators: ['complexity', 'change-history'],
352
- baseProbability: 0.3
353
- },
354
- {
355
- type: 'null-pointer',
356
- indicators: ['code-quality', 'author-patterns'],
357
- baseProbability: 0.2
358
- },
359
- {
360
- type: 'boundary-error',
361
- indicators: ['complexity', 'structural'],
362
- baseProbability: 0.15
363
- },
364
- {
365
- type: 'concurrency-issue',
366
- indicators: ['structural', 'complexity'],
367
- baseProbability: 0.1
368
- },
369
- {
370
- type: 'integration-failure',
371
- indicators: ['structural', 'change-history'],
372
- baseProbability: 0.15
373
- },
374
- {
375
- type: 'performance-degradation',
376
- indicators: ['complexity', 'structural'],
377
- baseProbability: 0.1
378
- }
379
- ];
380
- for (const typeDef of typeDefinitions) {
381
- let probability = typeDef.baseProbability;
382
- // Adjust probability based on relevant features
383
- for (const indicator of typeDef.indicators) {
384
- if (features.has(indicator)) {
385
- const featureScore = this.calculateFeatureGroupScore(features.get(indicator));
386
- probability += featureScore * 0.2;
387
- }
388
- }
389
- if (probability > 0.05) { // Only include if probability > 5%
390
- defectTypes.push({
391
- type: typeDef.type,
392
- probability: Math.min(1, probability),
393
- description: this.getDefectTypeDescription(typeDef.type),
394
- examples: this.getDefectTypeExamples(typeDef.type),
395
- prevention: this.getDefectTypePrevention(typeDef.type)
396
- });
397
- }
398
- }
399
- return defectTypes.sort((a, b) => b.probability - a.probability);
400
- }
401
- analyzeFeatureImportance(features) {
402
- const analyzedFeatures = [];
403
- for (const [featureGroup, featureValues] of features.entries()) {
404
- const extractor = this.featureExtractors.get(featureGroup);
405
- if (extractor) {
406
- for (const [featureName, value] of Object.entries(featureValues)) {
407
- if (typeof value === 'number') {
408
- analyzedFeatures.push({
409
- name: `${featureGroup}.${featureName}`,
410
- value,
411
- importance: extractor.weight * SecureRandom_js_1.SecureRandom.randomFloat(), // Simulate importance
412
- interpretation: this.interpretFeature(featureName, value)
413
- });
414
- }
415
- }
416
- }
417
- }
418
- return analyzedFeatures.sort((a, b) => b.importance - a.importance).slice(0, 10); // Top 10
419
- }
420
- getHistoricalContext(target) {
421
- return {
422
- similarDefects: Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 10 + 1), // 1-10
423
- lastDefectDate: new Date(Date.now() - SecureRandom_js_1.SecureRandom.randomFloat() * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
424
- defectPattern: ['regression', 'new-feature', 'refactoring', 'hotfix'][Math.floor(SecureRandom_js_1.SecureRandom.randomFloat() * 4)],
425
- changeFrequency: SecureRandom_js_1.SecureRandom.randomFloat() * 5 + 1, // 1-6 changes per month
426
- authorExperience: SecureRandom_js_1.SecureRandom.randomFloat() * 5 + 0.5 // 0.5-5.5 years
427
- };
428
- }
429
- calculateSeverity(riskScore) {
430
- if (riskScore >= 0.8)
431
- return 'critical';
432
- if (riskScore >= 0.6)
433
- return 'high';
434
- if (riskScore >= 0.3)
435
- return 'medium';
436
- return 'low';
437
- }
438
- estimateTimeframe(riskScore, features) {
439
- // Estimate when defect might manifest
440
- const baseTimeframe = Math.floor((1 - riskScore) * 90 + 7); // 7-97 days
441
- return `${baseTimeframe} days`;
442
- }
443
- calculateModelMetrics(model) {
444
- return {
445
- accuracy: model.accuracy,
446
- precision: model.accuracy * 0.95, // Simulate precision
447
- recall: model.accuracy * 0.90, // Simulate recall
448
- f1Score: model.accuracy * 0.92, // Simulate F1
449
- auc: model.accuracy * 0.98, // Simulate AUC
450
- trainingData: {
451
- samples: model.trainingData,
452
- features: 45,
453
- timespan: '12 months'
454
- },
455
- lastTraining: new Date(Date.now() - SecureRandom_js_1.SecureRandom.randomFloat() * 30 * 24 * 60 * 60 * 1000).toISOString(),
456
- modelVersion: '2.1.0'
457
- };
458
- }
459
- async generatePreventionRecommendations(predictions) {
460
- const recommendations = [];
461
- // Generate recommendations based on high-risk predictions
462
- const highRiskPredictions = predictions.filter(p => p.riskScore > 0.6);
463
- for (const prediction of highRiskPredictions) {
464
- for (const defectType of prediction.defectTypes) {
465
- if (defectType.probability > 0.3) {
466
- const recommendation = this.createPreventionRecommendation(prediction, defectType);
467
- recommendations.push(recommendation);
468
- }
469
- }
470
- }
471
- // Add general preventive recommendations
472
- recommendations.push(...this.generateGeneralPreventionRecommendations(predictions));
473
- return recommendations.slice(0, 10); // Limit to top 10
474
- }
475
- createPreventionRecommendation(prediction, defectType) {
476
- return {
477
- id: `prevention-${Date.now()}-${SecureRandom_js_1.SecureRandom.generateId(2)}`,
478
- category: defectType.type,
479
- priority: prediction.severity === 'critical' ? 'critical' : prediction.severity === 'high' ? 'high' : 'medium',
480
- title: `Prevent ${defectType.type} in ${prediction.target}`,
481
- description: `Implement preventive measures to reduce ${defectType.type} risk from ${(defectType.probability * 100).toFixed(1)}%`,
482
- preventiveActions: defectType.prevention.map(prev => ({
483
- type: this.categorizePreventionAction(prev),
484
- description: prev,
485
- automated: this.isActionAutomated(prev),
486
- tools: this.getRecommendedTools(prev)
487
- })),
488
- estimatedEffectiveness: SecureRandom_js_1.SecureRandom.randomFloat() * 0.4 + 0.6, // 60-100%
489
- implementationCost: this.estimateImplementationCost(defectType.type),
490
- timeToImplement: this.estimateTimeToImplement(defectType.type)
491
- };
492
- }
493
- generateGeneralPreventionRecommendations(predictions) {
494
- return [
495
- {
496
- id: `general-prevention-${Date.now()}`,
497
- category: 'general',
498
- priority: 'medium',
499
- title: 'Enhance Code Review Process',
500
- description: 'Implement more thorough code review practices to catch potential defects early',
501
- preventiveActions: [
502
- {
503
- type: 'review',
504
- description: 'Require two reviewers for high-risk changes',
505
- automated: false,
506
- tools: ['github', 'gitlab', 'bitbucket']
507
- }
508
- ],
509
- estimatedEffectiveness: 0.75,
510
- implementationCost: 'low',
511
- timeToImplement: 5
512
- }
513
- ];
514
- }
515
- assessOverallRisk(predictions) {
516
- const highRiskCount = predictions.filter(p => p.riskScore > 0.7).length;
517
- const mediumRiskCount = predictions.filter(p => p.riskScore > 0.4 && p.riskScore <= 0.7).length;
518
- let overallRisk;
519
- if (highRiskCount > 3)
520
- overallRisk = 'critical';
521
- else if (highRiskCount > 1)
522
- overallRisk = 'high';
523
- else if (mediumRiskCount > 5)
524
- overallRisk = 'medium';
525
- else
526
- overallRisk = 'low';
527
- return {
528
- overallRisk,
529
- riskFactors: this.identifyRiskFactors(predictions),
530
- mitigationStrategies: this.generateMitigationStrategies(overallRisk),
531
- businessImpact: this.estimateBusinessImpact(overallRisk, predictions)
532
- };
533
- }
534
- calculateOverallConfidence(predictions, model, features) {
535
- const averageConfidence = predictions.reduce((sum, p) => sum + p.confidence, 0) / predictions.length;
536
- return {
537
- score: averageConfidence,
538
- factors: [
539
- {
540
- factor: 'model-accuracy',
541
- impact: 0.4,
542
- description: `Model accuracy: ${(model.accuracy * 100).toFixed(1)}%`
543
- },
544
- {
545
- factor: 'feature-completeness',
546
- impact: 0.3,
547
- description: `Feature completeness: ${(features.size / this.featureExtractors.size * 100).toFixed(1)}%`
548
- },
549
- {
550
- factor: 'data-quality',
551
- impact: 0.3,
552
- description: 'Historical data quality and completeness'
553
- }
554
- ],
555
- limitations: [
556
- 'Predictions based on historical patterns may not account for novel defect types',
557
- 'Model accuracy decreases for rarely seen code patterns',
558
- 'External factors (team changes, tool updates) not fully captured'
559
- ],
560
- recommendations: [
561
- 'Continuously retrain models with new defect data',
562
- 'Validate predictions through manual review for critical components',
563
- 'Use predictions as guidance, not absolute truth'
564
- ]
565
- };
566
- }
567
- // Helper methods
568
- getTargetCount(analysisType) {
569
- const counts = { file: 10, function: 25, line: 50, module: 5 };
570
- return counts[analysisType] || 10;
571
- }
572
- generateTarget(analysisType, index) {
573
- const prefixes = { file: 'src/', function: 'function:', line: 'line:', module: 'module:' };
574
- const prefix = prefixes[analysisType] || '';
575
- return `${prefix}target_${index + 1}`;
576
- }
577
- getDefectTypeDescription(type) {
578
- const descriptions = {
579
- 'logic-error': 'Incorrect program logic leading to wrong behavior',
580
- 'null-pointer': 'Accessing null or undefined references',
581
- 'boundary-error': 'Array/string index out of bounds errors',
582
- 'concurrency-issue': 'Race conditions and thread safety problems',
583
- 'integration-failure': 'Failures in component or system integration',
584
- 'performance-degradation': 'Code changes causing performance issues'
585
- };
586
- return descriptions[type] || 'Unknown defect type';
587
- }
588
- getDefectTypeExamples(type) {
589
- const examples = {
590
- 'logic-error': ['Incorrect conditional logic', 'Wrong calculation formulas', 'Missing edge case handling'],
591
- 'null-pointer': ['Accessing properties of null objects', 'Using uninitialized variables', 'Missing null checks'],
592
- 'boundary-error': ['Array index out of bounds', 'String substring errors', 'Loop boundary conditions']
593
- };
594
- return examples[type] || ['No examples available'];
595
- }
596
- getDefectTypePrevention(type) {
597
- const prevention = {
598
- 'logic-error': ['Add comprehensive unit tests', 'Use property-based testing', 'Implement code reviews'],
599
- 'null-pointer': ['Use null-safe operators', 'Add null checks', 'Use static analysis tools'],
600
- 'boundary-error': ['Validate array bounds', 'Use safe collection methods', 'Add boundary tests']
601
- };
602
- return prevention[type] || ['Standard code review practices'];
603
- }
604
- interpretFeature(featureName, value) {
605
- if (featureName.includes('complexity')) {
606
- return value > 10 ? 'High complexity increases defect risk' : 'Acceptable complexity level';
607
- }
608
- if (featureName.includes('coverage')) {
609
- return value < 70 ? 'Low coverage increases defect risk' : 'Good test coverage';
610
- }
611
- return `Feature value: ${value.toFixed(2)}`;
612
- }
613
- categorizePreventionAction(action) {
614
- if (action.includes('review'))
615
- return 'review';
616
- if (action.includes('test'))
617
- return 'testing';
618
- if (action.includes('refactor'))
619
- return 'refactoring';
620
- if (action.includes('monitor'))
621
- return 'monitoring';
622
- return 'review';
623
- }
624
- isActionAutomated(action) {
625
- return action.includes('automated') || action.includes('static analysis') || action.includes('lint');
626
- }
627
- getRecommendedTools(action) {
628
- if (action.includes('test'))
629
- return ['jest', 'mocha', 'pytest'];
630
- if (action.includes('static'))
631
- return ['eslint', 'sonarqube', 'codecov'];
632
- if (action.includes('review'))
633
- return ['github', 'reviewboard'];
634
- return [];
635
- }
636
- estimateImplementationCost(defectType) {
637
- const costs = {
638
- 'logic-error': 'medium',
639
- 'null-pointer': 'low',
640
- 'boundary-error': 'low',
641
- 'concurrency-issue': 'high',
642
- 'integration-failure': 'high',
643
- 'performance-degradation': 'medium'
644
- };
645
- return costs[defectType] || 'medium';
646
- }
647
- estimateTimeToImplement(defectType) {
648
- const times = {
649
- 'logic-error': 8,
650
- 'null-pointer': 4,
651
- 'boundary-error': 4,
652
- 'concurrency-issue': 16,
653
- 'integration-failure': 12,
654
- 'performance-degradation': 10
655
- };
656
- return times[defectType] || 8;
657
- }
658
- identifyRiskFactors(predictions) {
659
- return [
660
- {
661
- factor: 'high-complexity-code',
662
- impact: 0.8,
663
- likelihood: 0.6,
664
- description: 'Multiple components with high cyclomatic complexity'
665
- },
666
- {
667
- factor: 'frequent-changes',
668
- impact: 0.6,
669
- likelihood: 0.7,
670
- description: 'Areas of code with frequent modifications'
671
- }
672
- ];
673
- }
674
- generateMitigationStrategies(overallRisk) {
675
- return [
676
- {
677
- strategy: 'Enhanced Testing',
678
- effectiveness: 0.8,
679
- cost: 0.6,
680
- timeToImplement: 2,
681
- description: 'Implement comprehensive testing for high-risk areas'
682
- },
683
- {
684
- strategy: 'Code Review Intensification',
685
- effectiveness: 0.7,
686
- cost: 0.3,
687
- timeToImplement: 1,
688
- description: 'Require additional reviewers for high-risk changes'
689
- }
690
- ];
691
- }
692
- estimateBusinessImpact(overallRisk, predictions) {
693
- const impactMultipliers = { low: 1, medium: 2, high: 4, critical: 8 };
694
- const multiplier = impactMultipliers[overallRisk];
695
- return {
696
- estimatedCost: multiplier * 5000, // Base cost $5000
697
- timeToResolve: multiplier * 2, // Base time 2 hours
698
- affectedUsers: multiplier * 100, // Base users 100
699
- reputationImpact: overallRisk === 'critical' ? 'high' : overallRisk === 'high' ? 'medium' : 'low'
700
- };
701
- }
702
- /**
703
- * Get prediction by ID
704
- */
705
- getPrediction(predictionId) {
706
- return this.predictionHistory.get(predictionId);
707
- }
708
- /**
709
- * List all predictions
710
- */
711
- listPredictions() {
712
- return Array.from(this.predictionHistory.values());
713
- }
714
- /**
715
- * Get model performance metrics
716
- */
717
- getModelMetrics(modelType) {
718
- return this.models.get(modelType);
719
- }
720
- }
721
- exports.PredictDefectsHandler = PredictDefectsHandler;
722
- //# sourceMappingURL=predict-defects.js.map