-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaiModelRouter.ts
More file actions
1441 lines (1242 loc) · 60.5 KB
/
aiModelRouter.ts
File metadata and controls
1441 lines (1242 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from 'path';
interface AIModel {
name: string;
specialty: string[];
process: (context: any) => Promise<any>;
confidence: (context: any) => number;
analysisType: string;
}
export interface WorkspaceContext {
files: string[];
language: Map<string, number>;
dependencies: Record<string, string>;
projectType: string;
fileContents: Map<string, string>;
folderStructure: Record<string, any>;
symbols?: Map<string, any[]>;
references?: Map<string, any[]>;
imports?: Map<string, any[]>;
semanticRelationships?: Map<string, string[]>;
workspaceContext?: WorkspaceContext;
selectionMetadata?: any;
analysisTimestamp?: number;
securityScan?: {
vulnerabilities: any[];
score: number;
lastScanDate?: string;
};
}
export class AIModelRouter {
private models: Map<string, AIModel>;
private lastUsedModel: string | null = null;
private defaultModel = 'code';
constructor() {
this.models = new Map([
['code', {
name: 'Claude',
specialty: ['code-analysis', 'code-generation', 'refactoring', 'debugging'],
confidence: (context: WorkspaceContext) => {
// Higher confidence for code-heavy contexts
const codeFiles = Array.from(context.language.entries())
.filter(([ext]) => ['.ts', '.js', '.py', '.java', '.cpp', '.c', '.cs', '.go', '.rs', '.php'].includes(ext))
.reduce((sum, [, count]) => sum + count, 0);
// Check if we have symbols (indicates code structure)
const hasSymbols = context.symbols && context.symbols.size > 0;
// Check if we're dealing with a complex codebase
const hasImports = context.imports && context.imports.size > 0;
// Base confidence on code files + bonus for structure
return Math.min(0.95, (codeFiles > 0 ? 0.7 : 0.3) + (hasSymbols ? 0.15 : 0) + (hasImports ? 0.1 : 0));
},
process: async (context: WorkspaceContext) => {
// Using integrated VS Code Copilot for code analysis
const result = await this.processWithCopilot(context, 'code');
// Enhance the result with code structure information
if (context.symbols && context.symbols.size > 0) {
result.codeStructure = this.summarizeCodeStructure(context);
}
if (context.semanticRelationships && context.semanticRelationships.size > 0) {
result.dependencies = this.summarizeDependencies(context);
}
return {
type: 'code-analysis',
suggestions: result
};
},
analysisType: 'code-analysis'
}],
['testing', {
name: 'ChatGPT',
specialty: ['testing', 'quality-assurance', 'test-generation', 'test-coverage'],
confidence: (context: WorkspaceContext) => {
// Higher confidence for test files
const testFiles = Array.from(context.fileContents.keys())
.filter(file => file.includes('test') || file.includes('spec')).length;
// Check if we have test frameworks in dependencies
const hasTestDeps = Object.keys(context.dependencies || {})
.some(dep => ['jest', 'mocha', 'jasmine', 'karma', 'pytest', 'unittest', 'cypress', 'selenium'].includes(dep));
return Math.min(0.95, (testFiles > 0 ? 0.7 : 0.4) + (hasTestDeps ? 0.2 : 0));
},
process: async (context: WorkspaceContext) => {
// Using integrated VS Code Copilot for test analysis
const result = await this.processWithCopilot(context, 'test');
// Enhance with test-specific insights
result.testCoverage = this.analyzeTestCoverage(context);
return {
type: 'test-analysis',
suggestions: result
};
},
analysisType: 'test-analysis'
}],
['documentation', {
name: 'Gemini',
specialty: ['documentation', 'explanation', 'readme-generation', 'api-docs'],
confidence: (context: WorkspaceContext) => {
// Higher confidence for documentation files
const docFiles = Array.from(context.fileContents.keys())
.filter(file => file.endsWith('.md') || file.endsWith('.txt') ||
file.includes('README') || file.includes('CONTRIBUTING') ||
file.includes('docs/')).length;
// Check if we're dealing with API documentation
const hasApiDocs = Array.from(context.fileContents.values())
.some(content => content.includes('@api') || content.includes('* @param') ||
content.includes('/**') || content.includes('///'));
return Math.min(0.95, (docFiles > 0 ? 0.7 : 0.5) + (hasApiDocs ? 0.2 : 0));
},
process: async (context: WorkspaceContext) => {
// Using integrated VS Code Copilot for documentation
const result = await this.processWithCopilot(context, 'docs');
// Enhance with documentation-specific insights
result.docQuality = this.analyzeDocumentationQuality(context);
result.missingDocs = this.findMissingDocumentation(context);
return {
type: 'documentation-analysis',
suggestions: result
};
},
analysisType: 'documentation-analysis'
}],
['security', {
name: 'Anthropic Claude',
specialty: ['security-analysis', 'vulnerability-detection', 'risk-assessment', 'compliance'],
confidence: (context: WorkspaceContext) => {
// Higher confidence for security-critical contexts
// Check for security-sensitive files
const securityFiles = Array.from(context.fileContents.keys())
.filter(file =>
file.includes('auth') ||
file.includes('security') ||
file.includes('crypto') ||
file.includes('password') ||
file.includes('login') ||
file.endsWith('.env')
).length;
// Check for security-related dependencies
const hasSecurityDeps = Object.keys(context.dependencies || {})
.some(dep =>
['bcrypt', 'crypto', 'jsonwebtoken', 'passport', 'helmet', 'ssl', 'auth0'].includes(dep.toLowerCase())
);
// Check for security-sensitive code patterns
const securityPatterns = Array.from(context.fileContents.values())
.some(content =>
content.includes('password') ||
content.includes('token') ||
content.includes('secret') ||
content.includes('encrypt') ||
content.includes('decrypt')
);
return Math.min(0.95,
0.5 +
(securityFiles > 0 ? 0.2 : 0) +
(hasSecurityDeps ? 0.15 : 0) +
(securityPatterns ? 0.1 : 0)
);
},
process: async (context: WorkspaceContext) => {
// Using integrated VS Code Copilot for security analysis
const result = await this.processWithCopilot(context, 'security');
// Perform security scan
result.securityAnalysis = await this.performSecurityScan(context);
return {
type: 'security-analysis',
suggestions: result
};
},
analysisType: 'security-analysis'
}]
]);
}
async routeRequest(context: WorkspaceContext): Promise<any> {
// Determine the best model to use based on context
const modelType = this.determineModelType(context);
return this.routeRequestToModel(context, modelType);
}
async routeRequestToModel(context: WorkspaceContext, modelType: string): Promise<any> {
// Get the appropriate model
const model = this.models.get(modelType) || this.models.get(this.defaultModel);
if (!model) {
throw new Error('No model available for analysis');
}
// Calculate confidence score based on context complexity
const confidenceScore = this.calculateConfidenceScore(context, modelType);
try {
// Prepare the context for the model
const preparedContext = this.prepareContextForModel(context);
// Call the model with the prepared context
const result = await this.callModel(model, preparedContext);
// Process the results
const processedResult = this.processResults(result);
// Add metadata to the result
return {
modelUsed: model.name,
modelType: modelType,
confidenceScore: confidenceScore.toFixed(2),
analysisType: model.analysisType,
results: processedResult,
summary: this.generateSummary(processedResult),
selectionMetadata: (context as any).selectionMetadata
};
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Model analysis failed: ${errorMessage}`);
}
}
private determineModelType(context: WorkspaceContext): string {
// If this is a selection analysis with selection metadata
if ((context as any).selectionMetadata) {
const metadata = (context as any).selectionMetadata;
// Check if it's a test file
if (metadata.fileName.includes('test') ||
metadata.fileName.includes('spec') ||
metadata.containingSymbol?.name.includes('test') ||
metadata.containingSymbol?.name.includes('Test')) {
return 'testing';
}
// Check if it's documentation
if (metadata.language === 'markdown' ||
metadata.fileName.endsWith('.md') ||
metadata.selectedText.includes('/**') ||
metadata.selectedText.includes('///')) {
return 'documentation';
}
// Check if it's debugging-related
if (metadata.selectedText.includes('console.log') ||
metadata.selectedText.includes('debugger') ||
metadata.selectedText.includes('catch') ||
metadata.selectedText.includes('error') ||
metadata.selectedText.includes('exception')) {
return 'debugging';
}
// Default to code analysis for selections
return 'code';
}
// For non-selection analysis, determine based on file types
let bestModel = this.defaultModel;
let highestConfidence = 0;
// Check confidence scores for each model
for (const [modelType, model] of this.models.entries()) {
const confidence = model.confidence(context);
if (confidence > highestConfidence) {
highestConfidence = confidence;
bestModel = modelType;
}
}
// Remember the model we used
this.lastUsedModel = bestModel;
return bestModel;
}
// Get available model types for UI display
getAvailableModelTypes(): string[] {
return Array.from(this.models.keys());
} private copilotIntegration: any; // Will be initialized on first use
async processWithCopilot(context: WorkspaceContext, analysisType: string): Promise<any> {
// Lazy-load the Copilot integration to avoid circular dependencies
if (!this.copilotIntegration) {
try {
const CopilotIntegration = require('./src/copilotIntegration').CopilotIntegration;
this.copilotIntegration = new CopilotIntegration();
} catch (error) {
console.error('Error loading Copilot integration:', error);
// Fall back to simulation mode if module cannot be loaded
return this.simulateCopilotResponse(context, analysisType);
}
}
console.log(`Processing with Copilot for ${analysisType} analysis`);
try {
// Use the Copilot integration module
return await this.copilotIntegration.processWithCopilot(context, analysisType);
} catch (error) {
console.error('Error using Copilot integration:', error);
// Fall back to simulation on error
return this.simulateCopilotResponse(context, analysisType);
}
}
/**
* Fallback simulation of Copilot response
*/
private simulateCopilotResponse(context: WorkspaceContext, analysisType: string): any {
console.log(`Simulating Copilot ${analysisType} analysis (fallback mode)`);
// Create a response based on the context and analysis type
let response: any = {
content: `Analysis of ${context.files.length} files completed.`,
suggestions: []
};
// Add different suggestions based on analysis type
if (analysisType === 'code') {
response.suggestions = [
'Consider refactoring duplicate code into shared functions',
'Add type annotations to improve code clarity',
'Implement error handling for edge cases',
'Use dependency injection for better testability'
];
} else if (analysisType === 'test') {
response.suggestions = [
'Increase test coverage for critical components',
'Add integration tests for key workflows',
'Consider implementing property-based testing',
'Mock external dependencies for unit tests'
];
} else if (analysisType === 'docs') {
response.suggestions = [
'Add examples to complex function documentation',
'Update README with installation instructions',
'Document public API endpoints',
'Create API reference documentation'
];
} else if (analysisType === 'security') {
response.suggestions = [
'Review authentication implementation for security vulnerabilities',
'Ensure all user inputs are properly validated',
'Update dependencies with known security issues',
'Implement CSRF protection for forms'
];
}
return response;
}
/**
* Summarize code structure from workspace context
*/
private summarizeCodeStructure(context: WorkspaceContext): any {
// Initialize code structure summary
const codeStructure = {
fileCount: context.files.length,
languages: {} as Record<string, number>,
symbolCounts: {} as Record<string, number>,
dependencies: [] as string[],
complexity: 'low' as 'low' | 'medium' | 'high'
};
// Summarize language distribution
if (context.language) {
context.language.forEach((count, ext) => {
codeStructure.languages[ext] = count;
});
}
// Count symbols by type
if (context.symbols && context.symbols.size > 0) {
// Gather all symbols from all files
let allSymbols: any[] = [];
context.symbols.forEach((fileSymbols) => {
allSymbols = allSymbols.concat(fileSymbols);
});
// Count by symbol kind
allSymbols.forEach(symbol => {
const kind = typeof symbol.kind === 'string' ? symbol.kind : `kind_${symbol.kind}`;
codeStructure.symbolCounts[kind] = (codeStructure.symbolCounts[kind] || 0) + 1;
});
}
// Include dependencies
if (context.dependencies) {
codeStructure.dependencies = Object.keys(context.dependencies);
}
// Estimate complexity based on various factors
let complexityScore = 0;
// Factor 1: Number of files
if (context.files.length > 100) {
complexityScore += 3;
} else if (context.files.length > 20) {
complexityScore += 2;
} else if (context.files.length > 5) {
complexityScore += 1;
}
// Factor 2: Symbol count
const totalSymbols = Object.values(codeStructure.symbolCounts).reduce((sum, count) => sum + count, 0);
if (totalSymbols > 200) {
complexityScore += 3;
} else if (totalSymbols > 50) {
complexityScore += 2;
} else if (totalSymbols > 10) {
complexityScore += 1;
}
// Factor 3: Dependency count
if (codeStructure.dependencies.length > 15) {
complexityScore += 2;
} else if (codeStructure.dependencies.length > 5) {
complexityScore += 1;
}
// Set complexity level
if (complexityScore >= 5) {
codeStructure.complexity = 'high';
} else if (complexityScore >= 3) {
codeStructure.complexity = 'medium';
}
return codeStructure;
}
/**
* Summarize dependencies and their relationships
*/
private summarizeDependencies(context: WorkspaceContext): any {
const summary = {
totalDependencies: 0,
directDependencies: [] as string[],
devDependencies: [] as string[],
relationships: [] as {source: string, target: string, type: string}[]
};
// Extract package.json dependencies if available
const packageJsonFile = context.files.find(file => path.basename(file) === 'package.json');
if (packageJsonFile && context.fileContents.has(packageJsonFile)) {
try {
const packageJson = JSON.parse(context.fileContents.get(packageJsonFile) || '{}');
if (packageJson.dependencies) {
summary.directDependencies = Object.keys(packageJson.dependencies);
summary.totalDependencies += summary.directDependencies.length;
}
if (packageJson.devDependencies) {
summary.devDependencies = Object.keys(packageJson.devDependencies);
summary.totalDependencies += summary.devDependencies.length;
}
} catch (error) {
console.error('Error parsing package.json:', error);
}
}
// Extract relationship information from imports if available
if (context.imports && context.imports.size > 0) {
const internalModules = new Set<string>();
const allImports: {source: string, target: string}[] = [];
// First pass: collect all internal modules
context.imports.forEach((imports, sourceFile) => {
imports.forEach(imp => {
if (imp.path && !imp.path.startsWith('.')) {
return; // Skip external imports
}
// Resolve relative path to absolute
try {
const sourceDir = path.dirname(sourceFile);
let targetPath = imp.path || '';
if (targetPath.startsWith('.')) {
targetPath = path.resolve(sourceDir, targetPath);
// Handle extensions (.js, .ts, etc.)
if (!path.extname(targetPath)) {
// Try common extensions
for (const ext of ['.ts', '.js', '.tsx', '.jsx']) {
const withExt = targetPath + ext;
if (context.files.includes(withExt)) {
targetPath = withExt;
break;
}
}
}
if (context.files.includes(targetPath)) {
internalModules.add(path.basename(targetPath, path.extname(targetPath)));
}
}
} catch (error) {
// Ignore resolution errors
}
});
});
// Second pass: build relationships
context.imports.forEach((imports, sourceFile) => {
const sourceModule = path.basename(sourceFile, path.extname(sourceFile));
imports.forEach(imp => {
let targetModule = '';
if (imp.path && imp.path.startsWith('.')) {
// Internal import
try {
const sourceDir = path.dirname(sourceFile);
let targetPath = imp.path;
if (targetPath.startsWith('.')) {
targetPath = path.resolve(sourceDir, targetPath);
targetModule = path.basename(targetPath, path.extname(targetPath));
}
} catch (error) {
// Ignore resolution errors
}
} else if (imp.path) {
// External import
targetModule = imp.path.split('/')[0]; // Get package name
}
if (targetModule && sourceModule !== targetModule) {
allImports.push({
source: sourceModule,
target: targetModule
});
}
});
});
// Build final relationships list
const processedRelations = new Set<string>();
allImports.forEach(({source, target}) => {
const relationKey = `${source}:${target}`;
if (!processedRelations.has(relationKey)) {
const relationType = internalModules.has(target) ? 'internal' : 'external';
summary.relationships.push({
source,
target,
type: relationType
});
processedRelations.add(relationKey);
}
});
}
return summary;
}
/**
* Analyze test coverage based on the workspace context
*/
private analyzeTestCoverage(context: WorkspaceContext): any {
const testCoverage = {
testFileCount: 0,
sourceFileCount: 0,
estimatedCoverage: 0,
untested: [] as string[]
};
const testPatterns = [
/test|spec|_test\.|\btest_/i
];
const testFiles: string[] = [];
const sourceFiles: string[] = [];
const sourceExtensions = ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cs', '.go', '.cpp'];
// Categorize files
for (const filePath of context.files) {
const fileExt = path.extname(filePath);
const fileName = path.basename(filePath);
// Skip non-source files
if (!sourceExtensions.includes(fileExt)) {
continue;
}
// Check if it's a test file
if (testPatterns.some(pattern => pattern.test(fileName))) {
testFiles.push(filePath);
} else {
sourceFiles.push(filePath);
}
}
testCoverage.testFileCount = testFiles.length;
testCoverage.sourceFileCount = sourceFiles.length;
// Function to extract imported file names from content
const extractImportedFiles = (content: string): string[] => {
const imports: string[] = [];
// Match import patterns for different languages
// JavaScript/TypeScript imports
const jsImportMatches = content.match(/from\s+['"]([^'"]+)['"]/g);
if (jsImportMatches) {
for (const match of jsImportMatches) {
const importPath = match.replace(/from\s+['"]|['"]/g, '');
imports.push(importPath);
}
}
// Python imports
const pyImportMatches = content.match(/import\s+([a-zA-Z0-9_.]+)|from\s+([a-zA-Z0-9_.]+)\s+import/g);
if (pyImportMatches) {
for (const match of pyImportMatches) {
const parts = match.split(/\s+/);
if (parts[0] === 'import') {
imports.push(parts[1]);
} else if (parts[0] === 'from') {
imports.push(parts[1]);
}
}
}
return imports;
};
// Find which source files might be untested
const testedFiles = new Set<string>();
// Assume files are tested if they appear in imports of test files
for (const testFile of testFiles) {
if (context.fileContents.has(testFile)) {
const content = context.fileContents.get(testFile) || '';
const imports = extractImportedFiles(content);
for (const sourceFile of sourceFiles) {
const baseName = path.basename(sourceFile, path.extname(sourceFile));
if (imports.some(imp => imp.includes(baseName))) {
testedFiles.add(sourceFile);
}
}
}
}
// Files that might be untested
const untestedFiles = sourceFiles.filter(file => !testedFiles.has(file));
// Limit to reasonable number to display
testCoverage.untested = untestedFiles
.slice(0, 10)
.map(file => path.basename(file));
// Estimate coverage percentage
if (sourceFiles.length > 0) {
testCoverage.estimatedCoverage = Math.round((testedFiles.size / sourceFiles.length) * 100);
}
return testCoverage;
}
/**
* Analyze documentation quality
*/
private analyzeDocumentationQuality(context: WorkspaceContext): any {
const docQuality = {
documentationFiles: 0,
hasReadme: false,
docCommentCount: 0,
totalFunctions: 0,
estimatedDocCoverage: 0
};
// Count documentation files
let readmeContent = '';
for (const filePath of context.files) {
const fileExt = path.extname(filePath);
const fileName = path.basename(filePath);
// Check for documentation files
if (fileExt === '.md' || fileExt === '.txt' || fileName.toLowerCase() === 'readme') {
docQuality.documentationFiles++;
// Store README content for further analysis
if (fileName.toLowerCase() === 'readme.md' && context.fileContents.has(filePath)) {
readmeContent = context.fileContents.get(filePath) || '';
docQuality.hasReadme = true;
}
}
}
// Analyze code files for documentation comments
let totalDocComments = 0;
let totalFunctions = 0;
let documentedFunctions = 0;
const codeFiles = Array.from(context.fileContents.entries())
.filter(([filePath]) => {
const fileExt = path.extname(filePath);
return ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cs'].includes(fileExt);
});
for (const [filePath, content] of codeFiles) {
// Count JSDoc/TSDoc comments
const docCommentMatches = content.match(/\/\*\*[\s\S]*?\*\//g);
if (docCommentMatches) {
totalDocComments += docCommentMatches.length;
}
// Count Python docstrings
const pyDocstringMatches = content.match(/"""\s*[\s\S]*?"""/g);
if (pyDocstringMatches) {
totalDocComments += pyDocstringMatches.length;
}
// Count functions/methods
const functionMatches = content.match(/function\s+\w+\s*\(|def\s+\w+\s*\(|\w+\s*\([^)]*\)\s*{/g);
if (functionMatches) {
totalFunctions += functionMatches.length;
}
// Estimate documented functions by looking at nearby doc comments
const lines = content.split('\n');
let inDocComment = false;
let docCommentEndLine = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Check for start of doc comment
if (line.startsWith('/**') || line.startsWith('"""')) {
inDocComment = true;
continue;
}
// Check for end of doc comment
if (inDocComment && (line.endsWith('*/') || line.endsWith('"""'))) {
inDocComment = false;
docCommentEndLine = i;
continue;
}
// Check if function follows a doc comment
if (docCommentEndLine === i - 1 &&
(line.startsWith('function ') || line.startsWith('def ') || /\w+\s*\([^)]*\)\s*{/.test(line))) {
documentedFunctions++;
}
}
}
// Store analysis results
docQuality.docCommentCount = totalDocComments;
docQuality.totalFunctions = totalFunctions;
// Calculate estimated coverage
if (totalFunctions > 0) {
docQuality.estimatedDocCoverage = Math.round((documentedFunctions / totalFunctions) * 100);
} else {
// If no functions found but has README, give a minimum score
docQuality.estimatedDocCoverage = docQuality.hasReadme ? 30 : 0;
}
return docQuality;
}
/**
* Identify missing documentation
*/
private findMissingDocumentation(context: WorkspaceContext): any {
const missingDocs = {
missingReadme: false,
undocumentedFunctions: [] as string[],
undocumentedClasses: [] as string[]
};
// Check if README exists
const hasReadme = context.files.some(file => {
const fileName = path.basename(file).toLowerCase();
return fileName === 'readme.md' || fileName === 'readme';
});
missingDocs.missingReadme = !hasReadme;
// Check for undocumented code elements
const codeFiles = Array.from(context.fileContents.entries())
.filter(([filePath]) => {
const fileExt = path.extname(filePath);
return ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cs'].includes(fileExt);
});
for (const [filePath, content] of codeFiles) {
const fileName = path.basename(filePath);
const lines = content.split('\n');
// Track documented and undocumented elements
const documentedLines = new Set<number>();
// Find lines that are preceded by documentation
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// JSDoc comment
if (line.startsWith('/**')) {
// Find the end of the comment
let j = i;
while (j < lines.length && !lines[j].trim().endsWith('*/')) {
j++;
}
// Mark the line after the comment as documented
if (j < lines.length - 1) {
documentedLines.add(j + 1);
}
i = j;
continue;
}
// Python docstring
if (line.startsWith('"""')) {
// Find the end of the docstring
let j = i;
while (j < lines.length && !lines[j].trim().endsWith('"""') && j !== i) {
j++;
}
// Mark the line after the docstring as documented
if (j < lines.length - 1) {
documentedLines.add(j + 1);
}
i = j;
continue;
}
}
// Find undocumented functions and classes
for (let i = 0; i < lines.length; i++) {
if (documentedLines.has(i)) continue;
const line = lines[i].trim();
// JavaScript/TypeScript functions
if ((line.startsWith('function ') ||
line.match(/^(export|async)?\s*function\s+\w+/)) &&
!line.includes('{') && i < lines.length - 1) {
const functionName = line.replace(/^(export|async)?\s*function\s+/, '')
.split('(')[0].trim();
if (functionName && !documentedLines.has(i)) {
missingDocs.undocumentedFunctions.push(`${fileName}: ${functionName}`);
}
}
// JavaScript/TypeScript classes
if ((line.startsWith('class ') ||
line.match(/^(export)?\s*class\s+\w+/)) &&
!line.includes('{') && i < lines.length - 1) {
const className = line.replace(/^(export)?\s*class\s+/, '')
.split(' ')[0].trim();
if (className && !documentedLines.has(i)) {
missingDocs.undocumentedClasses.push(`${fileName}: ${className}`);
}
}
// Python functions
if (line.startsWith('def ')) {
const functionName = line.replace('def ', '')
.split('(')[0].trim();
if (functionName && !documentedLines.has(i)) {
missingDocs.undocumentedFunctions.push(`${fileName}: ${functionName}`);
}
}
// Python classes
if (line.startsWith('class ')) {
const className = line.replace('class ', '')
.split('(')[0].trim();
if (className && !documentedLines.has(i)) {
missingDocs.undocumentedClasses.push(`${fileName}: ${className}`);
}
}
}
}
// Limit to a reasonable number to display
missingDocs.undocumentedFunctions = missingDocs.undocumentedFunctions.slice(0, 15);
missingDocs.undocumentedClasses = missingDocs.undocumentedClasses.slice(0, 10);
return missingDocs;
}
/**
* Performs a security scan on the provided workspace context
* Identifies common security issues and vulnerabilities in code
*/
private async performSecurityScan(context: WorkspaceContext): Promise<any> {
console.log('Performing security scan...');
// Initialize security scan result
const securityScanResult = {
score: 0,
summary: '',
lastScanDate: new Date().toISOString(),
vulnerabilities: [] as any[]
};
// Common security vulnerability patterns to check for
const vulnerabilityPatterns = [
{
type: 'SQL Injection',
patterns: [
/string\s*\+\s*.+\s*\+\s*["']\s*(SELECT|INSERT|UPDATE|DELETE)/i,
/\.query\s*\(\s*["']\s*.*\$\{.*\}/i,
/executeQuery\s*\(\s*["']\s*.*\+\s*.+/i
],
severity: 'high',
recommendation: 'Use parameterized queries or prepared statements instead of string concatenation'
},
{
type: 'XSS Vulnerability',
patterns: [
/\.innerHTML\s*=\s*.+/,
/\.outerHTML\s*=\s*.+/,
/document\.write\s*\(/,
/eval\s*\(/
],
severity: 'high',
recommendation: 'Use safe DOM APIs like textContent or implement proper output encoding'
},
{
type: 'Hard-coded Credentials',
patterns: [
/const\s+(password|secret|token|key)\s*=\s*["'][^"']+["']/i,
/let\s+(password|secret|token|key)\s*=\s*["'][^"']+["']/i,
/var\s+(password|secret|token|key)\s*=\s*["'][^"']+["']/i,
/password\s*:\s*["'][^"']{6,}["']/i
],
severity: 'critical',
recommendation: 'Use environment variables or a secure configuration management system'
},
{
type: 'Insecure Cryptography',
patterns: [
/createHash\s*\(\s*["']md5["']/i,
/createHash\s*\(\s*["']sha1["']/i,
/createCipher\s*\(/i
],
severity: 'medium',
recommendation: 'Use modern cryptographic algorithms and libraries'
},
{
type: 'Insecure Cookie',
patterns: [
/document\.cookie\s*=\s*["'][^"']*(?!secure|httponly)["']/i,
/cookie\s*:\s*["'][^"']*(?!secure|httponly)["']/i,
/cookieOptions\s*=\s*\{\s*(?!.*secure.*true)(?!.*httpOnly.*true)/i
],
severity: 'medium',
recommendation: 'Use secure and httpOnly flags on cookies'
},
{
type: 'Insecure File Operations',
patterns: [
/\.\.\/|\.\.\\|\.\.[\/\\]/,
/(?:fs|require\s*\(\s*["']fs["']\))\.(?:read|write).+\.\.(?:\/|\\)/
],
severity: 'high',
recommendation: 'Validate file paths and prevent path traversal attacks'
},
{
type: 'Command Injection',
patterns: [
/exec\s*\(\s*["'].+\$\{.*\}/i,
/spawn\s*\(\s*["'].+\$\{.*\}/i,
/execSync\s*\(\s*["'].+\$\{.*\}/i
],
severity: 'critical',
recommendation: 'Avoid command execution with user input or properly validate and sanitize inputs'