@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,1778 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StaticAnalysisTool - Static code analysis for finding errors without execution
|
|
3
|
+
*
|
|
4
|
+
* Purpose:
|
|
5
|
+
* - Analyze code files for syntax, type, and import errors
|
|
6
|
+
* - Detect programming languages and frameworks
|
|
7
|
+
* - Provide actionable error references with line numbers
|
|
8
|
+
* - Support single file, multiple files, and project-wide analysis
|
|
9
|
+
* - Use official language parsers for accurate results
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { BaseTool } from './baseTool.js';
|
|
13
|
+
import TagParser from '../utilities/tagParser.js';
|
|
14
|
+
import DirectoryAccessManager from '../utilities/directoryAccessManager.js';
|
|
15
|
+
import fs from 'fs/promises';
|
|
16
|
+
import path from 'path';
|
|
17
|
+
import crypto from 'crypto';
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
STATIC_ANALYSIS,
|
|
21
|
+
TOOL_STATUS,
|
|
22
|
+
SYSTEM_DEFAULTS
|
|
23
|
+
} from '../utilities/constants.js';
|
|
24
|
+
|
|
25
|
+
class StaticAnalysisTool extends BaseTool {
|
|
26
|
+
constructor(config = {}, logger = null) {
|
|
27
|
+
super(config, logger);
|
|
28
|
+
|
|
29
|
+
// Tool metadata
|
|
30
|
+
this.requiresProject = true;
|
|
31
|
+
this.isAsync = false;
|
|
32
|
+
this.timeout = config.timeout || STATIC_ANALYSIS.ANALYSIS_TIMEOUT;
|
|
33
|
+
this.maxConcurrentOperations = config.maxConcurrentOperations || 1;
|
|
34
|
+
|
|
35
|
+
// Analysis settings
|
|
36
|
+
this.maxFileSize = config.maxFileSize || STATIC_ANALYSIS.MAX_FILE_SIZE_FOR_ANALYSIS;
|
|
37
|
+
this.maxFilesPerBatch = config.maxFilesPerBatch || STATIC_ANALYSIS.MAX_FILES_PER_BATCH;
|
|
38
|
+
this.enableCache = config.enableCache !== false && STATIC_ANALYSIS.ENABLE_CACHE;
|
|
39
|
+
|
|
40
|
+
// Cache for analysis results
|
|
41
|
+
this.analysisCache = new Map();
|
|
42
|
+
this.cacheExpiry = STATIC_ANALYSIS.CACHE_DURATION;
|
|
43
|
+
|
|
44
|
+
// Performance optimization settings
|
|
45
|
+
this.parallelAnalysis = config.parallelAnalysis !== false;
|
|
46
|
+
this.maxParallelFiles = config.maxParallelFiles || 10;
|
|
47
|
+
this.useContentHash = config.useContentHash !== false;
|
|
48
|
+
|
|
49
|
+
// Performance metrics
|
|
50
|
+
this.metrics = {
|
|
51
|
+
totalAnalyses: 0,
|
|
52
|
+
cacheHits: 0,
|
|
53
|
+
cacheMisses: 0,
|
|
54
|
+
totalAnalysisTime: 0,
|
|
55
|
+
filesAnalyzed: 0,
|
|
56
|
+
parallelBatches: 0
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Directory access manager
|
|
60
|
+
this.directoryAccessManager = new DirectoryAccessManager(config, logger);
|
|
61
|
+
|
|
62
|
+
// Analyzers will be initialized lazily when needed
|
|
63
|
+
this.analyzers = {
|
|
64
|
+
javascript: null,
|
|
65
|
+
typescript: null,
|
|
66
|
+
python: null,
|
|
67
|
+
css: null,
|
|
68
|
+
scss: null,
|
|
69
|
+
less: null,
|
|
70
|
+
eslint: null,
|
|
71
|
+
security: null,
|
|
72
|
+
config: null
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// Formatters will be initialized lazily when needed
|
|
76
|
+
this.formatters = {
|
|
77
|
+
prettier: null
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Get tool description for LLM consumption
|
|
83
|
+
* @returns {string} Tool description
|
|
84
|
+
*/
|
|
85
|
+
getDescription() {
|
|
86
|
+
return `
|
|
87
|
+
Static Code Analysis Tool: Analyze code files for errors without execution
|
|
88
|
+
|
|
89
|
+
This tool performs static analysis on code files to find syntax errors, type errors, import issues, and other problems without running the code. It uses official language parsers for accurate results.
|
|
90
|
+
|
|
91
|
+
SUPPORTED LANGUAGES:
|
|
92
|
+
- JavaScript (.js, .jsx, .mjs, .cjs)
|
|
93
|
+
- TypeScript (.ts, .tsx)
|
|
94
|
+
- Python (.py)
|
|
95
|
+
- CSS (.css)
|
|
96
|
+
- SCSS (.scss, .sass)
|
|
97
|
+
- LESS (.less)
|
|
98
|
+
|
|
99
|
+
USAGE - XML FORMAT:
|
|
100
|
+
|
|
101
|
+
Single File Analysis:
|
|
102
|
+
[tool id="staticanalysis"]
|
|
103
|
+
<analyze file-path="src/index.js" />
|
|
104
|
+
[/tool]
|
|
105
|
+
|
|
106
|
+
Multiple Files Analysis:
|
|
107
|
+
[tool id="staticanalysis"]
|
|
108
|
+
<analyze file-path="src/index.js" />
|
|
109
|
+
<analyze file-path="src/utils.js" />
|
|
110
|
+
<analyze file-path="src/components/Button.jsx" />
|
|
111
|
+
[/tool]
|
|
112
|
+
|
|
113
|
+
Project-Wide Analysis:
|
|
114
|
+
[tool id="staticanalysis"]
|
|
115
|
+
<analyze-project directory="src" pattern="**/*.js" />
|
|
116
|
+
[/tool]
|
|
117
|
+
|
|
118
|
+
Auto-Fix Code Issues:
|
|
119
|
+
[tool id="staticanalysis"]
|
|
120
|
+
<fix file-path="src/app.js" />
|
|
121
|
+
[/tool]
|
|
122
|
+
|
|
123
|
+
Format Code:
|
|
124
|
+
[tool id="staticanalysis"]
|
|
125
|
+
<format file-path="src/app.js" />
|
|
126
|
+
[/tool]
|
|
127
|
+
|
|
128
|
+
USAGE - JSON FORMAT:
|
|
129
|
+
|
|
130
|
+
\`\`\`json
|
|
131
|
+
{
|
|
132
|
+
"toolId": "staticanalysis",
|
|
133
|
+
"actions": [
|
|
134
|
+
{
|
|
135
|
+
"type": "analyze",
|
|
136
|
+
"filePath": "src/index.js"
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"type": "analyze-project",
|
|
140
|
+
"directory": "src",
|
|
141
|
+
"pattern": "**/*.{js,ts,py}"
|
|
142
|
+
}
|
|
143
|
+
]
|
|
144
|
+
}
|
|
145
|
+
\`\`\`
|
|
146
|
+
|
|
147
|
+
PARAMETERS:
|
|
148
|
+
- file-path: Path to file to analyze (for single file)
|
|
149
|
+
- directory: Directory to analyze (for project-wide)
|
|
150
|
+
- pattern: Glob pattern for files to include (optional, defaults to language-specific patterns)
|
|
151
|
+
- include-warnings: Include warnings in results (true/false, default: true)
|
|
152
|
+
- max-errors: Maximum number of errors to return (default: all)
|
|
153
|
+
|
|
154
|
+
OUTPUT FORMAT:
|
|
155
|
+
Returns structured error information:
|
|
156
|
+
- file: File path
|
|
157
|
+
- line: Line number
|
|
158
|
+
- column: Column number
|
|
159
|
+
- severity: critical | error | warning | info
|
|
160
|
+
- rule: Rule identifier
|
|
161
|
+
- message: Human-readable description
|
|
162
|
+
- category: syntax | type | import | style | security | performance | best_practice
|
|
163
|
+
- fixable: Whether error can be auto-fixed
|
|
164
|
+
- suggestion: Fix suggestion (if applicable)
|
|
165
|
+
- remediation: Security remediation advice (for security issues)
|
|
166
|
+
|
|
167
|
+
DETECTION:
|
|
168
|
+
- Language: Automatically detected from file extension
|
|
169
|
+
- Framework: Detected from package.json, requirements.txt, etc.
|
|
170
|
+
- Context: Project structure analyzed for better accuracy
|
|
171
|
+
|
|
172
|
+
EXAMPLES:
|
|
173
|
+
|
|
174
|
+
Find all errors in a JavaScript file:
|
|
175
|
+
[tool id="staticanalysis"]
|
|
176
|
+
<analyze file-path="src/app.js" />
|
|
177
|
+
[/tool]
|
|
178
|
+
|
|
179
|
+
Analyze TypeScript with type checking:
|
|
180
|
+
[tool id="staticanalysis"]
|
|
181
|
+
<analyze file-path="src/types.ts" />
|
|
182
|
+
[/tool]
|
|
183
|
+
|
|
184
|
+
Check all Python files in a directory:
|
|
185
|
+
[tool id="staticanalysis"]
|
|
186
|
+
<analyze-project directory="backend" pattern="**/*.py" />
|
|
187
|
+
[/tool]
|
|
188
|
+
|
|
189
|
+
LIMITATIONS:
|
|
190
|
+
- File size limit: ${Math.round(this.maxFileSize / 1024 / 1024)}MB per file
|
|
191
|
+
- Batch limit: ${this.maxFilesPerBatch} files per operation
|
|
192
|
+
- Analysis timeout: ${this.timeout / 1000} seconds
|
|
193
|
+
- Only supports languages with built-in analyzers
|
|
194
|
+
`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Parse parameters from tool command content
|
|
199
|
+
* @param {string} content - Raw tool command content
|
|
200
|
+
* @returns {Object} Parsed parameters
|
|
201
|
+
*/
|
|
202
|
+
parseParameters(content) {
|
|
203
|
+
try {
|
|
204
|
+
const params = {};
|
|
205
|
+
const actions = [];
|
|
206
|
+
|
|
207
|
+
this.logger?.debug('StaticAnalysis tool parsing parameters', {
|
|
208
|
+
contentLength: content.length,
|
|
209
|
+
contentPreview: content.substring(0, 200)
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
// Extract self-closing <analyze> tags
|
|
213
|
+
// Pattern: <analyze ...attributes... />
|
|
214
|
+
// We need to capture everything between 'analyze' and '/>' which includes file paths with /
|
|
215
|
+
const analyzePattern = /<analyze\s+(.+?)\/>/g;
|
|
216
|
+
let match;
|
|
217
|
+
|
|
218
|
+
while ((match = analyzePattern.exec(content)) !== null) {
|
|
219
|
+
const attributeString = match[1].trim();
|
|
220
|
+
const parser = new TagParser();
|
|
221
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
222
|
+
|
|
223
|
+
const action = {
|
|
224
|
+
type: 'analyze',
|
|
225
|
+
...attributes
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
// Normalize attribute names
|
|
229
|
+
if (action['file-path']) {
|
|
230
|
+
action.filePath = action['file-path'];
|
|
231
|
+
delete action['file-path'];
|
|
232
|
+
}
|
|
233
|
+
if (action['include-warnings']) {
|
|
234
|
+
action.includeWarnings = action['include-warnings'] === 'true';
|
|
235
|
+
delete action['include-warnings'];
|
|
236
|
+
}
|
|
237
|
+
if (action['max-errors']) {
|
|
238
|
+
action.maxErrors = parseInt(action['max-errors'], 10);
|
|
239
|
+
delete action['max-errors'];
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
actions.push(action);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Extract self-closing <analyze-project> tags
|
|
246
|
+
const projectPattern = /<analyze-project\s+(.+?)\/>/g;
|
|
247
|
+
|
|
248
|
+
while ((match = projectPattern.exec(content)) !== null) {
|
|
249
|
+
const attributeString = match[1].trim();
|
|
250
|
+
const parser = new TagParser();
|
|
251
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
252
|
+
|
|
253
|
+
const action = {
|
|
254
|
+
type: 'analyze-project',
|
|
255
|
+
...attributes
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// Normalize attribute names
|
|
259
|
+
if (action['include-warnings']) {
|
|
260
|
+
action.includeWarnings = action['include-warnings'] === 'true';
|
|
261
|
+
delete action['include-warnings'];
|
|
262
|
+
}
|
|
263
|
+
if (action['max-errors']) {
|
|
264
|
+
action.maxErrors = parseInt(action['max-errors'], 10);
|
|
265
|
+
delete action['max-errors'];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
actions.push(action);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Extract self-closing <fix> tags
|
|
272
|
+
const fixPattern = /<fix\s+(.+?)\/>/g;
|
|
273
|
+
|
|
274
|
+
while ((match = fixPattern.exec(content)) !== null) {
|
|
275
|
+
const attributeString = match[1].trim();
|
|
276
|
+
const parser = new TagParser();
|
|
277
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
278
|
+
|
|
279
|
+
const action = {
|
|
280
|
+
type: 'fix',
|
|
281
|
+
...attributes
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
// Normalize attribute names
|
|
285
|
+
if (action['file-path']) {
|
|
286
|
+
action.filePath = action['file-path'];
|
|
287
|
+
delete action['file-path'];
|
|
288
|
+
}
|
|
289
|
+
if (action['write-file']) {
|
|
290
|
+
action.writeFile = action['write-file'] === 'true';
|
|
291
|
+
delete action['write-file'];
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
actions.push(action);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Extract self-closing <format> tags
|
|
298
|
+
const formatPattern = /<format\s+(.+?)\/>/g;
|
|
299
|
+
|
|
300
|
+
while ((match = formatPattern.exec(content)) !== null) {
|
|
301
|
+
const attributeString = match[1].trim();
|
|
302
|
+
const parser = new TagParser();
|
|
303
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
304
|
+
|
|
305
|
+
const action = {
|
|
306
|
+
type: 'format',
|
|
307
|
+
...attributes
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
// Normalize attribute names
|
|
311
|
+
if (action['file-path']) {
|
|
312
|
+
action.filePath = action['file-path'];
|
|
313
|
+
delete action['file-path'];
|
|
314
|
+
}
|
|
315
|
+
if (action['write-file']) {
|
|
316
|
+
action.writeFile = action['write-file'] === 'true';
|
|
317
|
+
delete action['write-file'];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
actions.push(action);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Extract self-closing <security-scan> tags
|
|
324
|
+
const securityScanPattern = /<security-scan\s+(.+?)\/>/g;
|
|
325
|
+
|
|
326
|
+
while ((match = securityScanPattern.exec(content)) !== null) {
|
|
327
|
+
const attributeString = match[1].trim();
|
|
328
|
+
const parser = new TagParser();
|
|
329
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
330
|
+
|
|
331
|
+
const action = {
|
|
332
|
+
type: 'security-scan',
|
|
333
|
+
...attributes
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// Normalize attribute names
|
|
337
|
+
if (action['file-path']) {
|
|
338
|
+
action.filePath = action['file-path'];
|
|
339
|
+
delete action['file-path'];
|
|
340
|
+
}
|
|
341
|
+
if (action['skip-test-files']) {
|
|
342
|
+
action.skipTestFiles = action['skip-test-files'] === 'true';
|
|
343
|
+
delete action['skip-test-files'];
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
actions.push(action);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Extract self-closing <security-scan-project> tags
|
|
350
|
+
const securityScanProjectPattern = /<security-scan-project\s+(.+?)\/>/g;
|
|
351
|
+
|
|
352
|
+
while ((match = securityScanProjectPattern.exec(content)) !== null) {
|
|
353
|
+
const attributeString = match[1].trim();
|
|
354
|
+
const parser = new TagParser();
|
|
355
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
356
|
+
|
|
357
|
+
const action = {
|
|
358
|
+
type: 'security-scan-project',
|
|
359
|
+
...attributes
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
// Normalize attribute names
|
|
363
|
+
if (action['skip-test-files']) {
|
|
364
|
+
action.skipTestFiles = action['skip-test-files'] === 'true';
|
|
365
|
+
delete action['skip-test-files'];
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
actions.push(action);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Extract self-closing <validate-config> tags
|
|
372
|
+
const validateConfigPattern = /<validate-config\s+(.+?)\/>/g;
|
|
373
|
+
|
|
374
|
+
while ((match = validateConfigPattern.exec(content)) !== null) {
|
|
375
|
+
const attributeString = match[1].trim();
|
|
376
|
+
const parser = new TagParser();
|
|
377
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
378
|
+
|
|
379
|
+
const action = {
|
|
380
|
+
type: 'validate-config',
|
|
381
|
+
...attributes
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// Normalize attribute names
|
|
385
|
+
if (action['file-path']) {
|
|
386
|
+
action.filePath = action['file-path'];
|
|
387
|
+
delete action['file-path'];
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
actions.push(action);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Extract self-closing <validate-config-directory> tags
|
|
394
|
+
const validateConfigDirPattern = /<validate-config-directory\s+(.+?)\/>/g;
|
|
395
|
+
|
|
396
|
+
while ((match = validateConfigDirPattern.exec(content)) !== null) {
|
|
397
|
+
const attributeString = match[1].trim();
|
|
398
|
+
const parser = new TagParser();
|
|
399
|
+
const attributes = parser.parseAttributes(attributeString);
|
|
400
|
+
|
|
401
|
+
const action = {
|
|
402
|
+
type: 'validate-config-directory',
|
|
403
|
+
...attributes
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
// Normalize attribute names (none specific yet)
|
|
407
|
+
|
|
408
|
+
actions.push(action);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
params.actions = actions;
|
|
412
|
+
params.rawContent = content.trim();
|
|
413
|
+
|
|
414
|
+
this.logger?.debug('Parsed StaticAnalysis tool parameters', {
|
|
415
|
+
totalActions: actions.length,
|
|
416
|
+
actionTypes: actions.map(a => a.type)
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
return params;
|
|
420
|
+
|
|
421
|
+
} catch (error) {
|
|
422
|
+
throw new Error(`Failed to parse static analysis parameters: ${error.message}`);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Get required parameters
|
|
428
|
+
* @returns {Array<string>} Array of required parameter names
|
|
429
|
+
*/
|
|
430
|
+
getRequiredParameters() {
|
|
431
|
+
return ['actions'];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Custom parameter validation
|
|
436
|
+
* @param {Object} params - Parameters to validate
|
|
437
|
+
* @returns {Object} Validation result
|
|
438
|
+
*/
|
|
439
|
+
customValidateParameters(params) {
|
|
440
|
+
const errors = [];
|
|
441
|
+
|
|
442
|
+
if (!params.actions || !Array.isArray(params.actions) || params.actions.length === 0) {
|
|
443
|
+
errors.push('At least one action is required');
|
|
444
|
+
} else {
|
|
445
|
+
// Validate each action
|
|
446
|
+
for (const [index, action] of params.actions.entries()) {
|
|
447
|
+
if (!action.type) {
|
|
448
|
+
errors.push(`Action ${index + 1}: type is required`);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
switch (action.type) {
|
|
453
|
+
case 'analyze':
|
|
454
|
+
if (!action.filePath) {
|
|
455
|
+
errors.push(`Action ${index + 1}: file-path is required for analyze`);
|
|
456
|
+
}
|
|
457
|
+
break;
|
|
458
|
+
|
|
459
|
+
case 'analyze-project':
|
|
460
|
+
if (!action.directory) {
|
|
461
|
+
errors.push(`Action ${index + 1}: directory is required for analyze-project`);
|
|
462
|
+
}
|
|
463
|
+
break;
|
|
464
|
+
|
|
465
|
+
case 'fix':
|
|
466
|
+
if (!action.filePath) {
|
|
467
|
+
errors.push(`Action ${index + 1}: file-path is required for fix`);
|
|
468
|
+
}
|
|
469
|
+
break;
|
|
470
|
+
|
|
471
|
+
case 'format':
|
|
472
|
+
if (!action.filePath) {
|
|
473
|
+
errors.push(`Action ${index + 1}: file-path is required for format`);
|
|
474
|
+
}
|
|
475
|
+
break;
|
|
476
|
+
|
|
477
|
+
case 'security-scan':
|
|
478
|
+
if (!action.filePath) {
|
|
479
|
+
errors.push(`Action ${index + 1}: file-path is required for security-scan`);
|
|
480
|
+
}
|
|
481
|
+
break;
|
|
482
|
+
|
|
483
|
+
case 'security-scan-project':
|
|
484
|
+
if (!action.directory) {
|
|
485
|
+
errors.push(`Action ${index + 1}: directory is required for security-scan-project`);
|
|
486
|
+
}
|
|
487
|
+
break;
|
|
488
|
+
|
|
489
|
+
case 'validate-config':
|
|
490
|
+
if (!action.filePath) {
|
|
491
|
+
errors.push(`Action ${index + 1}: file-path is required for validate-config`);
|
|
492
|
+
}
|
|
493
|
+
break;
|
|
494
|
+
|
|
495
|
+
case 'validate-config-directory':
|
|
496
|
+
if (!action.directory) {
|
|
497
|
+
errors.push(`Action ${index + 1}: directory is required for validate-config-directory`);
|
|
498
|
+
}
|
|
499
|
+
break;
|
|
500
|
+
|
|
501
|
+
default:
|
|
502
|
+
errors.push(`Action ${index + 1}: unknown action type: ${action.type}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Check batch size limit
|
|
507
|
+
if (params.actions.length > this.maxFilesPerBatch) {
|
|
508
|
+
errors.push(`Too many actions: ${params.actions.length} (max ${this.maxFilesPerBatch})`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return {
|
|
513
|
+
valid: errors.length === 0,
|
|
514
|
+
errors
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Execute tool with parsed parameters
|
|
520
|
+
* @param {Object} params - Parsed parameters
|
|
521
|
+
* @param {Object} context - Execution context
|
|
522
|
+
* @returns {Promise<Object>} Execution result
|
|
523
|
+
*/
|
|
524
|
+
async execute(params, context) {
|
|
525
|
+
const { actions } = params;
|
|
526
|
+
const { projectDir, agentId, directoryAccess } = context;
|
|
527
|
+
|
|
528
|
+
// Get directory access configuration
|
|
529
|
+
const accessConfig = directoryAccess ||
|
|
530
|
+
this.directoryAccessManager.createDirectoryAccess({
|
|
531
|
+
workingDirectory: projectDir || process.cwd(),
|
|
532
|
+
writeEnabledDirectories: [projectDir || process.cwd()],
|
|
533
|
+
restrictToProject: true
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
const workingDir = this.directoryAccessManager.getWorkingDirectory(accessConfig);
|
|
537
|
+
const results = {
|
|
538
|
+
files: [],
|
|
539
|
+
summary: {
|
|
540
|
+
totalFiles: 0,
|
|
541
|
+
totalErrors: 0,
|
|
542
|
+
totalWarnings: 0,
|
|
543
|
+
totalInfo: 0,
|
|
544
|
+
errorsByCategory: {},
|
|
545
|
+
filesByLanguage: {},
|
|
546
|
+
filesWithErrors: 0
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
for (const action of actions) {
|
|
551
|
+
try {
|
|
552
|
+
let actionResult;
|
|
553
|
+
|
|
554
|
+
switch (action.type) {
|
|
555
|
+
case 'analyze':
|
|
556
|
+
actionResult = await this.analyzeFile(action.filePath, workingDir, accessConfig, action);
|
|
557
|
+
if (actionResult) {
|
|
558
|
+
results.files.push(actionResult);
|
|
559
|
+
this.updateSummary(results.summary, actionResult);
|
|
560
|
+
}
|
|
561
|
+
break;
|
|
562
|
+
|
|
563
|
+
case 'analyze-project':
|
|
564
|
+
const projectFiles = await this.analyzeProject(action.directory, action.pattern, workingDir, accessConfig, action);
|
|
565
|
+
results.files.push(...projectFiles);
|
|
566
|
+
for (const fileResult of projectFiles) {
|
|
567
|
+
this.updateSummary(results.summary, fileResult);
|
|
568
|
+
}
|
|
569
|
+
break;
|
|
570
|
+
|
|
571
|
+
case 'fix':
|
|
572
|
+
actionResult = await this.fixFile(action.filePath, workingDir, accessConfig, action);
|
|
573
|
+
if (actionResult) {
|
|
574
|
+
results.files.push(actionResult);
|
|
575
|
+
}
|
|
576
|
+
break;
|
|
577
|
+
|
|
578
|
+
case 'format':
|
|
579
|
+
actionResult = await this.formatFile(action.filePath, workingDir, accessConfig, action);
|
|
580
|
+
if (actionResult) {
|
|
581
|
+
results.files.push(actionResult);
|
|
582
|
+
}
|
|
583
|
+
break;
|
|
584
|
+
|
|
585
|
+
case 'security-scan':
|
|
586
|
+
actionResult = await this.securityScanFile(action.filePath, workingDir, accessConfig, action);
|
|
587
|
+
if (actionResult) {
|
|
588
|
+
results.files.push(actionResult);
|
|
589
|
+
this.updateSummary(results.summary, actionResult);
|
|
590
|
+
}
|
|
591
|
+
break;
|
|
592
|
+
|
|
593
|
+
case 'security-scan-project':
|
|
594
|
+
const securityProjectFiles = await this.securityScanProject(action.directory, action.pattern, workingDir, accessConfig, action);
|
|
595
|
+
results.files.push(...securityProjectFiles);
|
|
596
|
+
for (const fileResult of securityProjectFiles) {
|
|
597
|
+
this.updateSummary(results.summary, fileResult);
|
|
598
|
+
}
|
|
599
|
+
break;
|
|
600
|
+
|
|
601
|
+
case 'validate-config':
|
|
602
|
+
actionResult = await this.validateConfigFile(action.filePath, workingDir, accessConfig, action);
|
|
603
|
+
if (actionResult) {
|
|
604
|
+
results.files.push(actionResult);
|
|
605
|
+
this.updateSummary(results.summary, actionResult);
|
|
606
|
+
}
|
|
607
|
+
break;
|
|
608
|
+
|
|
609
|
+
case 'validate-config-directory':
|
|
610
|
+
const configFiles = await this.validateConfigDirectory(action.directory, workingDir, accessConfig, action);
|
|
611
|
+
results.files.push(...configFiles);
|
|
612
|
+
for (const fileResult of configFiles) {
|
|
613
|
+
this.updateSummary(results.summary, fileResult);
|
|
614
|
+
}
|
|
615
|
+
break;
|
|
616
|
+
|
|
617
|
+
default:
|
|
618
|
+
throw new Error(`Unknown action type: ${action.type}`);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
} catch (error) {
|
|
622
|
+
this.logger?.error('Static analysis action failed', {
|
|
623
|
+
action: action.type,
|
|
624
|
+
error: error.message
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
results.files.push({
|
|
628
|
+
file: action.filePath || action.directory,
|
|
629
|
+
error: error.message,
|
|
630
|
+
success: false
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
return {
|
|
636
|
+
success: true,
|
|
637
|
+
results,
|
|
638
|
+
toolUsed: 'staticanalysis',
|
|
639
|
+
performance: this.getPerformanceMetrics()
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Analyze a single file
|
|
645
|
+
* @private
|
|
646
|
+
*/
|
|
647
|
+
async analyzeFile(filePath, workingDir, accessConfig, options = {}) {
|
|
648
|
+
const fullPath = path.isAbsolute(filePath)
|
|
649
|
+
? path.normalize(filePath)
|
|
650
|
+
: path.resolve(workingDir, filePath);
|
|
651
|
+
|
|
652
|
+
// Validate read access
|
|
653
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullPath, accessConfig);
|
|
654
|
+
if (!accessResult.allowed) {
|
|
655
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Check file exists
|
|
659
|
+
try {
|
|
660
|
+
const stats = await fs.stat(fullPath);
|
|
661
|
+
|
|
662
|
+
if (stats.size > this.maxFileSize) {
|
|
663
|
+
throw new Error(`File too large: ${stats.size} bytes (max ${this.maxFileSize})`);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Detect language from file extension
|
|
667
|
+
const language = this.detectLanguage(fullPath);
|
|
668
|
+
|
|
669
|
+
if (!language) {
|
|
670
|
+
return {
|
|
671
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
672
|
+
fullPath,
|
|
673
|
+
language: 'unknown',
|
|
674
|
+
errors: [],
|
|
675
|
+
warnings: [],
|
|
676
|
+
info: [],
|
|
677
|
+
skipped: true,
|
|
678
|
+
skipReason: 'Unsupported file type'
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Read file content
|
|
683
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
684
|
+
|
|
685
|
+
// Check cache (use content hash for more accurate caching)
|
|
686
|
+
const contentHash = this.useContentHash ? this.computeContentHash(content) : null;
|
|
687
|
+
const cacheKey = this.useContentHash
|
|
688
|
+
? `${fullPath}:${contentHash}`
|
|
689
|
+
: `${fullPath}:${stats.mtime.getTime()}`;
|
|
690
|
+
|
|
691
|
+
if (this.enableCache && this.analysisCache.has(cacheKey)) {
|
|
692
|
+
const cached = this.analysisCache.get(cacheKey);
|
|
693
|
+
if (Date.now() - cached.timestamp < this.cacheExpiry) {
|
|
694
|
+
this.logger?.debug('Using cached analysis result', { file: fullPath });
|
|
695
|
+
this.metrics.cacheHits++;
|
|
696
|
+
this.metrics.totalAnalyses++;
|
|
697
|
+
return cached.result;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
this.metrics.cacheMisses++;
|
|
702
|
+
this.metrics.totalAnalyses++;
|
|
703
|
+
|
|
704
|
+
// Get analyzer for language
|
|
705
|
+
const analyzer = await this.getAnalyzer(language);
|
|
706
|
+
|
|
707
|
+
if (!analyzer) {
|
|
708
|
+
return {
|
|
709
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
710
|
+
fullPath,
|
|
711
|
+
language,
|
|
712
|
+
errors: [],
|
|
713
|
+
warnings: [],
|
|
714
|
+
info: [],
|
|
715
|
+
skipped: true,
|
|
716
|
+
skipReason: `No analyzer available for ${language}`
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// Perform analysis with timing
|
|
721
|
+
const analysisStart = Date.now();
|
|
722
|
+
const diagnostics = await analyzer.analyze(fullPath, content, {
|
|
723
|
+
workingDir,
|
|
724
|
+
accessConfig,
|
|
725
|
+
framework: await this.detectFramework(workingDir, language)
|
|
726
|
+
});
|
|
727
|
+
const analysisTime = Date.now() - analysisStart;
|
|
728
|
+
|
|
729
|
+
this.metrics.totalAnalysisTime += analysisTime;
|
|
730
|
+
this.metrics.filesAnalyzed++;
|
|
731
|
+
|
|
732
|
+
// Format results
|
|
733
|
+
const result = {
|
|
734
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
735
|
+
fullPath,
|
|
736
|
+
language,
|
|
737
|
+
framework: await this.detectFramework(workingDir, language),
|
|
738
|
+
errors: diagnostics.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.ERROR),
|
|
739
|
+
warnings: options.includeWarnings !== false
|
|
740
|
+
? diagnostics.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.WARNING)
|
|
741
|
+
: [],
|
|
742
|
+
info: diagnostics.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.INFO),
|
|
743
|
+
totalIssues: diagnostics.length,
|
|
744
|
+
analyzed: true,
|
|
745
|
+
timestamp: new Date().toISOString()
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
// Apply max errors limit
|
|
749
|
+
if (options.maxErrors && result.errors.length > options.maxErrors) {
|
|
750
|
+
result.errors = result.errors.slice(0, options.maxErrors);
|
|
751
|
+
result.truncated = true;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Cache result
|
|
755
|
+
if (this.enableCache) {
|
|
756
|
+
this.analysisCache.set(cacheKey, {
|
|
757
|
+
result,
|
|
758
|
+
timestamp: Date.now()
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
return result;
|
|
763
|
+
|
|
764
|
+
} catch (error) {
|
|
765
|
+
throw new Error(`Failed to analyze ${filePath}: ${error.message}`);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Analyze project directory
|
|
771
|
+
* @private
|
|
772
|
+
*/
|
|
773
|
+
async analyzeProject(directory, pattern, workingDir, accessConfig, options = {}) {
|
|
774
|
+
const fullDir = path.isAbsolute(directory)
|
|
775
|
+
? path.normalize(directory)
|
|
776
|
+
: path.resolve(workingDir, directory);
|
|
777
|
+
|
|
778
|
+
// Validate read access
|
|
779
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullDir, accessConfig);
|
|
780
|
+
if (!accessResult.allowed) {
|
|
781
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// Find all matching files
|
|
785
|
+
const files = await this.findFiles(fullDir, pattern);
|
|
786
|
+
|
|
787
|
+
if (files.length > this.maxFilesPerBatch) {
|
|
788
|
+
throw new Error(`Too many files: ${files.length} (max ${this.maxFilesPerBatch})`);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// Analyze files (parallel or sequential based on configuration)
|
|
792
|
+
const results = [];
|
|
793
|
+
|
|
794
|
+
if (this.parallelAnalysis && files.length > 1) {
|
|
795
|
+
// Parallel analysis in batches
|
|
796
|
+
this.logger?.debug('Using parallel analysis', {
|
|
797
|
+
totalFiles: files.length,
|
|
798
|
+
batchSize: this.maxParallelFiles
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
for (let i = 0; i < files.length; i += this.maxParallelFiles) {
|
|
802
|
+
const batch = files.slice(i, i + this.maxParallelFiles);
|
|
803
|
+
this.metrics.parallelBatches++;
|
|
804
|
+
|
|
805
|
+
// Report progress
|
|
806
|
+
const progress = {
|
|
807
|
+
completed: i,
|
|
808
|
+
total: files.length,
|
|
809
|
+
percentage: Math.round((i / files.length) * 100)
|
|
810
|
+
};
|
|
811
|
+
|
|
812
|
+
if (options.onProgress) {
|
|
813
|
+
options.onProgress(progress);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
this.logger?.debug('Analyzing batch', {
|
|
817
|
+
batch: Math.floor(i / this.maxParallelFiles) + 1,
|
|
818
|
+
filesInBatch: batch.length,
|
|
819
|
+
progress: `${progress.completed}/${progress.total}`
|
|
820
|
+
});
|
|
821
|
+
|
|
822
|
+
// Analyze batch in parallel
|
|
823
|
+
const batchPromises = batch.map(async (file) => {
|
|
824
|
+
try {
|
|
825
|
+
const result = await this.analyzeFile(file, workingDir, accessConfig, options);
|
|
826
|
+
return result;
|
|
827
|
+
} catch (error) {
|
|
828
|
+
this.logger?.warn('Failed to analyze file in project', {
|
|
829
|
+
file,
|
|
830
|
+
error: error.message
|
|
831
|
+
});
|
|
832
|
+
|
|
833
|
+
return {
|
|
834
|
+
file: this.directoryAccessManager.createRelativePath(file, accessConfig),
|
|
835
|
+
fullPath: file,
|
|
836
|
+
error: error.message,
|
|
837
|
+
success: false
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
const batchResults = await Promise.all(batchPromises);
|
|
843
|
+
results.push(...batchResults.filter(r => r !== null));
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// Final progress report
|
|
847
|
+
if (options.onProgress) {
|
|
848
|
+
options.onProgress({
|
|
849
|
+
completed: files.length,
|
|
850
|
+
total: files.length,
|
|
851
|
+
percentage: 100
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
} else {
|
|
856
|
+
// Sequential analysis
|
|
857
|
+
for (const file of files) {
|
|
858
|
+
try {
|
|
859
|
+
const result = await this.analyzeFile(file, workingDir, accessConfig, options);
|
|
860
|
+
if (result) {
|
|
861
|
+
results.push(result);
|
|
862
|
+
}
|
|
863
|
+
} catch (error) {
|
|
864
|
+
this.logger?.warn('Failed to analyze file in project', {
|
|
865
|
+
file,
|
|
866
|
+
error: error.message
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
results.push({
|
|
870
|
+
file: this.directoryAccessManager.createRelativePath(file, accessConfig),
|
|
871
|
+
fullPath: file,
|
|
872
|
+
error: error.message,
|
|
873
|
+
success: false
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
return results;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* Fix code issues in a file
|
|
884
|
+
* @private
|
|
885
|
+
*/
|
|
886
|
+
async fixFile(filePath, workingDir, accessConfig, options = {}) {
|
|
887
|
+
const fullPath = path.isAbsolute(filePath)
|
|
888
|
+
? path.normalize(filePath)
|
|
889
|
+
: path.resolve(workingDir, filePath);
|
|
890
|
+
|
|
891
|
+
// Validate read access
|
|
892
|
+
const readResult = this.directoryAccessManager.validateReadAccess(fullPath, accessConfig);
|
|
893
|
+
if (!readResult.allowed) {
|
|
894
|
+
throw new Error(`Read access denied: ${readResult.reason}`);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// Validate write access if writeFile is true
|
|
898
|
+
if (options.writeFile) {
|
|
899
|
+
const writeResult = this.directoryAccessManager.validateWriteAccess(fullPath, accessConfig);
|
|
900
|
+
if (!writeResult.allowed) {
|
|
901
|
+
throw new Error(`Write access denied: ${writeResult.reason}`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
try {
|
|
906
|
+
// Read file
|
|
907
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
908
|
+
|
|
909
|
+
// Get ESLint analyzer
|
|
910
|
+
const eslintAnalyzer = await this.getESLintAnalyzer();
|
|
911
|
+
|
|
912
|
+
// Fix the code
|
|
913
|
+
const fixResult = await eslintAnalyzer.fix(fullPath, content, {
|
|
914
|
+
workingDir,
|
|
915
|
+
accessConfig,
|
|
916
|
+
framework: await this.detectFramework(workingDir, this.detectLanguage(fullPath))
|
|
917
|
+
});
|
|
918
|
+
|
|
919
|
+
// Write file if requested and changes were made
|
|
920
|
+
if (options.writeFile && fixResult.fixed) {
|
|
921
|
+
await fs.writeFile(fullPath, fixResult.content, 'utf-8');
|
|
922
|
+
this.logger?.info('File fixed and written', { file: fullPath });
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
return {
|
|
926
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
927
|
+
fullPath,
|
|
928
|
+
action: 'fix',
|
|
929
|
+
fixed: fixResult.fixed,
|
|
930
|
+
fixedCount: fixResult.fixedCount,
|
|
931
|
+
remainingErrors: fixResult.remainingErrors,
|
|
932
|
+
remainingWarnings: fixResult.remainingWarnings,
|
|
933
|
+
changes: fixResult.changes,
|
|
934
|
+
written: !!(options.writeFile && fixResult.fixed),
|
|
935
|
+
preview: !options.writeFile && fixResult.fixed ? fixResult.content : undefined
|
|
936
|
+
};
|
|
937
|
+
|
|
938
|
+
} catch (error) {
|
|
939
|
+
throw new Error(`Failed to fix ${filePath}: ${error.message}`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* Format code in a file
|
|
945
|
+
* @private
|
|
946
|
+
*/
|
|
947
|
+
async formatFile(filePath, workingDir, accessConfig, options = {}) {
|
|
948
|
+
const fullPath = path.isAbsolute(filePath)
|
|
949
|
+
? path.normalize(filePath)
|
|
950
|
+
: path.resolve(workingDir, filePath);
|
|
951
|
+
|
|
952
|
+
// Validate read access
|
|
953
|
+
const readResult = this.directoryAccessManager.validateReadAccess(fullPath, accessConfig);
|
|
954
|
+
if (!readResult.allowed) {
|
|
955
|
+
throw new Error(`Read access denied: ${readResult.reason}`);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// Validate write access if writeFile is true
|
|
959
|
+
if (options.writeFile) {
|
|
960
|
+
const writeResult = this.directoryAccessManager.validateWriteAccess(fullPath, accessConfig);
|
|
961
|
+
if (!writeResult.allowed) {
|
|
962
|
+
throw new Error(`Write access denied: ${writeResult.reason}`);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
try {
|
|
967
|
+
// Read file
|
|
968
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
969
|
+
|
|
970
|
+
// Get Prettier formatter
|
|
971
|
+
const prettierFormatter = await this.getPrettierFormatter();
|
|
972
|
+
|
|
973
|
+
// Check if file type is supported
|
|
974
|
+
if (!prettierFormatter.isSupported(fullPath)) {
|
|
975
|
+
return {
|
|
976
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
977
|
+
fullPath,
|
|
978
|
+
action: 'format',
|
|
979
|
+
formatted: false,
|
|
980
|
+
skipped: true,
|
|
981
|
+
skipReason: 'File type not supported by Prettier'
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// Format the code
|
|
986
|
+
const formatResult = await prettierFormatter.format(fullPath, content, {
|
|
987
|
+
workingDir,
|
|
988
|
+
accessConfig
|
|
989
|
+
});
|
|
990
|
+
|
|
991
|
+
// Write file if requested and changes were made
|
|
992
|
+
if (options.writeFile && formatResult.formatted) {
|
|
993
|
+
await fs.writeFile(fullPath, formatResult.content, 'utf-8');
|
|
994
|
+
this.logger?.info('File formatted and written', { file: fullPath });
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
return {
|
|
998
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
999
|
+
fullPath,
|
|
1000
|
+
action: 'format',
|
|
1001
|
+
formatted: formatResult.formatted,
|
|
1002
|
+
linesChanged: formatResult.linesChanged,
|
|
1003
|
+
changes: formatResult.changes,
|
|
1004
|
+
written: !!(options.writeFile && formatResult.formatted),
|
|
1005
|
+
preview: !options.writeFile && formatResult.formatted ? formatResult.content : undefined
|
|
1006
|
+
};
|
|
1007
|
+
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
throw new Error(`Failed to format ${filePath}: ${error.message}`);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* Security scan a single file
|
|
1015
|
+
* @private
|
|
1016
|
+
*/
|
|
1017
|
+
async securityScanFile(filePath, workingDir, accessConfig, options = {}) {
|
|
1018
|
+
const fullPath = path.isAbsolute(filePath)
|
|
1019
|
+
? path.normalize(filePath)
|
|
1020
|
+
: path.resolve(workingDir, filePath);
|
|
1021
|
+
|
|
1022
|
+
// Validate read access
|
|
1023
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullPath, accessConfig);
|
|
1024
|
+
if (!accessResult.allowed) {
|
|
1025
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
try {
|
|
1029
|
+
const stats = await fs.stat(fullPath);
|
|
1030
|
+
|
|
1031
|
+
if (stats.size > this.maxFileSize) {
|
|
1032
|
+
throw new Error(`File too large: ${stats.size} bytes (max ${this.maxFileSize})`);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// Detect language
|
|
1036
|
+
const language = this.detectLanguage(fullPath);
|
|
1037
|
+
|
|
1038
|
+
// Security analyzer only supports JS/TS/Python
|
|
1039
|
+
if (!language || !['javascript', 'typescript', 'python'].includes(language)) {
|
|
1040
|
+
return {
|
|
1041
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
1042
|
+
fullPath,
|
|
1043
|
+
language: language || 'unknown',
|
|
1044
|
+
issues: [],
|
|
1045
|
+
skipped: true,
|
|
1046
|
+
skipReason: 'Security scanning only supports JavaScript, TypeScript, and Python files'
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// Read file content
|
|
1051
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
1052
|
+
|
|
1053
|
+
// Get security analyzer
|
|
1054
|
+
const securityAnalyzer = await this.getSecurityAnalyzer();
|
|
1055
|
+
|
|
1056
|
+
// Perform security scan
|
|
1057
|
+
const issues = await securityAnalyzer.analyze(fullPath, content, {
|
|
1058
|
+
skipTestFiles: options.skipTestFiles !== false
|
|
1059
|
+
});
|
|
1060
|
+
|
|
1061
|
+
// Categorize issues by severity
|
|
1062
|
+
const result = {
|
|
1063
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
1064
|
+
fullPath,
|
|
1065
|
+
language,
|
|
1066
|
+
action: 'security-scan',
|
|
1067
|
+
critical: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.CRITICAL),
|
|
1068
|
+
errors: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.ERROR),
|
|
1069
|
+
warnings: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.WARNING),
|
|
1070
|
+
info: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.INFO),
|
|
1071
|
+
totalIssues: issues.length,
|
|
1072
|
+
analyzed: true,
|
|
1073
|
+
scannersUsed: issues.map(i => i.scanner).filter((v, i, a) => a.indexOf(v) === i),
|
|
1074
|
+
timestamp: new Date().toISOString()
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
return result;
|
|
1078
|
+
|
|
1079
|
+
} catch (error) {
|
|
1080
|
+
throw new Error(`Failed to security scan ${filePath}: ${error.message}`);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* Security scan project directory
|
|
1086
|
+
* @private
|
|
1087
|
+
*/
|
|
1088
|
+
async securityScanProject(directory, pattern, workingDir, accessConfig, options = {}) {
|
|
1089
|
+
const fullDir = path.isAbsolute(directory)
|
|
1090
|
+
? path.normalize(directory)
|
|
1091
|
+
: path.resolve(workingDir, directory);
|
|
1092
|
+
|
|
1093
|
+
// Validate read access
|
|
1094
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullDir, accessConfig);
|
|
1095
|
+
if (!accessResult.allowed) {
|
|
1096
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
// Get security analyzer for dependency scanning
|
|
1100
|
+
const securityAnalyzer = await this.getSecurityAnalyzer();
|
|
1101
|
+
|
|
1102
|
+
// Run dependency scans at project level
|
|
1103
|
+
const dependencyIssues = await securityAnalyzer.analyzeProject(fullDir, 'javascript', options);
|
|
1104
|
+
|
|
1105
|
+
// Find all matching files (only JS/TS/Python for security scanning)
|
|
1106
|
+
const searchPattern = pattern || '**/*.{js,jsx,mjs,cjs,ts,tsx,py}';
|
|
1107
|
+
const files = await this.findFiles(fullDir, searchPattern);
|
|
1108
|
+
|
|
1109
|
+
if (files.length > this.maxFilesPerBatch) {
|
|
1110
|
+
throw new Error(`Too many files: ${files.length} (max ${this.maxFilesPerBatch})`);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// Scan files (parallel or sequential)
|
|
1114
|
+
const results = [];
|
|
1115
|
+
|
|
1116
|
+
if (this.parallelAnalysis && files.length > 1) {
|
|
1117
|
+
// Parallel scanning in batches
|
|
1118
|
+
this.logger?.debug('Using parallel security scanning', {
|
|
1119
|
+
totalFiles: files.length,
|
|
1120
|
+
batchSize: this.maxParallelFiles
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
for (let i = 0; i < files.length; i += this.maxParallelFiles) {
|
|
1124
|
+
const batch = files.slice(i, i + this.maxParallelFiles);
|
|
1125
|
+
|
|
1126
|
+
if (options.onProgress) {
|
|
1127
|
+
options.onProgress({
|
|
1128
|
+
completed: i,
|
|
1129
|
+
total: files.length,
|
|
1130
|
+
percentage: Math.round((i / files.length) * 100)
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
const batchPromises = batch.map(async (file) => {
|
|
1135
|
+
try {
|
|
1136
|
+
return await this.securityScanFile(file, workingDir, accessConfig, options);
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
this.logger?.warn('Failed to security scan file in project', {
|
|
1139
|
+
file,
|
|
1140
|
+
error: error.message
|
|
1141
|
+
});
|
|
1142
|
+
|
|
1143
|
+
return {
|
|
1144
|
+
file: this.directoryAccessManager.createRelativePath(file, accessConfig),
|
|
1145
|
+
fullPath: file,
|
|
1146
|
+
error: error.message,
|
|
1147
|
+
success: false
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
});
|
|
1151
|
+
|
|
1152
|
+
const batchResults = await Promise.all(batchPromises);
|
|
1153
|
+
results.push(...batchResults.filter(r => r !== null));
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
if (options.onProgress) {
|
|
1157
|
+
options.onProgress({
|
|
1158
|
+
completed: files.length,
|
|
1159
|
+
total: files.length,
|
|
1160
|
+
percentage: 100
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
} else {
|
|
1165
|
+
// Sequential scanning
|
|
1166
|
+
for (const file of files) {
|
|
1167
|
+
try {
|
|
1168
|
+
const result = await this.securityScanFile(file, workingDir, accessConfig, options);
|
|
1169
|
+
if (result) {
|
|
1170
|
+
results.push(result);
|
|
1171
|
+
}
|
|
1172
|
+
} catch (error) {
|
|
1173
|
+
this.logger?.warn('Failed to security scan file in project', {
|
|
1174
|
+
file,
|
|
1175
|
+
error: error.message
|
|
1176
|
+
});
|
|
1177
|
+
|
|
1178
|
+
results.push({
|
|
1179
|
+
file: this.directoryAccessManager.createRelativePath(file, accessConfig),
|
|
1180
|
+
fullPath: file,
|
|
1181
|
+
error: error.message,
|
|
1182
|
+
success: false
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// Add dependency scan results if any
|
|
1189
|
+
if (dependencyIssues.length > 0) {
|
|
1190
|
+
results.push({
|
|
1191
|
+
file: path.join(fullDir, 'package.json'),
|
|
1192
|
+
fullPath: path.join(fullDir, 'package.json'),
|
|
1193
|
+
action: 'dependency-scan',
|
|
1194
|
+
critical: dependencyIssues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.CRITICAL),
|
|
1195
|
+
errors: dependencyIssues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.ERROR),
|
|
1196
|
+
warnings: dependencyIssues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.WARNING),
|
|
1197
|
+
info: dependencyIssues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.INFO),
|
|
1198
|
+
totalIssues: dependencyIssues.length,
|
|
1199
|
+
analyzed: true,
|
|
1200
|
+
scannersUsed: ['npm-audit'],
|
|
1201
|
+
timestamp: new Date().toISOString()
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
return results;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Validate a configuration file
|
|
1210
|
+
* @private
|
|
1211
|
+
*/
|
|
1212
|
+
async validateConfigFile(filePath, workingDir, accessConfig, options = {}) {
|
|
1213
|
+
const fullPath = path.isAbsolute(filePath)
|
|
1214
|
+
? path.normalize(filePath)
|
|
1215
|
+
: path.resolve(workingDir, filePath);
|
|
1216
|
+
|
|
1217
|
+
// Validate read access
|
|
1218
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullPath, accessConfig);
|
|
1219
|
+
if (!accessResult.allowed) {
|
|
1220
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
try {
|
|
1224
|
+
const stats = await fs.stat(fullPath);
|
|
1225
|
+
|
|
1226
|
+
if (stats.size > this.maxFileSize) {
|
|
1227
|
+
throw new Error(`File too large: ${stats.size} bytes (max ${this.maxFileSize})`);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// Get config validator
|
|
1231
|
+
const configValidator = await this.getConfigValidator();
|
|
1232
|
+
|
|
1233
|
+
// Perform validation
|
|
1234
|
+
const issues = await configValidator.validate(fullPath, options);
|
|
1235
|
+
|
|
1236
|
+
// Categorize issues by severity
|
|
1237
|
+
const result = {
|
|
1238
|
+
file: this.directoryAccessManager.createRelativePath(fullPath, accessConfig),
|
|
1239
|
+
fullPath,
|
|
1240
|
+
action: 'validate-config',
|
|
1241
|
+
critical: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.CRITICAL),
|
|
1242
|
+
errors: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.ERROR),
|
|
1243
|
+
warnings: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.WARNING),
|
|
1244
|
+
info: issues.filter(d => d.severity === STATIC_ANALYSIS.SEVERITY.INFO),
|
|
1245
|
+
totalIssues: issues.length,
|
|
1246
|
+
analyzed: true,
|
|
1247
|
+
validatorsUsed: issues.map(i => i.validator).filter((v, i, a) => a.indexOf(v) === i),
|
|
1248
|
+
timestamp: new Date().toISOString()
|
|
1249
|
+
};
|
|
1250
|
+
|
|
1251
|
+
return result;
|
|
1252
|
+
|
|
1253
|
+
} catch (error) {
|
|
1254
|
+
throw new Error(`Failed to validate config ${filePath}: ${error.message}`);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* Validate configuration files in a directory
|
|
1260
|
+
* @private
|
|
1261
|
+
*/
|
|
1262
|
+
async validateConfigDirectory(directory, workingDir, accessConfig, options = {}) {
|
|
1263
|
+
const fullDir = path.isAbsolute(directory)
|
|
1264
|
+
? path.normalize(directory)
|
|
1265
|
+
: path.resolve(workingDir, directory);
|
|
1266
|
+
|
|
1267
|
+
// Validate read access
|
|
1268
|
+
const accessResult = this.directoryAccessManager.validateReadAccess(fullDir, accessConfig);
|
|
1269
|
+
if (!accessResult.allowed) {
|
|
1270
|
+
throw new Error(`Read access denied: ${accessResult.reason}`);
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
// Find common config files
|
|
1274
|
+
const configFiles = await this.findConfigFiles(fullDir);
|
|
1275
|
+
|
|
1276
|
+
if (configFiles.length > this.maxFilesPerBatch) {
|
|
1277
|
+
throw new Error(`Too many config files: ${configFiles.length} (max ${this.maxFilesPerBatch})`);
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// Validate files
|
|
1281
|
+
const results = [];
|
|
1282
|
+
|
|
1283
|
+
for (const file of configFiles) {
|
|
1284
|
+
try {
|
|
1285
|
+
const result = await this.validateConfigFile(file, workingDir, accessConfig, options);
|
|
1286
|
+
if (result) {
|
|
1287
|
+
results.push(result);
|
|
1288
|
+
}
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
this.logger?.warn('Failed to validate config file', {
|
|
1291
|
+
file,
|
|
1292
|
+
error: error.message
|
|
1293
|
+
});
|
|
1294
|
+
|
|
1295
|
+
results.push({
|
|
1296
|
+
file: this.directoryAccessManager.createRelativePath(file, accessConfig),
|
|
1297
|
+
fullPath: file,
|
|
1298
|
+
error: error.message,
|
|
1299
|
+
success: false
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
return results;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* Find common configuration files in directory
|
|
1309
|
+
* @private
|
|
1310
|
+
*/
|
|
1311
|
+
async findConfigFiles(directory) {
|
|
1312
|
+
const files = [];
|
|
1313
|
+
const configFileNames = [
|
|
1314
|
+
'package.json',
|
|
1315
|
+
'tsconfig.json',
|
|
1316
|
+
'Dockerfile',
|
|
1317
|
+
'docker-compose.yml',
|
|
1318
|
+
'docker-compose.yaml',
|
|
1319
|
+
'.env',
|
|
1320
|
+
'.env.example',
|
|
1321
|
+
'.eslintrc.js',
|
|
1322
|
+
'.eslintrc.json',
|
|
1323
|
+
'.prettierrc',
|
|
1324
|
+
'.prettierrc.json'
|
|
1325
|
+
];
|
|
1326
|
+
|
|
1327
|
+
const configExtensions = ['.yml', '.yaml', '.json', '.tf', '.tfvars'];
|
|
1328
|
+
|
|
1329
|
+
const walk = async (dir) => {
|
|
1330
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1331
|
+
|
|
1332
|
+
for (const entry of entries) {
|
|
1333
|
+
const fullPath = path.join(dir, entry.name);
|
|
1334
|
+
|
|
1335
|
+
if (entry.isDirectory()) {
|
|
1336
|
+
// Check specific directories for config files
|
|
1337
|
+
if (entry.name === '.github' || entry.name === 'kubernetes' || entry.name === 'k8s' || entry.name === 'terraform') {
|
|
1338
|
+
await walk(fullPath);
|
|
1339
|
+
} else if (!['node_modules', '.git', 'dist', 'build'].includes(entry.name)) {
|
|
1340
|
+
// Don't recurse into all subdirectories, only known config dirs
|
|
1341
|
+
// Check this level only
|
|
1342
|
+
continue;
|
|
1343
|
+
}
|
|
1344
|
+
} else if (entry.isFile()) {
|
|
1345
|
+
// Check if it's a known config file
|
|
1346
|
+
if (configFileNames.includes(entry.name)) {
|
|
1347
|
+
files.push(fullPath);
|
|
1348
|
+
} else {
|
|
1349
|
+
// Check if it's in a config directory with config extension
|
|
1350
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
1351
|
+
if (configExtensions.includes(ext)) {
|
|
1352
|
+
const dirname = path.basename(path.dirname(fullPath));
|
|
1353
|
+
if (dirname === 'kubernetes' || dirname === 'k8s' || dirname === 'terraform' || dirname === 'workflows') {
|
|
1354
|
+
files.push(fullPath);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
};
|
|
1361
|
+
|
|
1362
|
+
await walk(directory);
|
|
1363
|
+
return files;
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
/**
|
|
1367
|
+
* Detect programming language from file extension
|
|
1368
|
+
* @private
|
|
1369
|
+
*/
|
|
1370
|
+
detectLanguage(filePath) {
|
|
1371
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
1372
|
+
return STATIC_ANALYSIS.EXTENSION_TO_LANGUAGE[ext] || null;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/**
|
|
1376
|
+
* Detect framework from project directory
|
|
1377
|
+
* @private
|
|
1378
|
+
*/
|
|
1379
|
+
async detectFramework(projectDir, language) {
|
|
1380
|
+
try {
|
|
1381
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.JAVASCRIPT ||
|
|
1382
|
+
language === STATIC_ANALYSIS.LANGUAGE.TYPESCRIPT) {
|
|
1383
|
+
return await this.detectJSFramework(projectDir);
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.PYTHON) {
|
|
1387
|
+
return await this.detectPythonFramework(projectDir);
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
return null;
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
this.logger?.debug('Framework detection failed', { error: error.message });
|
|
1393
|
+
return null;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
/**
|
|
1398
|
+
* Detect JavaScript/TypeScript framework
|
|
1399
|
+
* @private
|
|
1400
|
+
*/
|
|
1401
|
+
async detectJSFramework(projectDir) {
|
|
1402
|
+
try {
|
|
1403
|
+
const pkgPath = path.join(projectDir, STATIC_ANALYSIS.FRAMEWORK_MANIFESTS.JAVASCRIPT);
|
|
1404
|
+
const pkgContent = await fs.readFile(pkgPath, 'utf-8');
|
|
1405
|
+
const pkg = JSON.parse(pkgContent);
|
|
1406
|
+
|
|
1407
|
+
const deps = {
|
|
1408
|
+
...pkg.dependencies,
|
|
1409
|
+
...pkg.devDependencies
|
|
1410
|
+
};
|
|
1411
|
+
|
|
1412
|
+
// Check for frameworks in priority order
|
|
1413
|
+
for (const [name, identifier] of Object.entries(STATIC_ANALYSIS.JS_FRAMEWORKS)) {
|
|
1414
|
+
if (deps[identifier]) {
|
|
1415
|
+
return name.toLowerCase();
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
return null;
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
return null;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Detect Python framework
|
|
1427
|
+
* @private
|
|
1428
|
+
*/
|
|
1429
|
+
async detectPythonFramework(projectDir) {
|
|
1430
|
+
try {
|
|
1431
|
+
// Try requirements.txt
|
|
1432
|
+
const reqPath = path.join(projectDir, STATIC_ANALYSIS.FRAMEWORK_MANIFESTS.PYTHON);
|
|
1433
|
+
const reqContent = await fs.readFile(reqPath, 'utf-8');
|
|
1434
|
+
|
|
1435
|
+
// Check for frameworks
|
|
1436
|
+
for (const [name, identifier] of Object.entries(STATIC_ANALYSIS.PYTHON_FRAMEWORKS)) {
|
|
1437
|
+
if (reqContent.toLowerCase().includes(identifier)) {
|
|
1438
|
+
return name.toLowerCase();
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
return null;
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
// Try pyproject.toml
|
|
1445
|
+
try {
|
|
1446
|
+
const tomlPath = path.join(projectDir, STATIC_ANALYSIS.FRAMEWORK_MANIFESTS.PYTHON_POETRY);
|
|
1447
|
+
const tomlContent = await fs.readFile(tomlPath, 'utf-8');
|
|
1448
|
+
|
|
1449
|
+
for (const [name, identifier] of Object.entries(STATIC_ANALYSIS.PYTHON_FRAMEWORKS)) {
|
|
1450
|
+
if (tomlContent.toLowerCase().includes(identifier)) {
|
|
1451
|
+
return name.toLowerCase();
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
} catch {
|
|
1455
|
+
// No framework detected
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
return null;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/**
|
|
1463
|
+
* Find files matching pattern in directory
|
|
1464
|
+
* @private
|
|
1465
|
+
*/
|
|
1466
|
+
async findFiles(directory, pattern) {
|
|
1467
|
+
const files = [];
|
|
1468
|
+
|
|
1469
|
+
// Default patterns by language if not specified
|
|
1470
|
+
const searchPattern = pattern || '**/*.{js,jsx,mjs,cjs,ts,tsx,py,css,scss,sass,less}';
|
|
1471
|
+
|
|
1472
|
+
// Parse pattern to extract extensions
|
|
1473
|
+
// Supports patterns like "**/*.ts", "**/*.{js,ts}", "*.js", etc.
|
|
1474
|
+
const getExtensionsFromPattern = (pat) => {
|
|
1475
|
+
const exts = [];
|
|
1476
|
+
|
|
1477
|
+
// Match patterns like *.{js,ts,tsx} or *.js
|
|
1478
|
+
const bracesMatch = pat.match(/\*\.\{([^}]+)\}/);
|
|
1479
|
+
if (bracesMatch) {
|
|
1480
|
+
// Multiple extensions: *.{js,ts,tsx}
|
|
1481
|
+
const extList = bracesMatch[1].split(',').map(e => e.trim());
|
|
1482
|
+
extList.forEach(ext => exts.push(ext.startsWith('.') ? ext : '.' + ext));
|
|
1483
|
+
} else {
|
|
1484
|
+
// Single extension: *.js or **/*.ts
|
|
1485
|
+
const singleMatch = pat.match(/\*\.([a-z]+)$/i);
|
|
1486
|
+
if (singleMatch) {
|
|
1487
|
+
const ext = singleMatch[1];
|
|
1488
|
+
exts.push(ext.startsWith('.') ? ext : '.' + ext);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
// If no pattern found, allow all supported extensions
|
|
1493
|
+
if (exts.length === 0) {
|
|
1494
|
+
return null; // null means "all supported extensions"
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
return exts;
|
|
1498
|
+
};
|
|
1499
|
+
|
|
1500
|
+
const allowedExtensions = getExtensionsFromPattern(searchPattern);
|
|
1501
|
+
|
|
1502
|
+
// Simple recursive file search
|
|
1503
|
+
const walk = async (dir) => {
|
|
1504
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1505
|
+
|
|
1506
|
+
for (const entry of entries) {
|
|
1507
|
+
const fullPath = path.join(dir, entry.name);
|
|
1508
|
+
|
|
1509
|
+
if (entry.isDirectory()) {
|
|
1510
|
+
// Skip common ignore directories
|
|
1511
|
+
if (!['node_modules', '.git', 'dist', 'build', '__pycache__', '.venv', 'venv'].includes(entry.name)) {
|
|
1512
|
+
await walk(fullPath);
|
|
1513
|
+
}
|
|
1514
|
+
} else if (entry.isFile()) {
|
|
1515
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
1516
|
+
|
|
1517
|
+
// Check if file extension is supported
|
|
1518
|
+
if (STATIC_ANALYSIS.EXTENSION_TO_LANGUAGE[ext]) {
|
|
1519
|
+
// If pattern specified, check if extension matches
|
|
1520
|
+
if (allowedExtensions === null || allowedExtensions.includes(ext)) {
|
|
1521
|
+
files.push(fullPath);
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
await walk(directory);
|
|
1529
|
+
return files;
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* Get analyzer for language (lazy initialization)
|
|
1534
|
+
* @private
|
|
1535
|
+
*/
|
|
1536
|
+
async getAnalyzer(language) {
|
|
1537
|
+
try {
|
|
1538
|
+
// Lazy load analyzers
|
|
1539
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.JAVASCRIPT) {
|
|
1540
|
+
if (!this.analyzers.javascript) {
|
|
1541
|
+
const { default: JavaScriptAnalyzer } = await import('../analyzers/JavaScriptAnalyzer.js');
|
|
1542
|
+
this.analyzers.javascript = new JavaScriptAnalyzer(this.logger);
|
|
1543
|
+
}
|
|
1544
|
+
return this.analyzers.javascript;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.TYPESCRIPT) {
|
|
1548
|
+
if (!this.analyzers.typescript) {
|
|
1549
|
+
const { default: TypeScriptAnalyzer } = await import('../analyzers/TypeScriptAnalyzer.js');
|
|
1550
|
+
this.analyzers.typescript = new TypeScriptAnalyzer(this.logger);
|
|
1551
|
+
}
|
|
1552
|
+
return this.analyzers.typescript;
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
// Python analyzer
|
|
1556
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.PYTHON) {
|
|
1557
|
+
if (!this.analyzers.python) {
|
|
1558
|
+
const { default: PythonAnalyzer } = await import('../analyzers/PythonAnalyzer.js');
|
|
1559
|
+
this.analyzers.python = new PythonAnalyzer(this.logger);
|
|
1560
|
+
}
|
|
1561
|
+
return this.analyzers.python;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// CSS analyzer (handles CSS, SCSS, LESS)
|
|
1565
|
+
if (language === STATIC_ANALYSIS.LANGUAGE.CSS ||
|
|
1566
|
+
language === STATIC_ANALYSIS.LANGUAGE.SCSS ||
|
|
1567
|
+
language === STATIC_ANALYSIS.LANGUAGE.LESS) {
|
|
1568
|
+
if (!this.analyzers.css) {
|
|
1569
|
+
const { default: CSSAnalyzer } = await import('../analyzers/CSSAnalyzer.js');
|
|
1570
|
+
this.analyzers.css = new CSSAnalyzer(this.logger);
|
|
1571
|
+
}
|
|
1572
|
+
return this.analyzers.css;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
return null;
|
|
1576
|
+
} catch (error) {
|
|
1577
|
+
this.logger?.error('Failed to load analyzer', {
|
|
1578
|
+
language,
|
|
1579
|
+
error: error.message
|
|
1580
|
+
});
|
|
1581
|
+
return null;
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
/**
|
|
1586
|
+
* Get ESLint analyzer (lazy initialization)
|
|
1587
|
+
* @private
|
|
1588
|
+
*/
|
|
1589
|
+
async getESLintAnalyzer() {
|
|
1590
|
+
if (!this.analyzers.eslint) {
|
|
1591
|
+
const { default: ESLintAnalyzer } = await import('../analyzers/ESLintAnalyzer.js');
|
|
1592
|
+
this.analyzers.eslint = new ESLintAnalyzer(this.logger);
|
|
1593
|
+
}
|
|
1594
|
+
return this.analyzers.eslint;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
/**
|
|
1598
|
+
* Get Prettier formatter (lazy initialization)
|
|
1599
|
+
* @private
|
|
1600
|
+
*/
|
|
1601
|
+
async getPrettierFormatter() {
|
|
1602
|
+
if (!this.formatters.prettier) {
|
|
1603
|
+
const { default: PrettierFormatter } = await import('../analyzers/PrettierFormatter.js');
|
|
1604
|
+
this.formatters.prettier = new PrettierFormatter(this.logger);
|
|
1605
|
+
}
|
|
1606
|
+
return this.formatters.prettier;
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
/**
|
|
1610
|
+
* Get Security analyzer (lazy initialization)
|
|
1611
|
+
* @private
|
|
1612
|
+
*/
|
|
1613
|
+
async getSecurityAnalyzer() {
|
|
1614
|
+
if (!this.analyzers.security) {
|
|
1615
|
+
const { default: SecurityAnalyzer } = await import('../analyzers/SecurityAnalyzer.js');
|
|
1616
|
+
this.analyzers.security = new SecurityAnalyzer(this.logger);
|
|
1617
|
+
}
|
|
1618
|
+
return this.analyzers.security;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* Get Config validator (lazy initialization)
|
|
1623
|
+
* @private
|
|
1624
|
+
*/
|
|
1625
|
+
async getConfigValidator() {
|
|
1626
|
+
if (!this.analyzers.config) {
|
|
1627
|
+
const { default: ConfigValidator } = await import('../analyzers/ConfigValidator.js');
|
|
1628
|
+
this.analyzers.config = new ConfigValidator(this.logger);
|
|
1629
|
+
}
|
|
1630
|
+
return this.analyzers.config;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
/**
|
|
1634
|
+
* Update summary statistics
|
|
1635
|
+
* @private
|
|
1636
|
+
*/
|
|
1637
|
+
updateSummary(summary, fileResult) {
|
|
1638
|
+
if (fileResult.analyzed) {
|
|
1639
|
+
summary.totalFiles++;
|
|
1640
|
+
|
|
1641
|
+
const criticalCount = fileResult.critical?.length || 0;
|
|
1642
|
+
const errorCount = fileResult.errors?.length || 0;
|
|
1643
|
+
const warningCount = fileResult.warnings?.length || 0;
|
|
1644
|
+
const infoCount = fileResult.info?.length || 0;
|
|
1645
|
+
|
|
1646
|
+
// Initialize totalCritical if not exists (for backward compatibility)
|
|
1647
|
+
if (summary.totalCritical === undefined) {
|
|
1648
|
+
summary.totalCritical = 0;
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
summary.totalCritical += criticalCount;
|
|
1652
|
+
summary.totalErrors += errorCount;
|
|
1653
|
+
summary.totalWarnings += warningCount;
|
|
1654
|
+
summary.totalInfo += infoCount;
|
|
1655
|
+
|
|
1656
|
+
if (criticalCount > 0 || errorCount > 0) {
|
|
1657
|
+
summary.filesWithErrors++;
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
// Count by language
|
|
1661
|
+
if (fileResult.language) {
|
|
1662
|
+
summary.filesByLanguage[fileResult.language] =
|
|
1663
|
+
(summary.filesByLanguage[fileResult.language] || 0) + 1;
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
// Count by category (include critical issues)
|
|
1667
|
+
const allIssues = [
|
|
1668
|
+
...(fileResult.critical || []),
|
|
1669
|
+
...(fileResult.errors || []),
|
|
1670
|
+
...(fileResult.warnings || [])
|
|
1671
|
+
];
|
|
1672
|
+
|
|
1673
|
+
for (const issue of allIssues) {
|
|
1674
|
+
if (issue.category) {
|
|
1675
|
+
summary.errorsByCategory[issue.category] =
|
|
1676
|
+
(summary.errorsByCategory[issue.category] || 0) + 1;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/**
|
|
1683
|
+
* Compute content hash for caching
|
|
1684
|
+
* @private
|
|
1685
|
+
*/
|
|
1686
|
+
computeContentHash(content) {
|
|
1687
|
+
return crypto
|
|
1688
|
+
.createHash('sha256')
|
|
1689
|
+
.update(content)
|
|
1690
|
+
.digest('hex')
|
|
1691
|
+
.substring(0, 16); // Use first 16 chars for shorter cache keys
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
/**
|
|
1695
|
+
* Get performance metrics
|
|
1696
|
+
* @returns {Object} Performance metrics
|
|
1697
|
+
*/
|
|
1698
|
+
getPerformanceMetrics() {
|
|
1699
|
+
const cacheHitRate = this.metrics.totalAnalyses > 0
|
|
1700
|
+
? (this.metrics.cacheHits / this.metrics.totalAnalyses) * 100
|
|
1701
|
+
: 0;
|
|
1702
|
+
|
|
1703
|
+
const avgAnalysisTime = this.metrics.filesAnalyzed > 0
|
|
1704
|
+
? this.metrics.totalAnalysisTime / this.metrics.filesAnalyzed
|
|
1705
|
+
: 0;
|
|
1706
|
+
|
|
1707
|
+
return {
|
|
1708
|
+
...this.metrics,
|
|
1709
|
+
cacheHitRate: Math.round(cacheHitRate * 10) / 10, // Round to 1 decimal
|
|
1710
|
+
averageAnalysisTime: Math.round(avgAnalysisTime),
|
|
1711
|
+
cacheSize: this.analysisCache.size
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/**
|
|
1716
|
+
* Reset performance metrics
|
|
1717
|
+
*/
|
|
1718
|
+
resetPerformanceMetrics() {
|
|
1719
|
+
this.metrics = {
|
|
1720
|
+
totalAnalyses: 0,
|
|
1721
|
+
cacheHits: 0,
|
|
1722
|
+
cacheMisses: 0,
|
|
1723
|
+
totalAnalysisTime: 0,
|
|
1724
|
+
filesAnalyzed: 0,
|
|
1725
|
+
parallelBatches: 0
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
/**
|
|
1730
|
+
* Clear analysis cache
|
|
1731
|
+
*/
|
|
1732
|
+
clearCache() {
|
|
1733
|
+
this.analysisCache.clear();
|
|
1734
|
+
this.logger?.debug('Analysis cache cleared');
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* Get supported actions for this tool
|
|
1739
|
+
* @returns {Array<string>} Array of supported action names
|
|
1740
|
+
*/
|
|
1741
|
+
getSupportedActions() {
|
|
1742
|
+
return ['analyze', 'analyze-project', 'fix', 'format', 'security-scan', 'security-scan-project', 'validate-config', 'validate-config-directory'];
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
/**
|
|
1746
|
+
* Get parameter schema for validation
|
|
1747
|
+
* @returns {Object} Parameter schema
|
|
1748
|
+
*/
|
|
1749
|
+
getParameterSchema() {
|
|
1750
|
+
return {
|
|
1751
|
+
type: 'object',
|
|
1752
|
+
properties: {
|
|
1753
|
+
actions: {
|
|
1754
|
+
type: 'array',
|
|
1755
|
+
minItems: 1,
|
|
1756
|
+
items: {
|
|
1757
|
+
type: 'object',
|
|
1758
|
+
properties: {
|
|
1759
|
+
type: {
|
|
1760
|
+
type: 'string',
|
|
1761
|
+
enum: this.getSupportedActions()
|
|
1762
|
+
},
|
|
1763
|
+
filePath: { type: 'string' },
|
|
1764
|
+
directory: { type: 'string' },
|
|
1765
|
+
pattern: { type: 'string' },
|
|
1766
|
+
includeWarnings: { type: 'boolean' },
|
|
1767
|
+
maxErrors: { type: 'number' }
|
|
1768
|
+
},
|
|
1769
|
+
required: ['type']
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
},
|
|
1773
|
+
required: ['actions']
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
export default StaticAnalysisTool;
|