@goldensheepai/toknxr-cli 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli.js +182 -23
- package/lib/commands/hallucination-commands.js +453 -0
- package/lib/enhanced-hallucination-detector.js +622 -0
- package/lib/execution-based-detector.js +538 -0
- package/lib/execution-sandbox.js +602 -0
- package/lib/hallucination-database-service.js +447 -0
- package/lib/hallucination-patterns.js +490 -0
- package/lib/types/database-types.js +5 -0
- package/lib/types/hallucination-types.js +74 -0
- package/lib/types/index.js +8 -0
- package/lib/ui.js +73 -6
- package/package.json +1 -1
- package/lib/auth.js +0 -73
- package/lib/cli.test.js +0 -49
- package/lib/code-review.js +0 -319
- package/lib/config.js +0 -7
- package/lib/sync.js +0 -117
@@ -0,0 +1,622 @@
|
|
1
|
+
/**
|
2
|
+
* Enhanced Hallucination Detector
|
3
|
+
* Core detection algorithm implementing CodeHalu methodology
|
4
|
+
*/
|
5
|
+
import { HallucinationPatterns, detectAllPatterns, getPatternStatistics, } from './hallucination-patterns.js';
|
6
|
+
import { ExecutionSandbox } from './execution-sandbox.js';
|
7
|
+
/**
|
8
|
+
* Default detection configuration
|
9
|
+
*/
|
10
|
+
const DEFAULT_CONFIG = {
|
11
|
+
enableStaticAnalysis: true,
|
12
|
+
enableExecutionAnalysis: true,
|
13
|
+
enablePatternMatching: true,
|
14
|
+
enableStatisticalAnalysis: true,
|
15
|
+
maxExecutionTime: 5000,
|
16
|
+
confidenceThreshold: 0.6,
|
17
|
+
severityThreshold: 'medium',
|
18
|
+
};
|
19
|
+
/**
|
20
|
+
* Enhanced CodeHalu detection engine
|
21
|
+
*/
|
22
|
+
export class CodeHaluDetector {
|
23
|
+
constructor(config = {}) {
|
24
|
+
this.detectionHistory = new Map();
|
25
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
26
|
+
this.executionSandbox = new ExecutionSandbox({
|
27
|
+
maxExecutionTimeMs: this.config.maxExecutionTime,
|
28
|
+
maxMemoryMB: 128,
|
29
|
+
maxCpuCores: 1,
|
30
|
+
});
|
31
|
+
}
|
32
|
+
/**
|
33
|
+
* Main detection method - orchestrates all detection techniques
|
34
|
+
*/
|
35
|
+
async detectHallucinations(code, language = 'python', context) {
|
36
|
+
const startTime = Date.now();
|
37
|
+
try {
|
38
|
+
// Input validation
|
39
|
+
this.validateInput(code, language);
|
40
|
+
// Initialize result structure
|
41
|
+
const result = {
|
42
|
+
overallHallucinationRate: 0,
|
43
|
+
categories: [],
|
44
|
+
executionResult: undefined,
|
45
|
+
recommendations: [],
|
46
|
+
analysisMetadata: {
|
47
|
+
detectionTimeMs: 0,
|
48
|
+
codeLength: code.length,
|
49
|
+
language,
|
50
|
+
detectionMethods: [],
|
51
|
+
analysisVersion: '1.0.0',
|
52
|
+
},
|
53
|
+
businessImpact: {
|
54
|
+
estimatedDevTimeWasted: 0,
|
55
|
+
costMultiplier: 1.0,
|
56
|
+
qualityImpact: 0,
|
57
|
+
costOfHallucinations: 0,
|
58
|
+
},
|
59
|
+
};
|
60
|
+
// 1. Static Analysis (Pattern-based detection)
|
61
|
+
if (this.config.enableStaticAnalysis && this.config.enablePatternMatching) {
|
62
|
+
await this.performStaticAnalysis(code, result);
|
63
|
+
}
|
64
|
+
// 2. Execution-based Analysis
|
65
|
+
if (this.config.enableExecutionAnalysis && language === 'python') {
|
66
|
+
await this.performExecutionAnalysis(code, result, context);
|
67
|
+
}
|
68
|
+
// 3. Statistical Analysis (if enabled and we have history)
|
69
|
+
if (this.config.enableStatisticalAnalysis) {
|
70
|
+
await this.performStatisticalAnalysis(code, result, context);
|
71
|
+
}
|
72
|
+
// 4. Calculate overall hallucination rate
|
73
|
+
this.calculateOverallHallucinationRate(result);
|
74
|
+
// 5. Generate recommendations
|
75
|
+
this.generateRecommendations(result, context);
|
76
|
+
// 6. Calculate business impact
|
77
|
+
this.calculateBusinessImpact(result);
|
78
|
+
// 7. Finalize metadata
|
79
|
+
result.analysisMetadata.detectionTimeMs = Date.now() - startTime;
|
80
|
+
// Store in history for statistical analysis
|
81
|
+
const codeHash = this.generateCodeHash(code);
|
82
|
+
this.detectionHistory.set(codeHash, result);
|
83
|
+
return result;
|
84
|
+
}
|
85
|
+
catch (error) {
|
86
|
+
// Graceful error handling
|
87
|
+
return this.createErrorResult(error, code, language, Date.now() - startTime);
|
88
|
+
}
|
89
|
+
}
|
90
|
+
/**
|
91
|
+
* Perform static analysis using pattern matching
|
92
|
+
*/
|
93
|
+
async performStaticAnalysis(code, result) {
|
94
|
+
try {
|
95
|
+
const patternResults = detectAllPatterns(code);
|
96
|
+
const categories = HallucinationPatterns.convertToHallucinationCategories(patternResults);
|
97
|
+
// Filter by confidence threshold
|
98
|
+
const filteredCategories = categories.filter(category => category.confidence >= this.config.confidenceThreshold);
|
99
|
+
result.categories.push(...filteredCategories);
|
100
|
+
result.analysisMetadata.detectionMethods.push('static');
|
101
|
+
// Add pattern-specific metadata
|
102
|
+
const stats = getPatternStatistics(patternResults);
|
103
|
+
result.analysisMetadata.patternStats = stats;
|
104
|
+
}
|
105
|
+
catch (error) {
|
106
|
+
console.warn('Static analysis failed:', error);
|
107
|
+
// Continue with other detection methods
|
108
|
+
}
|
109
|
+
}
|
110
|
+
/**
|
111
|
+
* Perform execution-based analysis using sandbox
|
112
|
+
*/
|
113
|
+
async performExecutionAnalysis(code, result, context) {
|
114
|
+
try {
|
115
|
+
// Security check first
|
116
|
+
const securityAssessment = this.executionSandbox.validateSafety(code);
|
117
|
+
if (!securityAssessment.isSafe) {
|
118
|
+
// Add security-related hallucination categories
|
119
|
+
result.categories.push({
|
120
|
+
type: 'resource',
|
121
|
+
subtype: 'physical_constraint',
|
122
|
+
severity: 'critical',
|
123
|
+
confidence: securityAssessment.confidence,
|
124
|
+
description: 'Code contains potentially dangerous operations',
|
125
|
+
evidence: securityAssessment.risks.map(risk => ({
|
126
|
+
type: 'security_risk',
|
127
|
+
content: risk,
|
128
|
+
confidence: 0.9,
|
129
|
+
})),
|
130
|
+
suggestedFix: 'Remove dangerous operations or add proper security measures',
|
131
|
+
businessImpact: {
|
132
|
+
estimatedDevTimeWasted: 4.0,
|
133
|
+
costMultiplier: 2.0,
|
134
|
+
qualityImpact: 50,
|
135
|
+
costOfHallucinations: 400.0,
|
136
|
+
},
|
137
|
+
});
|
138
|
+
return;
|
139
|
+
}
|
140
|
+
// Execute the code
|
141
|
+
const executionResult = await this.executionSandbox.execute(code);
|
142
|
+
result.executionResult = executionResult;
|
143
|
+
result.analysisMetadata.detectionMethods.push('execution');
|
144
|
+
// Analyze execution results for hallucinations
|
145
|
+
await this.analyzeExecutionResults(executionResult, result, context);
|
146
|
+
}
|
147
|
+
catch (error) {
|
148
|
+
console.warn('Execution analysis failed:', error);
|
149
|
+
// Add execution failure as potential hallucination indicator
|
150
|
+
result.categories.push({
|
151
|
+
type: 'logic',
|
152
|
+
subtype: 'logic_breakdown',
|
153
|
+
severity: 'high',
|
154
|
+
confidence: 0.8,
|
155
|
+
description: 'Code failed to execute properly',
|
156
|
+
evidence: [{
|
157
|
+
type: 'execution_error',
|
158
|
+
content: error instanceof Error ? error.message : 'Unknown execution error',
|
159
|
+
confidence: 0.9,
|
160
|
+
}],
|
161
|
+
suggestedFix: 'Review code for syntax and logical errors',
|
162
|
+
businessImpact: {
|
163
|
+
estimatedDevTimeWasted: 3.0,
|
164
|
+
costMultiplier: 1.5,
|
165
|
+
qualityImpact: 40,
|
166
|
+
costOfHallucinations: 225.0,
|
167
|
+
},
|
168
|
+
});
|
169
|
+
}
|
170
|
+
}
|
171
|
+
/**
|
172
|
+
* Analyze execution results for hallucination indicators
|
173
|
+
*/
|
174
|
+
async analyzeExecutionResults(executionResult, result, context) {
|
175
|
+
// 1. Check for runtime errors
|
176
|
+
if (executionResult.errors.length > 0) {
|
177
|
+
executionResult.errors.forEach(error => {
|
178
|
+
const category = this.mapExecutionErrorToCategory(error);
|
179
|
+
if (category) {
|
180
|
+
result.categories.push(category);
|
181
|
+
}
|
182
|
+
});
|
183
|
+
}
|
184
|
+
// 2. Check for resource usage anomalies
|
185
|
+
if (executionResult.resourceUsage.memoryMB > 100) {
|
186
|
+
result.categories.push({
|
187
|
+
type: 'resource',
|
188
|
+
subtype: 'physical_constraint',
|
189
|
+
severity: 'medium',
|
190
|
+
confidence: 0.7,
|
191
|
+
description: 'Code uses excessive memory',
|
192
|
+
evidence: [{
|
193
|
+
type: 'resource_usage',
|
194
|
+
content: `Memory usage: ${executionResult.resourceUsage.memoryMB}MB`,
|
195
|
+
confidence: 0.9,
|
196
|
+
}],
|
197
|
+
suggestedFix: 'Optimize memory usage or add memory limits',
|
198
|
+
businessImpact: {
|
199
|
+
estimatedDevTimeWasted: 1.5,
|
200
|
+
costMultiplier: 1.2,
|
201
|
+
qualityImpact: 20,
|
202
|
+
costOfHallucinations: 90.0,
|
203
|
+
},
|
204
|
+
});
|
205
|
+
}
|
206
|
+
// 3. Check for timeout issues
|
207
|
+
if (executionResult.timedOut) {
|
208
|
+
result.categories.push({
|
209
|
+
type: 'resource',
|
210
|
+
subtype: 'computational_boundary',
|
211
|
+
severity: 'high',
|
212
|
+
confidence: 0.9,
|
213
|
+
description: 'Code execution timed out',
|
214
|
+
evidence: [{
|
215
|
+
type: 'timeout',
|
216
|
+
content: `Execution exceeded ${this.config.maxExecutionTime}ms`,
|
217
|
+
confidence: 1.0,
|
218
|
+
}],
|
219
|
+
suggestedFix: 'Optimize algorithm or add proper termination conditions',
|
220
|
+
businessImpact: {
|
221
|
+
estimatedDevTimeWasted: 3.0,
|
222
|
+
costMultiplier: 1.6,
|
223
|
+
qualityImpact: 35,
|
224
|
+
costOfHallucinations: 240.0,
|
225
|
+
},
|
226
|
+
});
|
227
|
+
}
|
228
|
+
// 4. Check output consistency (if expected output provided)
|
229
|
+
if (context?.expectedOutput && executionResult.output) {
|
230
|
+
const outputConsistency = this.checkOutputConsistency(executionResult.output, context.expectedOutput);
|
231
|
+
if (outputConsistency.confidence < 0.7) {
|
232
|
+
result.categories.push({
|
233
|
+
type: 'logic',
|
234
|
+
subtype: 'logic_deviation',
|
235
|
+
severity: 'medium',
|
236
|
+
confidence: 1.0 - outputConsistency.confidence,
|
237
|
+
description: 'Output does not match expected result',
|
238
|
+
evidence: [{
|
239
|
+
type: 'output_mismatch',
|
240
|
+
content: `Expected: ${context.expectedOutput}, Got: ${executionResult.output}`,
|
241
|
+
confidence: 0.8,
|
242
|
+
}],
|
243
|
+
suggestedFix: 'Review logic and ensure correct implementation',
|
244
|
+
businessImpact: {
|
245
|
+
estimatedDevTimeWasted: 2.5,
|
246
|
+
costMultiplier: 1.3,
|
247
|
+
qualityImpact: 25,
|
248
|
+
costOfHallucinations: 125.0,
|
249
|
+
},
|
250
|
+
});
|
251
|
+
}
|
252
|
+
}
|
253
|
+
}
|
254
|
+
/**
|
255
|
+
* Perform statistical analysis based on historical patterns
|
256
|
+
*/
|
257
|
+
async performStatisticalAnalysis(code, result, context) {
|
258
|
+
try {
|
259
|
+
// Analyze patterns across historical data
|
260
|
+
const historicalPatterns = this.analyzeHistoricalPatterns(code);
|
261
|
+
if (historicalPatterns.length > 0) {
|
262
|
+
result.analysisMetadata.detectionMethods.push('statistical');
|
263
|
+
// Add statistical confidence adjustments
|
264
|
+
result.categories.forEach(category => {
|
265
|
+
const historicalMatch = historicalPatterns.find(pattern => pattern.categoryType === category.type);
|
266
|
+
if (historicalMatch) {
|
267
|
+
// Adjust confidence based on historical reliability
|
268
|
+
category.confidence = Math.min(1.0, category.confidence * historicalMatch.reliability);
|
269
|
+
}
|
270
|
+
});
|
271
|
+
}
|
272
|
+
}
|
273
|
+
catch (error) {
|
274
|
+
console.warn('Statistical analysis failed:', error);
|
275
|
+
}
|
276
|
+
}
|
277
|
+
/**
|
278
|
+
* Calculate overall hallucination rate
|
279
|
+
*/
|
280
|
+
calculateOverallHallucinationRate(result) {
|
281
|
+
if (result.categories.length === 0) {
|
282
|
+
result.overallHallucinationRate = 0;
|
283
|
+
return;
|
284
|
+
}
|
285
|
+
// Weight by severity and confidence
|
286
|
+
const severityWeights = { low: 1, medium: 2, high: 3, critical: 4 };
|
287
|
+
let totalWeight = 0;
|
288
|
+
let weightedSum = 0;
|
289
|
+
result.categories.forEach(category => {
|
290
|
+
const weight = severityWeights[category.severity] * category.confidence;
|
291
|
+
totalWeight += weight;
|
292
|
+
weightedSum += weight;
|
293
|
+
});
|
294
|
+
// Normalize to 0-1 scale
|
295
|
+
const maxPossibleWeight = result.categories.length * 4; // All critical with confidence 1.0
|
296
|
+
result.overallHallucinationRate = Math.min(1.0, weightedSum / maxPossibleWeight);
|
297
|
+
}
|
298
|
+
/**
|
299
|
+
* Generate actionable recommendations
|
300
|
+
*/
|
301
|
+
generateRecommendations(result, context) {
|
302
|
+
const recommendations = [];
|
303
|
+
// Group categories by type for targeted recommendations
|
304
|
+
const categoryGroups = this.groupCategoriesByType(result.categories);
|
305
|
+
Object.entries(categoryGroups).forEach(([type, categories]) => {
|
306
|
+
const recommendation = this.generateTypeSpecificRecommendation(type, categories, context);
|
307
|
+
if (recommendation) {
|
308
|
+
recommendations.push(recommendation);
|
309
|
+
}
|
310
|
+
});
|
311
|
+
// Add general recommendations based on overall analysis
|
312
|
+
if (result.overallHallucinationRate > 0.7) {
|
313
|
+
recommendations.push({
|
314
|
+
priority: 'high',
|
315
|
+
title: 'Critical Code Review Required',
|
316
|
+
description: 'Multiple serious issues detected that require immediate attention',
|
317
|
+
actionItems: [
|
318
|
+
'Conduct thorough code review',
|
319
|
+
'Test with multiple input scenarios',
|
320
|
+
'Consider alternative implementation approach',
|
321
|
+
],
|
322
|
+
expectedImpact: 'Prevent production issues and reduce debugging time',
|
323
|
+
estimatedTimeToFix: '2-4 hours',
|
324
|
+
});
|
325
|
+
}
|
326
|
+
result.recommendations = recommendations;
|
327
|
+
}
|
328
|
+
/**
|
329
|
+
* Calculate business impact metrics
|
330
|
+
*/
|
331
|
+
calculateBusinessImpact(result) {
|
332
|
+
const impact = result.businessImpact;
|
333
|
+
// Sum up individual category impacts
|
334
|
+
result.categories.forEach(category => {
|
335
|
+
impact.estimatedDevTimeWasted += category.businessImpact.estimatedDevTimeWasted;
|
336
|
+
impact.qualityImpact = Math.max(impact.qualityImpact, category.businessImpact.qualityImpact);
|
337
|
+
impact.costMultiplier = Math.max(impact.costMultiplier, category.businessImpact.costMultiplier);
|
338
|
+
});
|
339
|
+
// Calculate cost of hallucinations (assuming $100/hour developer rate)
|
340
|
+
const hourlyRate = 100;
|
341
|
+
impact.costOfHallucinations = impact.estimatedDevTimeWasted * hourlyRate;
|
342
|
+
// Apply cost multiplier for indirect costs
|
343
|
+
impact.costOfHallucinations *= impact.costMultiplier;
|
344
|
+
}
|
345
|
+
/**
|
346
|
+
* Helper methods
|
347
|
+
*/
|
348
|
+
validateInput(code, language) {
|
349
|
+
if (!code || code.trim().length === 0) {
|
350
|
+
throw new Error('Code cannot be empty');
|
351
|
+
}
|
352
|
+
if (code.length > 100000) {
|
353
|
+
throw new Error('Code is too long (max 100KB)');
|
354
|
+
}
|
355
|
+
const supportedLanguages = ['python', 'javascript', 'typescript'];
|
356
|
+
if (!supportedLanguages.includes(language.toLowerCase())) {
|
357
|
+
console.warn(`Language '${language}' not fully supported. Using generic analysis.`);
|
358
|
+
}
|
359
|
+
}
|
360
|
+
mapExecutionErrorToCategory(error) {
|
361
|
+
const errorTypeMap = {
|
362
|
+
'TypeError': { type: 'mapping', subtype: 'data_compliance', severity: 'high' },
|
363
|
+
'IndexError': { type: 'mapping', subtype: 'structure_access', severity: 'medium' },
|
364
|
+
'KeyError': { type: 'mapping', subtype: 'structure_access', severity: 'medium' },
|
365
|
+
'NameError': { type: 'naming', subtype: 'identity', severity: 'high' },
|
366
|
+
'AttributeError': { type: 'naming', subtype: 'identity', severity: 'medium' },
|
367
|
+
'ImportError': { type: 'naming', subtype: 'external_source', severity: 'critical' },
|
368
|
+
'MemoryError': { type: 'resource', subtype: 'physical_constraint', severity: 'critical' },
|
369
|
+
'RecursionError': { type: 'resource', subtype: 'computational_boundary', severity: 'high' },
|
370
|
+
'ZeroDivisionError': { type: 'logic', subtype: 'logic_deviation', severity: 'high' },
|
371
|
+
};
|
372
|
+
const mapping = errorTypeMap[error.type];
|
373
|
+
if (!mapping)
|
374
|
+
return null;
|
375
|
+
return {
|
376
|
+
type: mapping.type,
|
377
|
+
subtype: mapping.subtype,
|
378
|
+
severity: mapping.severity,
|
379
|
+
confidence: 0.9,
|
380
|
+
description: `Runtime ${error.type}: ${error.message}`,
|
381
|
+
evidence: [{
|
382
|
+
type: 'execution_error',
|
383
|
+
content: error.message,
|
384
|
+
lineNumber: error.lineNumber,
|
385
|
+
confidence: 1.0,
|
386
|
+
}],
|
387
|
+
suggestedFix: this.getErrorSpecificFix(error.type),
|
388
|
+
businessImpact: {
|
389
|
+
estimatedDevTimeWasted: mapping.severity === 'critical' ? 4.0 :
|
390
|
+
mapping.severity === 'high' ? 2.5 : 1.5,
|
391
|
+
costMultiplier: mapping.severity === 'critical' ? 2.0 : 1.3,
|
392
|
+
qualityImpact: mapping.severity === 'critical' ? 50 :
|
393
|
+
mapping.severity === 'high' ? 35 : 20,
|
394
|
+
costOfHallucinations: (mapping.severity === 'critical' ? 4.0 :
|
395
|
+
mapping.severity === 'high' ? 2.5 : 1.5) * 100,
|
396
|
+
},
|
397
|
+
};
|
398
|
+
}
|
399
|
+
getErrorSpecificFix(errorType) {
|
400
|
+
const fixes = {
|
401
|
+
'TypeError': 'Check data types and add type validation',
|
402
|
+
'IndexError': 'Add bounds checking before array access',
|
403
|
+
'KeyError': 'Use .get() method or verify key existence',
|
404
|
+
'NameError': 'Define variable before use',
|
405
|
+
'AttributeError': 'Verify object has the required attribute',
|
406
|
+
'ImportError': 'Install required package or fix import path',
|
407
|
+
'MemoryError': 'Optimize memory usage',
|
408
|
+
'RecursionError': 'Add base case or use iteration',
|
409
|
+
'ZeroDivisionError': 'Add zero division check',
|
410
|
+
};
|
411
|
+
return fixes[errorType] || 'Review and fix the error';
|
412
|
+
}
|
413
|
+
checkOutputConsistency(actual, expected) {
|
414
|
+
// Simple consistency check - can be enhanced with more sophisticated comparison
|
415
|
+
const actualStr = actual.toString().trim();
|
416
|
+
const expectedStr = expected.toString().trim();
|
417
|
+
if (actualStr === expectedStr) {
|
418
|
+
return { confidence: 1.0 };
|
419
|
+
}
|
420
|
+
// Check for partial matches
|
421
|
+
const similarity = this.calculateStringSimilarity(actualStr, expectedStr);
|
422
|
+
return { confidence: similarity };
|
423
|
+
}
|
424
|
+
calculateStringSimilarity(str1, str2) {
|
425
|
+
// Simple Levenshtein distance-based similarity
|
426
|
+
const longer = str1.length > str2.length ? str1 : str2;
|
427
|
+
const shorter = str1.length > str2.length ? str2 : str1;
|
428
|
+
if (longer.length === 0)
|
429
|
+
return 1.0;
|
430
|
+
const distance = this.levenshteinDistance(longer, shorter);
|
431
|
+
return (longer.length - distance) / longer.length;
|
432
|
+
}
|
433
|
+
levenshteinDistance(str1, str2) {
|
434
|
+
const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
|
435
|
+
for (let i = 0; i <= str1.length; i++)
|
436
|
+
matrix[0][i] = i;
|
437
|
+
for (let j = 0; j <= str2.length; j++)
|
438
|
+
matrix[j][0] = j;
|
439
|
+
for (let j = 1; j <= str2.length; j++) {
|
440
|
+
for (let i = 1; i <= str1.length; i++) {
|
441
|
+
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
|
442
|
+
matrix[j][i] = Math.min(matrix[j][i - 1] + 1, matrix[j - 1][i] + 1, matrix[j - 1][i - 1] + indicator);
|
443
|
+
}
|
444
|
+
}
|
445
|
+
return matrix[str2.length][str1.length];
|
446
|
+
}
|
447
|
+
analyzeHistoricalPatterns(code) {
|
448
|
+
// Simplified historical analysis - in production, this would use a database
|
449
|
+
const patterns = [];
|
450
|
+
// Analyze code characteristics and match with historical patterns
|
451
|
+
const codeFeatures = this.extractCodeFeatures(code);
|
452
|
+
// Mock historical pattern matching
|
453
|
+
if (codeFeatures.hasLoops && codeFeatures.hasArrayAccess) {
|
454
|
+
patterns.push({ categoryType: 'mapping', reliability: 0.85 });
|
455
|
+
}
|
456
|
+
if (codeFeatures.hasImports && codeFeatures.hasExternalCalls) {
|
457
|
+
patterns.push({ categoryType: 'naming', reliability: 0.75 });
|
458
|
+
}
|
459
|
+
return patterns;
|
460
|
+
}
|
461
|
+
extractCodeFeatures(code) {
|
462
|
+
return {
|
463
|
+
hasLoops: /for\s+|while\s+/.test(code),
|
464
|
+
hasArrayAccess: /\[\s*\w+\s*\]/.test(code),
|
465
|
+
hasImports: /import\s+|from\s+/.test(code),
|
466
|
+
hasExternalCalls: /\w+\.\w+\s*\(/.test(code),
|
467
|
+
};
|
468
|
+
}
|
469
|
+
groupCategoriesByType(categories) {
|
470
|
+
return categories.reduce((groups, category) => {
|
471
|
+
const type = category.type;
|
472
|
+
if (!groups[type])
|
473
|
+
groups[type] = [];
|
474
|
+
groups[type].push(category);
|
475
|
+
return groups;
|
476
|
+
}, {});
|
477
|
+
}
|
478
|
+
generateTypeSpecificRecommendation(type, categories, context) {
|
479
|
+
const recommendations = {
|
480
|
+
mapping: {
|
481
|
+
title: 'Data Type and Structure Issues',
|
482
|
+
description: 'Code contains potential data mapping problems',
|
483
|
+
actionItems: [
|
484
|
+
'Add type checking and validation',
|
485
|
+
'Verify data structure assumptions',
|
486
|
+
'Test with edge cases and different data types',
|
487
|
+
],
|
488
|
+
},
|
489
|
+
naming: {
|
490
|
+
title: 'Identifier and Reference Issues',
|
491
|
+
description: 'Code contains potential naming and reference problems',
|
492
|
+
actionItems: [
|
493
|
+
'Verify all variables and functions are defined',
|
494
|
+
'Check import statements and module availability',
|
495
|
+
'Review scope and naming conventions',
|
496
|
+
],
|
497
|
+
},
|
498
|
+
resource: {
|
499
|
+
title: 'Resource and Performance Issues',
|
500
|
+
description: 'Code may have resource consumption problems',
|
501
|
+
actionItems: [
|
502
|
+
'Add resource limits and monitoring',
|
503
|
+
'Optimize memory and CPU usage',
|
504
|
+
'Implement proper error handling for resource constraints',
|
505
|
+
],
|
506
|
+
},
|
507
|
+
logic: {
|
508
|
+
title: 'Logic and Flow Issues',
|
509
|
+
description: 'Code contains potential logical inconsistencies',
|
510
|
+
actionItems: [
|
511
|
+
'Review algorithm logic and flow',
|
512
|
+
'Add proper termination conditions',
|
513
|
+
'Test with various input scenarios',
|
514
|
+
],
|
515
|
+
},
|
516
|
+
};
|
517
|
+
const config = recommendations[type];
|
518
|
+
if (!config)
|
519
|
+
return null;
|
520
|
+
const highSeverityCount = categories.filter(c => c.severity === 'high' || c.severity === 'critical').length;
|
521
|
+
const priority = highSeverityCount > 0 ? 'high' : 'medium';
|
522
|
+
return {
|
523
|
+
priority,
|
524
|
+
title: config.title,
|
525
|
+
description: config.description,
|
526
|
+
actionItems: config.actionItems,
|
527
|
+
expectedImpact: `Resolve ${categories.length} ${type} issue(s)`,
|
528
|
+
estimatedTimeToFix: this.estimateFixTime(categories),
|
529
|
+
};
|
530
|
+
}
|
531
|
+
estimateFixTime(categories) {
|
532
|
+
const totalTime = categories.reduce((sum, category) => {
|
533
|
+
return sum + category.businessImpact.estimatedDevTimeWasted;
|
534
|
+
}, 0);
|
535
|
+
if (totalTime < 1)
|
536
|
+
return '15-30 minutes';
|
537
|
+
if (totalTime < 2)
|
538
|
+
return '30-60 minutes';
|
539
|
+
if (totalTime < 4)
|
540
|
+
return '1-2 hours';
|
541
|
+
if (totalTime < 8)
|
542
|
+
return '2-4 hours';
|
543
|
+
return '4+ hours';
|
544
|
+
}
|
545
|
+
generateCodeHash(code) {
|
546
|
+
// Simple hash function for code identification
|
547
|
+
let hash = 0;
|
548
|
+
for (let i = 0; i < code.length; i++) {
|
549
|
+
const char = code.charCodeAt(i);
|
550
|
+
hash = ((hash << 5) - hash) + char;
|
551
|
+
hash = hash & hash; // Convert to 32-bit integer
|
552
|
+
}
|
553
|
+
return hash.toString(36);
|
554
|
+
}
|
555
|
+
createErrorResult(error, code, language, detectionTime) {
|
556
|
+
return {
|
557
|
+
overallHallucinationRate: 1.0, // Assume high hallucination rate on error
|
558
|
+
categories: [{
|
559
|
+
type: 'logic',
|
560
|
+
subtype: 'logic_breakdown',
|
561
|
+
severity: 'critical',
|
562
|
+
confidence: 0.9,
|
563
|
+
description: 'Detection failed due to critical error',
|
564
|
+
evidence: [{
|
565
|
+
type: 'system_error',
|
566
|
+
content: error instanceof Error ? error.message : 'Unknown error',
|
567
|
+
confidence: 1.0,
|
568
|
+
}],
|
569
|
+
suggestedFix: 'Review code structure and syntax',
|
570
|
+
businessImpact: {
|
571
|
+
estimatedDevTimeWasted: 4.0,
|
572
|
+
costMultiplier: 2.0,
|
573
|
+
qualityImpact: 50,
|
574
|
+
costOfHallucinations: 400.0,
|
575
|
+
},
|
576
|
+
}],
|
577
|
+
recommendations: [{
|
578
|
+
priority: 'high',
|
579
|
+
title: 'Critical Analysis Failure',
|
580
|
+
description: 'Code analysis failed - manual review required',
|
581
|
+
actionItems: [
|
582
|
+
'Check code syntax and structure',
|
583
|
+
'Verify code is complete and valid',
|
584
|
+
'Consider breaking down complex code',
|
585
|
+
],
|
586
|
+
expectedImpact: 'Enable proper analysis and detection',
|
587
|
+
estimatedTimeToFix: '1-2 hours',
|
588
|
+
}],
|
589
|
+
analysisMetadata: {
|
590
|
+
detectionTimeMs: detectionTime,
|
591
|
+
codeLength: code.length,
|
592
|
+
language,
|
593
|
+
detectionMethods: ['error'],
|
594
|
+
analysisVersion: '1.0.0',
|
595
|
+
},
|
596
|
+
businessImpact: {
|
597
|
+
estimatedDevTimeWasted: 4.0,
|
598
|
+
costMultiplier: 2.0,
|
599
|
+
qualityImpact: 50,
|
600
|
+
costOfHallucinations: 800.0, // 4 hours * $100/hour * 2.0 multiplier
|
601
|
+
},
|
602
|
+
};
|
603
|
+
}
|
604
|
+
}
|
605
|
+
/**
|
606
|
+
* Factory function to create detector with default configuration
|
607
|
+
*/
|
608
|
+
export function createCodeHaluDetector(config) {
|
609
|
+
return new CodeHaluDetector(config);
|
610
|
+
}
|
611
|
+
/**
|
612
|
+
* Utility function for quick hallucination detection
|
613
|
+
*/
|
614
|
+
export async function detectCodeHallucinations(code, language = 'python', options) {
|
615
|
+
const config = {
|
616
|
+
enableExecutionAnalysis: options?.enableExecution ?? true,
|
617
|
+
maxExecutionTime: options?.maxExecutionTime ?? 5000,
|
618
|
+
confidenceThreshold: options?.confidenceThreshold ?? 0.6,
|
619
|
+
};
|
620
|
+
const detector = createCodeHaluDetector(config);
|
621
|
+
return await detector.detectHallucinations(code, language);
|
622
|
+
}
|