@loxia-labs/loxia-autopilot-one 1.0.1
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/LICENSE +267 -0
- package/README.md +509 -0
- package/bin/cli.js +117 -0
- package/package.json +94 -0
- package/scripts/install-scanners.js +236 -0
- package/src/analyzers/CSSAnalyzer.js +297 -0
- package/src/analyzers/ConfigValidator.js +690 -0
- package/src/analyzers/ESLintAnalyzer.js +320 -0
- package/src/analyzers/JavaScriptAnalyzer.js +261 -0
- package/src/analyzers/PrettierFormatter.js +247 -0
- package/src/analyzers/PythonAnalyzer.js +266 -0
- package/src/analyzers/SecurityAnalyzer.js +729 -0
- package/src/analyzers/TypeScriptAnalyzer.js +247 -0
- package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
- package/src/analyzers/codeCloneDetector/detector.js +203 -0
- package/src/analyzers/codeCloneDetector/index.js +160 -0
- package/src/analyzers/codeCloneDetector/parser.js +199 -0
- package/src/analyzers/codeCloneDetector/reporter.js +148 -0
- package/src/analyzers/codeCloneDetector/scanner.js +59 -0
- package/src/core/agentPool.js +1474 -0
- package/src/core/agentScheduler.js +2147 -0
- package/src/core/contextManager.js +709 -0
- package/src/core/messageProcessor.js +732 -0
- package/src/core/orchestrator.js +548 -0
- package/src/core/stateManager.js +877 -0
- package/src/index.js +631 -0
- package/src/interfaces/cli.js +549 -0
- package/src/interfaces/webServer.js +2162 -0
- package/src/modules/fileExplorer/controller.js +280 -0
- package/src/modules/fileExplorer/index.js +37 -0
- package/src/modules/fileExplorer/middleware.js +92 -0
- package/src/modules/fileExplorer/routes.js +125 -0
- package/src/modules/fileExplorer/types.js +44 -0
- package/src/services/aiService.js +1232 -0
- package/src/services/apiKeyManager.js +164 -0
- package/src/services/benchmarkService.js +366 -0
- package/src/services/budgetService.js +539 -0
- package/src/services/contextInjectionService.js +247 -0
- package/src/services/conversationCompactionService.js +637 -0
- package/src/services/errorHandler.js +810 -0
- package/src/services/fileAttachmentService.js +544 -0
- package/src/services/modelRouterService.js +366 -0
- package/src/services/modelsService.js +322 -0
- package/src/services/qualityInspector.js +796 -0
- package/src/services/tokenCountingService.js +536 -0
- package/src/tools/agentCommunicationTool.js +1344 -0
- package/src/tools/agentDelayTool.js +485 -0
- package/src/tools/asyncToolManager.js +604 -0
- package/src/tools/baseTool.js +800 -0
- package/src/tools/browserTool.js +920 -0
- package/src/tools/cloneDetectionTool.js +621 -0
- package/src/tools/dependencyResolverTool.js +1215 -0
- package/src/tools/fileContentReplaceTool.js +875 -0
- package/src/tools/fileSystemTool.js +1107 -0
- package/src/tools/fileTreeTool.js +853 -0
- package/src/tools/imageTool.js +901 -0
- package/src/tools/importAnalyzerTool.js +1060 -0
- package/src/tools/jobDoneTool.js +248 -0
- package/src/tools/seekTool.js +956 -0
- package/src/tools/staticAnalysisTool.js +1778 -0
- package/src/tools/taskManagerTool.js +2873 -0
- package/src/tools/terminalTool.js +2304 -0
- package/src/tools/webTool.js +1430 -0
- package/src/types/agent.js +519 -0
- package/src/types/contextReference.js +972 -0
- package/src/types/conversation.js +730 -0
- package/src/types/toolCommand.js +747 -0
- package/src/utilities/attachmentValidator.js +292 -0
- package/src/utilities/configManager.js +582 -0
- package/src/utilities/constants.js +722 -0
- package/src/utilities/directoryAccessManager.js +535 -0
- package/src/utilities/fileProcessor.js +307 -0
- package/src/utilities/logger.js +436 -0
- package/src/utilities/tagParser.js +1246 -0
- package/src/utilities/toolConstants.js +317 -0
- package/web-ui/build/index.html +15 -0
- package/web-ui/build/logo.png +0 -0
- package/web-ui/build/logo2.png +0 -0
- package/web-ui/build/static/index-CjkkcnFA.js +344 -0
- package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScriptAnalyzer - Analyze TypeScript files for errors using TypeScript Compiler API
|
|
3
|
+
*
|
|
4
|
+
* Purpose:
|
|
5
|
+
* - Analyze TypeScript files for syntax, type, and semantic errors
|
|
6
|
+
* - Use TypeScript Compiler API with full type checking
|
|
7
|
+
* - Provide detailed error information with line numbers
|
|
8
|
+
* - Support TSX syntax
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import ts from 'typescript';
|
|
12
|
+
import path from 'path';
|
|
13
|
+
import { STATIC_ANALYSIS } from '../utilities/constants.js';
|
|
14
|
+
|
|
15
|
+
class TypeScriptAnalyzer {
|
|
16
|
+
constructor(logger = null) {
|
|
17
|
+
this.logger = logger;
|
|
18
|
+
this.compilerOptions = {
|
|
19
|
+
noEmit: true,
|
|
20
|
+
jsx: ts.JsxEmit.React,
|
|
21
|
+
target: ts.ScriptTarget.Latest,
|
|
22
|
+
module: ts.ModuleKind.ESNext,
|
|
23
|
+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
|
|
24
|
+
esModuleInterop: true,
|
|
25
|
+
skipLibCheck: true,
|
|
26
|
+
strict: true, // Enable strict type checking for TypeScript
|
|
27
|
+
noImplicitAny: true,
|
|
28
|
+
strictNullChecks: true,
|
|
29
|
+
strictFunctionTypes: true,
|
|
30
|
+
allowJs: false // TypeScript only
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Analyze TypeScript file for errors
|
|
36
|
+
* @param {string} filePath - Path to file
|
|
37
|
+
* @param {string} content - File content
|
|
38
|
+
* @param {Object} options - Analysis options
|
|
39
|
+
* @returns {Promise<Array>} Array of diagnostic errors
|
|
40
|
+
*/
|
|
41
|
+
async analyze(filePath, content, options = {}) {
|
|
42
|
+
try {
|
|
43
|
+
const diagnostics = [];
|
|
44
|
+
|
|
45
|
+
// Create in-memory source file
|
|
46
|
+
const sourceFile = ts.createSourceFile(
|
|
47
|
+
filePath,
|
|
48
|
+
content,
|
|
49
|
+
ts.ScriptTarget.Latest,
|
|
50
|
+
true // setParentNodes
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
// Get syntactic diagnostics (syntax errors)
|
|
54
|
+
const syntacticDiagnostics = this.getSyntacticDiagnostics(sourceFile);
|
|
55
|
+
diagnostics.push(...syntacticDiagnostics);
|
|
56
|
+
|
|
57
|
+
// Get semantic diagnostics (type errors, undefined variables, etc.)
|
|
58
|
+
const semanticDiagnostics = await this.getSemanticDiagnostics(filePath, content);
|
|
59
|
+
diagnostics.push(...semanticDiagnostics);
|
|
60
|
+
|
|
61
|
+
this.logger?.debug('TypeScript analysis completed', {
|
|
62
|
+
file: filePath,
|
|
63
|
+
totalDiagnostics: diagnostics.length,
|
|
64
|
+
errors: diagnostics.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.ERROR).length,
|
|
65
|
+
warnings: diagnostics.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.WARNING).length
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
return diagnostics;
|
|
69
|
+
|
|
70
|
+
} catch (error) {
|
|
71
|
+
this.logger?.error('TypeScript analysis failed', {
|
|
72
|
+
file: filePath,
|
|
73
|
+
error: error.message
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
return [{
|
|
77
|
+
file: filePath,
|
|
78
|
+
line: 0,
|
|
79
|
+
column: 0,
|
|
80
|
+
severity: STATIC_ANALYSIS.SEVERITY.ERROR,
|
|
81
|
+
rule: 'analyzer-error',
|
|
82
|
+
message: `Analysis failed: ${error.message}`,
|
|
83
|
+
category: STATIC_ANALYSIS.CATEGORY.SYNTAX
|
|
84
|
+
}];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Get syntactic diagnostics (syntax errors)
|
|
90
|
+
* @private
|
|
91
|
+
*/
|
|
92
|
+
getSyntacticDiagnostics(sourceFile) {
|
|
93
|
+
const diagnostics = [];
|
|
94
|
+
|
|
95
|
+
// Check for parsing errors
|
|
96
|
+
if (sourceFile.parseDiagnostics && sourceFile.parseDiagnostics.length > 0) {
|
|
97
|
+
for (const diagnostic of sourceFile.parseDiagnostics) {
|
|
98
|
+
diagnostics.push(this.formatDiagnostic(diagnostic, sourceFile));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return diagnostics;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Get semantic diagnostics (type errors, undefined variables)
|
|
107
|
+
* @private
|
|
108
|
+
*/
|
|
109
|
+
async getSemanticDiagnostics(filePath, content) {
|
|
110
|
+
const diagnostics = [];
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// Create a minimal program for semantic analysis
|
|
114
|
+
const sourceFile = ts.createSourceFile(
|
|
115
|
+
filePath,
|
|
116
|
+
content,
|
|
117
|
+
ts.ScriptTarget.Latest,
|
|
118
|
+
true
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
// Create a compiler host that provides files from memory
|
|
122
|
+
const host = {
|
|
123
|
+
getSourceFile: (fileName) => {
|
|
124
|
+
if (fileName === filePath) {
|
|
125
|
+
return sourceFile;
|
|
126
|
+
}
|
|
127
|
+
// Return undefined for library files - they won't be available
|
|
128
|
+
return undefined;
|
|
129
|
+
},
|
|
130
|
+
getDefaultLibFileName: () => 'lib.d.ts',
|
|
131
|
+
writeFile: () => {},
|
|
132
|
+
getCurrentDirectory: () => path.dirname(filePath),
|
|
133
|
+
getDirectories: () => [],
|
|
134
|
+
fileExists: (fileName) => fileName === filePath,
|
|
135
|
+
readFile: (fileName) => {
|
|
136
|
+
if (fileName === filePath) {
|
|
137
|
+
return content;
|
|
138
|
+
}
|
|
139
|
+
return undefined;
|
|
140
|
+
},
|
|
141
|
+
getCanonicalFileName: (fileName) => fileName,
|
|
142
|
+
useCaseSensitiveFileNames: () => true,
|
|
143
|
+
getNewLine: () => '\n'
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Create program
|
|
147
|
+
const program = ts.createProgram({
|
|
148
|
+
rootNames: [filePath],
|
|
149
|
+
options: this.compilerOptions,
|
|
150
|
+
host
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Get all diagnostics
|
|
154
|
+
const syntactic = program.getSyntacticDiagnostics(sourceFile);
|
|
155
|
+
const semantic = program.getSemanticDiagnostics(sourceFile);
|
|
156
|
+
|
|
157
|
+
for (const diagnostic of [...syntactic, ...semantic]) {
|
|
158
|
+
diagnostics.push(this.formatDiagnostic(diagnostic, sourceFile));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
} catch (error) {
|
|
162
|
+
this.logger?.debug('Semantic analysis encountered error', {
|
|
163
|
+
file: filePath,
|
|
164
|
+
error: error.message
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return diagnostics;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Format TypeScript diagnostic to standard error format
|
|
173
|
+
* @private
|
|
174
|
+
*/
|
|
175
|
+
formatDiagnostic(diagnostic, sourceFile) {
|
|
176
|
+
let line = 0;
|
|
177
|
+
let column = 0;
|
|
178
|
+
|
|
179
|
+
if (diagnostic.file && diagnostic.start !== undefined) {
|
|
180
|
+
const position = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
|
|
181
|
+
line = position.line + 1; // 1-indexed
|
|
182
|
+
column = position.character + 1;
|
|
183
|
+
} else if (sourceFile && diagnostic.start !== undefined) {
|
|
184
|
+
const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);
|
|
185
|
+
line = position.line + 1;
|
|
186
|
+
column = position.character + 1;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
|
|
190
|
+
|
|
191
|
+
// Determine severity
|
|
192
|
+
let severity;
|
|
193
|
+
switch (diagnostic.category) {
|
|
194
|
+
case ts.DiagnosticCategory.Error:
|
|
195
|
+
severity = STATIC_ANALYSIS.SEVERITY.ERROR;
|
|
196
|
+
break;
|
|
197
|
+
case ts.DiagnosticCategory.Warning:
|
|
198
|
+
severity = STATIC_ANALYSIS.SEVERITY.WARNING;
|
|
199
|
+
break;
|
|
200
|
+
case ts.DiagnosticCategory.Message:
|
|
201
|
+
case ts.DiagnosticCategory.Suggestion:
|
|
202
|
+
severity = STATIC_ANALYSIS.SEVERITY.INFO;
|
|
203
|
+
break;
|
|
204
|
+
default:
|
|
205
|
+
severity = STATIC_ANALYSIS.SEVERITY.ERROR;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Determine category based on error code and message
|
|
209
|
+
let category = STATIC_ANALYSIS.CATEGORY.SYNTAX;
|
|
210
|
+
const code = diagnostic.code;
|
|
211
|
+
|
|
212
|
+
// Categorize based on error code ranges
|
|
213
|
+
if (code >= 2000 && code < 3000) {
|
|
214
|
+
category = STATIC_ANALYSIS.CATEGORY.TYPE;
|
|
215
|
+
} else if (code >= 1000 && code < 2000) {
|
|
216
|
+
category = STATIC_ANALYSIS.CATEGORY.SYNTAX;
|
|
217
|
+
} else if (code >= 2300 && code < 2400) {
|
|
218
|
+
category = STATIC_ANALYSIS.CATEGORY.IMPORT;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Check message content for more specific categorization
|
|
222
|
+
const lowerMessage = message.toLowerCase();
|
|
223
|
+
if (lowerMessage.includes('cannot find module') ||
|
|
224
|
+
lowerMessage.includes('import') ||
|
|
225
|
+
lowerMessage.includes('export')) {
|
|
226
|
+
category = STATIC_ANALYSIS.CATEGORY.IMPORT;
|
|
227
|
+
} else if (lowerMessage.includes('type') ||
|
|
228
|
+
lowerMessage.includes('interface') ||
|
|
229
|
+
lowerMessage.includes('class')) {
|
|
230
|
+
category = STATIC_ANALYSIS.CATEGORY.TYPE;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
file: diagnostic.file?.fileName || sourceFile?.fileName || 'unknown',
|
|
235
|
+
line,
|
|
236
|
+
column,
|
|
237
|
+
severity,
|
|
238
|
+
rule: `TS${code}`,
|
|
239
|
+
message,
|
|
240
|
+
category,
|
|
241
|
+
fixable: false, // TypeScript doesn't provide fix information easily
|
|
242
|
+
code: diagnostic.code
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export default TypeScriptAnalyzer;
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analyzes clones and provides refactoring recommendations
|
|
3
|
+
*/
|
|
4
|
+
export class RefactoringAnalyzer {
|
|
5
|
+
constructor(config) {
|
|
6
|
+
this.config = config;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Analyze clones and provide refactoring advice
|
|
11
|
+
* @param {Array} clones - Array of detected clones
|
|
12
|
+
* @returns {Array} Enriched clones with refactoring advice
|
|
13
|
+
*/
|
|
14
|
+
analyzeClones(clones) {
|
|
15
|
+
console.log('Analyzing clones for refactoring opportunities...');
|
|
16
|
+
|
|
17
|
+
return clones.map((clone, index) => {
|
|
18
|
+
const metrics = this.calculateMetrics(clone);
|
|
19
|
+
const advice = this.generateRefactoringAdvice(clone, metrics);
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
id: `clone-${index + 1}`,
|
|
23
|
+
type: clone.type,
|
|
24
|
+
confidence: clone.confidence,
|
|
25
|
+
instances: clone.blocks.map(block => ({
|
|
26
|
+
file: block.file,
|
|
27
|
+
startLine: block.startLine,
|
|
28
|
+
endLine: block.endLine,
|
|
29
|
+
code: this.truncateCode(block.code),
|
|
30
|
+
fullCode: block.code,
|
|
31
|
+
blockType: block.type
|
|
32
|
+
})),
|
|
33
|
+
metrics,
|
|
34
|
+
refactoringAdvice: advice
|
|
35
|
+
};
|
|
36
|
+
}).sort((a, b) => b.metrics.impactScore - a.metrics.impactScore);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Calculate metrics for a clone
|
|
41
|
+
*/
|
|
42
|
+
calculateMetrics(clone) {
|
|
43
|
+
const blocks = clone.blocks;
|
|
44
|
+
const tokenCount = clone.tokenCount;
|
|
45
|
+
const lineCount = this.averageLineCount(blocks);
|
|
46
|
+
const instanceCount = blocks.length;
|
|
47
|
+
|
|
48
|
+
// Calculate impact score (higher = more important to refactor)
|
|
49
|
+
const impactScore = this.calculateImpactScore(
|
|
50
|
+
tokenCount,
|
|
51
|
+
lineCount,
|
|
52
|
+
instanceCount,
|
|
53
|
+
clone.confidence
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
// Calculate duplication overhead
|
|
57
|
+
const duplicatedLines = lineCount * (instanceCount - 1);
|
|
58
|
+
const duplicatedTokens = tokenCount * (instanceCount - 1);
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
tokenCount,
|
|
62
|
+
lineCount,
|
|
63
|
+
instanceCount,
|
|
64
|
+
duplicatedLines,
|
|
65
|
+
duplicatedTokens,
|
|
66
|
+
impactScore: parseFloat(impactScore.toFixed(2)),
|
|
67
|
+
filesCovered: new Set(blocks.map(b => b.file)).size
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Calculate impact score for prioritization
|
|
73
|
+
*/
|
|
74
|
+
calculateImpactScore(tokenCount, lineCount, instanceCount, confidence) {
|
|
75
|
+
// Weighted formula:
|
|
76
|
+
// - Size matters (more tokens = more important)
|
|
77
|
+
// - Instances matter (more copies = more important)
|
|
78
|
+
// - Confidence matters
|
|
79
|
+
// - Line count matters (user visibility)
|
|
80
|
+
|
|
81
|
+
const sizeScore = Math.log10(tokenCount + 1) * 2;
|
|
82
|
+
const instanceScore = Math.log2(instanceCount + 1) * 3;
|
|
83
|
+
const confidenceScore = confidence * 2;
|
|
84
|
+
const lineScore = Math.min(lineCount / 10, 3);
|
|
85
|
+
|
|
86
|
+
return sizeScore + instanceScore + confidenceScore + lineScore;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Generate refactoring advice
|
|
91
|
+
*/
|
|
92
|
+
generateRefactoringAdvice(clone, metrics) {
|
|
93
|
+
const strategy = this.determineRefactoringStrategy(clone, metrics);
|
|
94
|
+
const priority = this.determinePriority(metrics);
|
|
95
|
+
const suggestedName = this.suggestName(clone);
|
|
96
|
+
const reasoning = this.generateReasoning(clone, metrics, strategy);
|
|
97
|
+
const estimatedEffort = this.estimateEffort(metrics, strategy);
|
|
98
|
+
const benefits = this.describeBenefits(metrics);
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
priority,
|
|
102
|
+
strategy,
|
|
103
|
+
suggestedName,
|
|
104
|
+
reasoning,
|
|
105
|
+
estimatedEffort,
|
|
106
|
+
benefits,
|
|
107
|
+
actionableSteps: this.generateActionableSteps(strategy, suggestedName, metrics)
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Determine refactoring strategy
|
|
113
|
+
*/
|
|
114
|
+
determineRefactoringStrategy(clone, metrics) {
|
|
115
|
+
const { tokenCount, lineCount, instanceCount, filesCovered } = metrics;
|
|
116
|
+
const blockTypes = clone.blocks.map(b => b.type);
|
|
117
|
+
|
|
118
|
+
// Check if it's a function/method
|
|
119
|
+
const isFunctionLike = blockTypes.some(type =>
|
|
120
|
+
type.includes('Function') || type.includes('Method')
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
// Check if it's a class
|
|
124
|
+
const isClassLike = blockTypes.some(type =>
|
|
125
|
+
type.includes('Class')
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
// Decision tree
|
|
129
|
+
if (isClassLike && lineCount > 50) {
|
|
130
|
+
return 'extract-module';
|
|
131
|
+
} else if (filesCovered > 2 && tokenCount > 100) {
|
|
132
|
+
return 'extract-module';
|
|
133
|
+
} else if (isFunctionLike || (lineCount >= 10 && lineCount <= 50)) {
|
|
134
|
+
return 'extract-function';
|
|
135
|
+
} else if (lineCount > 50) {
|
|
136
|
+
return 'extract-class';
|
|
137
|
+
} else if (lineCount < 10) {
|
|
138
|
+
return 'extract-constant-or-utility';
|
|
139
|
+
} else {
|
|
140
|
+
return 'extract-function';
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Determine priority level
|
|
146
|
+
*/
|
|
147
|
+
determinePriority(metrics) {
|
|
148
|
+
const { impactScore } = metrics;
|
|
149
|
+
|
|
150
|
+
if (impactScore >= 8) return 'high';
|
|
151
|
+
if (impactScore >= 5) return 'medium';
|
|
152
|
+
return 'low';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Suggest a name based on code analysis
|
|
157
|
+
*/
|
|
158
|
+
suggestName(clone) {
|
|
159
|
+
// Extract common words from the code
|
|
160
|
+
const allCode = clone.blocks.map(b => b.code).join(' ');
|
|
161
|
+
|
|
162
|
+
// Look for common identifiers
|
|
163
|
+
const identifiers = allCode.match(/[a-zA-Z_$][a-zA-Z0-9_$]*/g) || [];
|
|
164
|
+
const frequency = {};
|
|
165
|
+
|
|
166
|
+
identifiers.forEach(id => {
|
|
167
|
+
// Skip common keywords
|
|
168
|
+
if (['const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while'].includes(id)) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
frequency[id] = (frequency[id] || 0) + 1;
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// Find most common meaningful identifier
|
|
175
|
+
const sorted = Object.entries(frequency)
|
|
176
|
+
.sort((a, b) => b[1] - a[1])
|
|
177
|
+
.slice(0, 3);
|
|
178
|
+
|
|
179
|
+
if (sorted.length > 0) {
|
|
180
|
+
// Create a descriptive name from top identifiers
|
|
181
|
+
const topWords = sorted.map(([word]) => word);
|
|
182
|
+
return this.createFunctionName(topWords);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return 'extractedFunction';
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Create a function name from words
|
|
190
|
+
*/
|
|
191
|
+
createFunctionName(words) {
|
|
192
|
+
if (words.length === 0) return 'extractedFunction';
|
|
193
|
+
|
|
194
|
+
// Convert to camelCase
|
|
195
|
+
return words[0] + words.slice(1).map(w =>
|
|
196
|
+
w.charAt(0).toUpperCase() + w.slice(1)
|
|
197
|
+
).join('');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Generate reasoning for refactoring
|
|
202
|
+
*/
|
|
203
|
+
generateReasoning(clone, metrics, strategy) {
|
|
204
|
+
const { instanceCount, duplicatedLines, filesCovered } = metrics;
|
|
205
|
+
|
|
206
|
+
let reasoning = `This ${clone.type} code pattern appears ${instanceCount} times`;
|
|
207
|
+
|
|
208
|
+
if (filesCovered > 1) {
|
|
209
|
+
reasoning += ` across ${filesCovered} different files`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
reasoning += `, resulting in ${duplicatedLines} duplicated lines. `;
|
|
213
|
+
|
|
214
|
+
reasoning += `Refactoring to ${strategy.replace(/-/g, ' ')} would improve maintainability`;
|
|
215
|
+
|
|
216
|
+
if (instanceCount >= 3) {
|
|
217
|
+
reasoning += ', reduce bugs from inconsistent changes';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
reasoning += ', and reduce code size';
|
|
221
|
+
|
|
222
|
+
if (metrics.impactScore >= 8) {
|
|
223
|
+
reasoning += '. This is a high-impact refactoring opportunity';
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return reasoning + '.';
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Estimate effort for refactoring
|
|
231
|
+
*/
|
|
232
|
+
estimateEffort(metrics, strategy) {
|
|
233
|
+
const { lineCount, instanceCount, filesCovered } = metrics;
|
|
234
|
+
|
|
235
|
+
let effortPoints = 0;
|
|
236
|
+
|
|
237
|
+
// Base effort on size
|
|
238
|
+
effortPoints += Math.min(lineCount / 10, 5);
|
|
239
|
+
|
|
240
|
+
// Effort increases with instances
|
|
241
|
+
effortPoints += instanceCount * 0.5;
|
|
242
|
+
|
|
243
|
+
// Effort increases with file spread
|
|
244
|
+
effortPoints += filesCovered * 0.5;
|
|
245
|
+
|
|
246
|
+
// Strategy-specific effort
|
|
247
|
+
if (strategy === 'extract-module') {
|
|
248
|
+
effortPoints += 3;
|
|
249
|
+
} else if (strategy === 'extract-class') {
|
|
250
|
+
effortPoints += 2;
|
|
251
|
+
} else if (strategy === 'extract-function') {
|
|
252
|
+
effortPoints += 1;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (effortPoints <= 3) return 'low';
|
|
256
|
+
if (effortPoints <= 7) return 'medium';
|
|
257
|
+
return 'high';
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Describe benefits of refactoring
|
|
262
|
+
*/
|
|
263
|
+
describeBenefits(metrics) {
|
|
264
|
+
const benefits = [];
|
|
265
|
+
|
|
266
|
+
benefits.push(`Eliminate ${metrics.duplicatedLines} duplicated lines of code`);
|
|
267
|
+
benefits.push(`Improve maintainability by centralizing logic in one place`);
|
|
268
|
+
|
|
269
|
+
if (metrics.instanceCount >= 3) {
|
|
270
|
+
benefits.push(`Reduce risk of inconsistent changes across ${metrics.instanceCount} locations`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (metrics.filesCovered > 2) {
|
|
274
|
+
benefits.push(`Improve code organization across ${metrics.filesCovered} files`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
benefits.push('Make future changes easier and less error-prone');
|
|
278
|
+
|
|
279
|
+
return benefits;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Generate actionable steps
|
|
284
|
+
*/
|
|
285
|
+
generateActionableSteps(strategy, suggestedName, metrics) {
|
|
286
|
+
const steps = [];
|
|
287
|
+
|
|
288
|
+
switch (strategy) {
|
|
289
|
+
case 'extract-function':
|
|
290
|
+
steps.push(`1. Create a new function named '${suggestedName}'`);
|
|
291
|
+
steps.push('2. Move the duplicated logic into this function');
|
|
292
|
+
steps.push('3. Identify parameters needed from the surrounding context');
|
|
293
|
+
steps.push('4. Replace all instances with calls to the new function');
|
|
294
|
+
steps.push('5. Test to ensure behavior is preserved');
|
|
295
|
+
break;
|
|
296
|
+
|
|
297
|
+
case 'extract-class':
|
|
298
|
+
steps.push(`1. Create a new class to encapsulate this functionality`);
|
|
299
|
+
steps.push('2. Move related methods and properties into the class');
|
|
300
|
+
steps.push('3. Update all instances to use the new class');
|
|
301
|
+
steps.push('4. Consider dependency injection for better testability');
|
|
302
|
+
break;
|
|
303
|
+
|
|
304
|
+
case 'extract-module':
|
|
305
|
+
steps.push(`1. Create a new module/file for this shared functionality`);
|
|
306
|
+
steps.push('2. Move the duplicated code into the new module');
|
|
307
|
+
steps.push('3. Export the necessary functions/classes');
|
|
308
|
+
steps.push('4. Update all files to import from the new module');
|
|
309
|
+
steps.push('5. Update any build configurations if needed');
|
|
310
|
+
break;
|
|
311
|
+
|
|
312
|
+
default:
|
|
313
|
+
steps.push(`1. Extract the duplicated code using ${strategy.replace(/-/g, ' ')}`);
|
|
314
|
+
steps.push('2. Replace all instances with the extracted version');
|
|
315
|
+
steps.push('3. Test thoroughly');
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
return steps;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Truncate code for display
|
|
323
|
+
*/
|
|
324
|
+
truncateCode(code, maxLines = 10) {
|
|
325
|
+
const lines = code.split('\n');
|
|
326
|
+
|
|
327
|
+
if (lines.length <= maxLines) {
|
|
328
|
+
return code;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return lines.slice(0, maxLines).join('\n') + '\n... (truncated)';
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Calculate average line count
|
|
336
|
+
*/
|
|
337
|
+
averageLineCount(blocks) {
|
|
338
|
+
const totalLines = blocks.reduce((sum, block) =>
|
|
339
|
+
sum + (block.endLine - block.startLine + 1), 0
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
return Math.round(totalLines / blocks.length);
|
|
343
|
+
}
|
|
344
|
+
}
|