codereview-aia 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/dist/analysis/static/wpPhpcsRunner.d.ts +11 -0
  2. package/dist/analysis/static/wpPhpcsRunner.js +219 -0
  3. package/dist/analysis/static/wpPhpcsRunner.js.map +1 -0
  4. package/dist/clients/implementations/openRouterClient.js +2 -2
  5. package/dist/clients/implementations/openRouterClient.js.map +1 -1
  6. package/dist/clients/openRouterClient.js +2 -2
  7. package/dist/clients/openRouterClient.js.map +1 -1
  8. package/dist/clients/utils/promptFormatter.d.ts +3 -2
  9. package/dist/clients/utils/promptFormatter.js +82 -24
  10. package/dist/clients/utils/promptFormatter.js.map +1 -1
  11. package/dist/core/ConfigurationService.d.ts +21 -0
  12. package/dist/core/ConfigurationService.js +39 -0
  13. package/dist/core/ConfigurationService.js.map +1 -1
  14. package/dist/core/handlers/FileProcessingHandler.js +5 -0
  15. package/dist/core/handlers/FileProcessingHandler.js.map +1 -1
  16. package/dist/core/reviewOrchestrator.js +61 -1
  17. package/dist/core/reviewOrchestrator.js.map +1 -1
  18. package/dist/index.d.ts +0 -1
  19. package/dist/index.js +0 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/runtime/cliEntry.js +57 -4
  22. package/dist/runtime/cliEntry.js.map +1 -1
  23. package/dist/runtime/fileCollector.d.ts +10 -1
  24. package/dist/runtime/fileCollector.js +217 -2
  25. package/dist/runtime/fileCollector.js.map +1 -1
  26. package/dist/runtime/reporting/markdownReportBuilder.d.ts +2 -0
  27. package/dist/runtime/reporting/markdownReportBuilder.js +57 -0
  28. package/dist/runtime/reporting/markdownReportBuilder.js.map +1 -1
  29. package/dist/runtime/reviewPipeline.d.ts +22 -3
  30. package/dist/runtime/reviewPipeline.js +46 -7
  31. package/dist/runtime/reviewPipeline.js.map +1 -1
  32. package/dist/runtime/runAiCodeReview.d.ts +19 -1
  33. package/dist/runtime/runAiCodeReview.js +243 -8
  34. package/dist/runtime/runAiCodeReview.js.map +1 -1
  35. package/dist/runtime/ui/RuntimeApp.js +15 -4
  36. package/dist/runtime/ui/RuntimeApp.js.map +1 -1
  37. package/dist/runtime/ui/screens/ProgressScreen.d.ts +6 -1
  38. package/dist/runtime/ui/screens/ProgressScreen.js +28 -2
  39. package/dist/runtime/ui/screens/ProgressScreen.js.map +1 -1
  40. package/dist/runtime/ui/screens/ResultsScreen.js +8 -1
  41. package/dist/runtime/ui/screens/ResultsScreen.js.map +1 -1
  42. package/dist/types/review.d.ts +60 -0
  43. package/dist/utils/detection/frameworkDetector.js +55 -0
  44. package/dist/utils/detection/frameworkDetector.js.map +1 -1
  45. package/dist/utils/promptTemplateManager.js +1 -0
  46. package/dist/utils/promptTemplateManager.js.map +1 -1
  47. package/package.json +13 -10
  48. package/.cr-aia.yml +0 -23
  49. package/.crignore +0 -0
  50. package/src/analysis/FindingsExtractor.ts +0 -431
  51. package/src/analysis/ai-detection/analyzers/BaseAnalyzer.ts +0 -267
  52. package/src/analysis/ai-detection/analyzers/DocumentationAnalyzer.ts +0 -622
  53. package/src/analysis/ai-detection/analyzers/GitHistoryAnalyzer.ts +0 -430
  54. package/src/analysis/ai-detection/core/AIDetectionEngine.ts +0 -467
  55. package/src/analysis/ai-detection/types/DetectionTypes.ts +0 -406
  56. package/src/analysis/ai-detection/utils/SubmissionConverter.ts +0 -390
  57. package/src/analysis/context/ReviewContext.ts +0 -378
  58. package/src/analysis/context/index.ts +0 -7
  59. package/src/analysis/index.ts +0 -8
  60. package/src/analysis/tokens/TokenAnalysisFormatter.ts +0 -154
  61. package/src/analysis/tokens/TokenAnalyzer.ts +0 -747
  62. package/src/analysis/tokens/index.ts +0 -8
  63. package/src/clients/base/abstractClient.ts +0 -190
  64. package/src/clients/base/httpClient.ts +0 -160
  65. package/src/clients/base/index.ts +0 -12
  66. package/src/clients/base/modelDetection.ts +0 -107
  67. package/src/clients/base/responseProcessor.ts +0 -586
  68. package/src/clients/factory/clientFactory.ts +0 -55
  69. package/src/clients/factory/index.ts +0 -8
  70. package/src/clients/implementations/index.ts +0 -8
  71. package/src/clients/implementations/openRouterClient.ts +0 -411
  72. package/src/clients/openRouterClient.ts +0 -863
  73. package/src/clients/openRouterClientWrapper.ts +0 -44
  74. package/src/clients/utils/directoryStructure.ts +0 -52
  75. package/src/clients/utils/index.ts +0 -11
  76. package/src/clients/utils/languageDetection.ts +0 -44
  77. package/src/clients/utils/promptFormatter.ts +0 -105
  78. package/src/clients/utils/promptLoader.ts +0 -53
  79. package/src/clients/utils/tokenCounter.ts +0 -297
  80. package/src/core/ApiClientSelector.ts +0 -37
  81. package/src/core/ConfigurationService.ts +0 -591
  82. package/src/core/ConsolidationService.ts +0 -423
  83. package/src/core/InteractiveDisplayManager.ts +0 -81
  84. package/src/core/OutputManager.ts +0 -275
  85. package/src/core/ReviewGenerator.ts +0 -140
  86. package/src/core/fileDiscovery.ts +0 -237
  87. package/src/core/handlers/EstimationHandler.ts +0 -104
  88. package/src/core/handlers/FileProcessingHandler.ts +0 -204
  89. package/src/core/handlers/OutputHandler.ts +0 -125
  90. package/src/core/handlers/ReviewExecutor.ts +0 -104
  91. package/src/core/reviewOrchestrator.ts +0 -333
  92. package/src/core/utils/ModelInfoUtils.ts +0 -56
  93. package/src/formatters/outputFormatter.ts +0 -62
  94. package/src/formatters/utils/IssueFormatters.ts +0 -83
  95. package/src/formatters/utils/JsonFormatter.ts +0 -77
  96. package/src/formatters/utils/MarkdownFormatters.ts +0 -609
  97. package/src/formatters/utils/MetadataFormatter.ts +0 -269
  98. package/src/formatters/utils/ModelInfoExtractor.ts +0 -115
  99. package/src/index.ts +0 -28
  100. package/src/plugins/PluginInterface.ts +0 -50
  101. package/src/plugins/PluginManager.ts +0 -126
  102. package/src/prompts/PromptManager.ts +0 -69
  103. package/src/prompts/cache/PromptCache.ts +0 -50
  104. package/src/prompts/promptText/common/variables/css-frameworks.json +0 -33
  105. package/src/prompts/promptText/common/variables/framework-versions.json +0 -45
  106. package/src/prompts/promptText/frameworks/react/comprehensive.hbs +0 -19
  107. package/src/prompts/promptText/languages/css/comprehensive.hbs +0 -18
  108. package/src/prompts/promptText/languages/generic/comprehensive.hbs +0 -20
  109. package/src/prompts/promptText/languages/html/comprehensive.hbs +0 -18
  110. package/src/prompts/promptText/languages/javascript/comprehensive.hbs +0 -18
  111. package/src/prompts/promptText/languages/python/comprehensive.hbs +0 -18
  112. package/src/prompts/promptText/languages/typescript/comprehensive.hbs +0 -18
  113. package/src/runtime/auth/service.ts +0 -58
  114. package/src/runtime/auth/session.ts +0 -103
  115. package/src/runtime/auth/types.ts +0 -11
  116. package/src/runtime/cliEntry.ts +0 -196
  117. package/src/runtime/debug/logManager.ts +0 -37
  118. package/src/runtime/errors.ts +0 -13
  119. package/src/runtime/fileCollector.ts +0 -222
  120. package/src/runtime/manifest.ts +0 -64
  121. package/src/runtime/openrouterProxy.ts +0 -45
  122. package/src/runtime/preprod/webCheck.ts +0 -104
  123. package/src/runtime/proxyConfig.ts +0 -94
  124. package/src/runtime/proxyEnvironment.ts +0 -71
  125. package/src/runtime/reportMerge.ts +0 -102
  126. package/src/runtime/reporting/markdownReportBuilder.ts +0 -138
  127. package/src/runtime/reporting/reportDataCollector.ts +0 -234
  128. package/src/runtime/reporting/summaryGenerator.ts +0 -86
  129. package/src/runtime/reviewPipeline.ts +0 -161
  130. package/src/runtime/runAiCodeReview.ts +0 -153
  131. package/src/runtime/runtimeConfig.ts +0 -5
  132. package/src/runtime/ui/Layout.tsx +0 -57
  133. package/src/runtime/ui/RuntimeApp.tsx +0 -233
  134. package/src/runtime/ui/inkModules.ts +0 -73
  135. package/src/runtime/ui/screens/AuthScreen.tsx +0 -128
  136. package/src/runtime/ui/screens/ModeSelection.tsx +0 -185
  137. package/src/runtime/ui/screens/ProgressScreen.tsx +0 -62
  138. package/src/runtime/ui/screens/ResultsScreen.tsx +0 -83
  139. package/src/strategies/ArchitecturalReviewStrategy.ts +0 -54
  140. package/src/strategies/CodingTestReviewStrategy.ts +0 -920
  141. package/src/strategies/ConsolidatedReviewStrategy.ts +0 -59
  142. package/src/strategies/ExtractPatternsReviewStrategy.ts +0 -64
  143. package/src/strategies/MultiPassReviewStrategy.ts +0 -785
  144. package/src/strategies/ReviewStrategy.ts +0 -64
  145. package/src/strategies/StrategyFactory.ts +0 -79
  146. package/src/strategies/index.ts +0 -14
  147. package/src/tokenizers/baseTokenizer.ts +0 -61
  148. package/src/tokenizers/gptTokenizer.ts +0 -27
  149. package/src/tokenizers/index.ts +0 -8
  150. package/src/types/apiResponses.ts +0 -40
  151. package/src/types/cli.ts +0 -24
  152. package/src/types/common.ts +0 -39
  153. package/src/types/configuration.ts +0 -201
  154. package/src/types/handlebars.d.ts +0 -5
  155. package/src/types/patch.d.ts +0 -25
  156. package/src/types/review.ts +0 -294
  157. package/src/types/reviewContext.d.ts +0 -65
  158. package/src/types/reviewSchema.ts +0 -181
  159. package/src/types/structuredReview.ts +0 -167
  160. package/src/types/tokenAnalysis.ts +0 -56
  161. package/src/utils/FileReader.ts +0 -93
  162. package/src/utils/FileWriter.ts +0 -76
  163. package/src/utils/PathGenerator.ts +0 -97
  164. package/src/utils/api/apiUtils.ts +0 -14
  165. package/src/utils/api/index.ts +0 -1
  166. package/src/utils/apiErrorHandler.ts +0 -287
  167. package/src/utils/ciDataCollector.ts +0 -252
  168. package/src/utils/codingTestConfigLoader.ts +0 -466
  169. package/src/utils/dependencies/aiDependencyAnalyzer.ts +0 -454
  170. package/src/utils/detection/frameworkDetector.ts +0 -879
  171. package/src/utils/detection/index.ts +0 -10
  172. package/src/utils/detection/projectTypeDetector.ts +0 -518
  173. package/src/utils/diagramGenerator.ts +0 -206
  174. package/src/utils/errorLogger.ts +0 -60
  175. package/src/utils/estimationUtils.ts +0 -407
  176. package/src/utils/fileFilters.ts +0 -373
  177. package/src/utils/fileSystem.ts +0 -57
  178. package/src/utils/index.ts +0 -36
  179. package/src/utils/logger.ts +0 -290
  180. package/src/utils/pathValidator.ts +0 -98
  181. package/src/utils/priorityFilter.ts +0 -59
  182. package/src/utils/projectDocs.ts +0 -189
  183. package/src/utils/promptPaths.ts +0 -29
  184. package/src/utils/promptTemplateManager.ts +0 -157
  185. package/src/utils/review/consolidateReview.ts +0 -553
  186. package/src/utils/review/fixDisplay.ts +0 -100
  187. package/src/utils/review/fixImplementation.ts +0 -61
  188. package/src/utils/review/index.ts +0 -36
  189. package/src/utils/review/interactiveProcessing.ts +0 -294
  190. package/src/utils/review/progressTracker.ts +0 -296
  191. package/src/utils/review/reviewExtraction.ts +0 -382
  192. package/src/utils/review/types.ts +0 -46
  193. package/src/utils/reviewActionHandler.ts +0 -18
  194. package/src/utils/reviewParser.ts +0 -253
  195. package/src/utils/sanitizer.ts +0 -238
  196. package/src/utils/smartFileSelector.ts +0 -255
  197. package/src/utils/templateLoader.ts +0 -514
  198. package/src/utils/treeGenerator.ts +0 -153
  199. package/tsconfig.build.json +0 -14
  200. package/tsconfig.json +0 -59
@@ -1,431 +0,0 @@
1
- /**
2
- * @fileoverview Findings Extractor for Code Reviews
3
- *
4
- * This service extracts, categorizes, and analyzes findings from code review
5
- * results. It provides utilities for grading, recommendation generation,
6
- * and finding prioritization.
7
- */
8
-
9
- import logger from '../utils/logger';
10
-
11
- /**
12
- * Categorized findings from code review
13
- */
14
- export interface CategorizedFindings {
15
- high: Set<string>;
16
- medium: Set<string>;
17
- low: Set<string>;
18
- }
19
-
20
- /**
21
- * Grade information with justification
22
- */
23
- export interface GradeInfo {
24
- grade: string;
25
- justification: string;
26
- }
27
-
28
- /**
29
- * Service for extracting and analyzing findings from code reviews
30
- */
31
- export class FindingsExtractor {
32
- /**
33
- * Extract findings from review passes
34
- * @param passes Array of review results with content
35
- * @returns Categorized findings
36
- */
37
- extractFindingsFromPasses(passes: Array<{ content: string }>): CategorizedFindings {
38
- const highPriorityFindings = new Set<string>();
39
- const mediumPriorityFindings = new Set<string>();
40
- const lowPriorityFindings = new Set<string>();
41
-
42
- for (const pass of passes) {
43
- if (!pass.content) continue;
44
-
45
- const issueTexts = this.extractIssueTexts(pass.content);
46
-
47
- for (const issue of issueTexts) {
48
- const lowerIssue = issue.toLowerCase();
49
-
50
- // Categorize by priority keywords
51
- if (this.isHighPriority(lowerIssue)) {
52
- highPriorityFindings.add(issue);
53
- } else if (this.isMediumPriority(lowerIssue)) {
54
- mediumPriorityFindings.add(issue);
55
- } else {
56
- lowPriorityFindings.add(issue);
57
- }
58
- }
59
- }
60
-
61
- logger.debug(
62
- `Extracted findings: ${highPriorityFindings.size} high, ${mediumPriorityFindings.size} medium, ${lowPriorityFindings.size} low`,
63
- );
64
-
65
- return {
66
- high: highPriorityFindings,
67
- medium: mediumPriorityFindings,
68
- low: lowPriorityFindings,
69
- };
70
- }
71
-
72
- /**
73
- * Extract individual issue texts from content
74
- * @param content Review content
75
- * @returns Array of issue descriptions
76
- */
77
- extractIssueTexts(content: string): string[] {
78
- const issues: string[] = [];
79
-
80
- // Extract bullet points and numbered items
81
- const bulletRegex = /^[\s]*[-*•]\s+(.+)$/gm;
82
- const numberedRegex = /^[\s]*\d+\.\s+(.+)$/gm;
83
- const dashRegex = /^[\s]*-\s+(.+)$/gm;
84
-
85
- let match;
86
-
87
- // Extract bullet points
88
- while ((match = bulletRegex.exec(content)) !== null) {
89
- const issue = match[1].trim();
90
- if (issue.length > 10) {
91
- // Filter out very short items
92
- issues.push(issue);
93
- }
94
- }
95
-
96
- // Extract numbered items
97
- while ((match = numberedRegex.exec(content)) !== null) {
98
- const issue = match[1].trim();
99
- if (issue.length > 10) {
100
- issues.push(issue);
101
- }
102
- }
103
-
104
- // Extract dash items (alternative format)
105
- while ((match = dashRegex.exec(content)) !== null) {
106
- const issue = match[1].trim();
107
- if (issue.length > 10) {
108
- issues.push(issue);
109
- }
110
- }
111
-
112
- // Remove duplicates
113
- return [...new Set(issues)];
114
- }
115
-
116
- /**
117
- * Check if an issue is high priority
118
- * @param issue Issue text (lowercase)
119
- * @returns True if high priority
120
- */
121
- private isHighPriority(issue: string): boolean {
122
- const highPriorityKeywords = [
123
- 'security',
124
- 'vulnerability',
125
- 'critical',
126
- 'error',
127
- 'bug',
128
- 'crash',
129
- 'memory leak',
130
- 'sql injection',
131
- 'xss',
132
- 'csrf',
133
- 'injection',
134
- 'authentication',
135
- 'authorization',
136
- 'privilege escalation',
137
- 'data breach',
138
- 'sensitive data',
139
- 'password',
140
- 'token',
141
- 'deadlock',
142
- 'race condition',
143
- 'null pointer',
144
- 'buffer overflow',
145
- ];
146
- return highPriorityKeywords.some((keyword) => issue.includes(keyword));
147
- }
148
-
149
- /**
150
- * Check if an issue is medium priority
151
- * @param issue Issue text (lowercase)
152
- * @returns True if medium priority
153
- */
154
- private isMediumPriority(issue: string): boolean {
155
- const mediumPriorityKeywords = [
156
- 'warning',
157
- 'deprecated',
158
- 'inefficient',
159
- 'refactor',
160
- 'improve',
161
- 'optimization',
162
- 'maintainability',
163
- 'readability',
164
- 'complexity',
165
- 'duplication',
166
- 'coupling',
167
- 'cohesion',
168
- 'design pattern',
169
- 'architecture',
170
- 'structure',
171
- 'organization',
172
- 'naming',
173
- 'documentation',
174
- 'comment',
175
- 'test coverage',
176
- 'error handling',
177
- ];
178
- return mediumPriorityKeywords.some((keyword) => issue.includes(keyword));
179
- }
180
-
181
- /**
182
- * Calculate grade based on findings for a specific category
183
- * @param findings Categorized findings
184
- * @param category Category name (for logging)
185
- * @returns Grade information
186
- */
187
- calculateGrade(findings: CategorizedFindings, category: string): GradeInfo {
188
- const totalIssues = findings.high.size + findings.medium.size + findings.low.size;
189
-
190
- let grade: string;
191
- let justification: string;
192
-
193
- if (findings.high.size > 5) {
194
- grade = 'D';
195
- justification = `Multiple critical issues (${findings.high.size}) require immediate attention`;
196
- } else if (findings.high.size > 2) {
197
- grade = 'C';
198
- justification = `Several critical issues (${findings.high.size}) need to be addressed`;
199
- } else if (findings.high.size > 0) {
200
- grade = 'C+';
201
- justification = `Some critical issues (${findings.high.size}) present`;
202
- } else if (findings.medium.size > 10) {
203
- grade = 'C+';
204
- justification = `Many medium-priority issues (${findings.medium.size}) affect code quality`;
205
- } else if (findings.medium.size > 5) {
206
- grade = 'B';
207
- justification = `Several medium-priority issues (${findings.medium.size}) could be improved`;
208
- } else if (findings.medium.size > 2) {
209
- grade = 'B+';
210
- justification = `Some medium-priority issues (${findings.medium.size}) noted`;
211
- } else if (totalIssues > 5) {
212
- grade = 'A-';
213
- justification = `Minor issues (${totalIssues}) but overall good quality`;
214
- } else if (totalIssues > 0) {
215
- grade = 'A';
216
- justification = `Very few issues (${totalIssues}), high quality code`;
217
- } else {
218
- grade = 'A+';
219
- justification = 'Excellent code quality with no significant issues';
220
- }
221
-
222
- logger.debug(`Grade for ${category}: ${grade} (${justification})`);
223
- return { grade, justification };
224
- }
225
-
226
- /**
227
- * Calculate overall grade based on findings
228
- * @param findings Categorized findings
229
- * @returns Overall grade string
230
- */
231
- calculateOverallGrade(findings: CategorizedFindings): string {
232
- const gradeInfo = this.calculateGrade(findings, 'overall');
233
- return gradeInfo.grade;
234
- }
235
-
236
- /**
237
- * Get justification for grade
238
- * @param findings Categorized findings
239
- * @param category Category name
240
- * @returns Grade justification string
241
- */
242
- getGradeJustification(findings: CategorizedFindings, category: string): string {
243
- const gradeInfo = this.calculateGrade(findings, category);
244
- return gradeInfo.justification;
245
- }
246
-
247
- /**
248
- * Generate recommendations based on findings
249
- * @param findings Categorized findings
250
- * @param hasErrors Whether there are compilation errors
251
- * @returns Array of recommendation strings
252
- */
253
- generateRecommendations(findings: CategorizedFindings, hasErrors: boolean): string[] {
254
- const recommendations: string[] = [];
255
-
256
- if (hasErrors) {
257
- recommendations.push('Fix compilation errors before proceeding with other improvements');
258
- }
259
-
260
- if (findings.high.size > 0) {
261
- recommendations.push(
262
- `Address ${findings.high.size} high-priority security and critical issues immediately`,
263
- );
264
-
265
- if (findings.high.size > 3) {
266
- recommendations.push(
267
- 'Consider conducting a security audit given the number of critical issues',
268
- );
269
- }
270
- }
271
-
272
- if (findings.medium.size > 8) {
273
- recommendations.push(
274
- `Review and address ${findings.medium.size} medium-priority maintainability issues`,
275
- );
276
- recommendations.push('Consider refactoring to improve code structure and maintainability');
277
- } else if (findings.medium.size > 3) {
278
- recommendations.push(
279
- `Address ${findings.medium.size} medium-priority issues to improve code quality`,
280
- );
281
- }
282
-
283
- if (findings.low.size > 15) {
284
- recommendations.push(
285
- `Consider addressing ${findings.low.size} low-priority style and minor issues`,
286
- );
287
- recommendations.push('Implement automated linting and formatting tools');
288
- } else if (findings.low.size > 8) {
289
- recommendations.push(`Review ${findings.low.size} low-priority issues when time permits`);
290
- }
291
-
292
- // Add positive recommendations for good code
293
- if (findings.high.size === 0 && findings.medium.size < 3) {
294
- recommendations.push('Code quality is good. Continue following current best practices.');
295
-
296
- if (findings.low.size === 0) {
297
- recommendations.push(
298
- 'Excellent code quality. Consider sharing best practices with the team.',
299
- );
300
- }
301
- }
302
-
303
- // Add specific recommendations based on issue types
304
- if (this.hasSecurityIssues(findings)) {
305
- recommendations.push('Implement security code review process and security testing');
306
- }
307
-
308
- if (this.hasPerformanceIssues(findings)) {
309
- recommendations.push('Consider performance profiling and optimization');
310
- }
311
-
312
- if (this.hasTestingIssues(findings)) {
313
- recommendations.push('Improve test coverage and add more comprehensive tests');
314
- }
315
-
316
- return recommendations;
317
- }
318
-
319
- /**
320
- * Check if findings contain security-related issues
321
- * @param findings Categorized findings
322
- * @returns True if security issues are present
323
- */
324
- private hasSecurityIssues(findings: CategorizedFindings): boolean {
325
- const allFindings = [...findings.high, ...findings.medium, ...findings.low];
326
- const securityKeywords = [
327
- 'security',
328
- 'vulnerability',
329
- 'injection',
330
- 'xss',
331
- 'csrf',
332
- 'authentication',
333
- ];
334
-
335
- return allFindings.some((finding) =>
336
- securityKeywords.some((keyword) => finding.toLowerCase().includes(keyword)),
337
- );
338
- }
339
-
340
- /**
341
- * Check if findings contain performance-related issues
342
- * @param findings Categorized findings
343
- * @returns True if performance issues are present
344
- */
345
- private hasPerformanceIssues(findings: CategorizedFindings): boolean {
346
- const allFindings = [...findings.high, ...findings.medium, ...findings.low];
347
- const performanceKeywords = [
348
- 'performance',
349
- 'slow',
350
- 'inefficient',
351
- 'optimization',
352
- 'memory',
353
- 'cpu',
354
- ];
355
-
356
- return allFindings.some((finding) =>
357
- performanceKeywords.some((keyword) => finding.toLowerCase().includes(keyword)),
358
- );
359
- }
360
-
361
- /**
362
- * Check if findings contain testing-related issues
363
- * @param findings Categorized findings
364
- * @returns True if testing issues are present
365
- */
366
- private hasTestingIssues(findings: CategorizedFindings): boolean {
367
- const allFindings = [...findings.high, ...findings.medium, ...findings.low];
368
- const testingKeywords = [
369
- 'test',
370
- 'coverage',
371
- 'mock',
372
- 'assertion',
373
- 'unit test',
374
- 'integration test',
375
- ];
376
-
377
- return allFindings.some((finding) =>
378
- testingKeywords.some((keyword) => finding.toLowerCase().includes(keyword)),
379
- );
380
- }
381
-
382
- /**
383
- * Format findings for display in reports
384
- * @param findings Categorized findings
385
- * @param maxPerCategory Maximum items to show per category
386
- * @returns Formatted findings string
387
- */
388
- formatFindings(findings: CategorizedFindings, maxPerCategory = 5): string {
389
- const sections: string[] = [];
390
-
391
- if (findings.high.size > 0) {
392
- sections.push(`**High Priority (${findings.high.size}):**`);
393
- sections.push(
394
- ...Array.from(findings.high)
395
- .slice(0, maxPerCategory)
396
- .map((f) => `- ${f}`),
397
- );
398
- if (findings.high.size > maxPerCategory) {
399
- sections.push(`- ... and ${findings.high.size - maxPerCategory} more`);
400
- }
401
- sections.push('');
402
- }
403
-
404
- if (findings.medium.size > 0) {
405
- sections.push(`**Medium Priority (${findings.medium.size}):**`);
406
- sections.push(
407
- ...Array.from(findings.medium)
408
- .slice(0, maxPerCategory)
409
- .map((f) => `- ${f}`),
410
- );
411
- if (findings.medium.size > maxPerCategory) {
412
- sections.push(`- ... and ${findings.medium.size - maxPerCategory} more`);
413
- }
414
- sections.push('');
415
- }
416
-
417
- if (findings.low.size > 0) {
418
- sections.push(`**Low Priority (${findings.low.size}):**`);
419
- sections.push(
420
- ...Array.from(findings.low)
421
- .slice(0, Math.min(maxPerCategory, 3))
422
- .map((f) => `- ${f}`),
423
- );
424
- if (findings.low.size > 3) {
425
- sections.push(`- ... and ${findings.low.size - 3} more`);
426
- }
427
- }
428
-
429
- return sections.join('\n');
430
- }
431
- }
@@ -1,267 +0,0 @@
1
- /**
2
- * @fileoverview Base analyzer class for AI detection patterns.
3
- *
4
- * This module provides the abstract base class that all specific analyzers extend,
5
- * ensuring consistent interface and common functionality across different analysis types.
6
- */
7
-
8
- import type {
9
- CodeSubmission,
10
- DetectedPattern,
11
- DetectionConfig,
12
- PatternDetectionResult,
13
- } from '../types/DetectionTypes';
14
-
15
- /**
16
- * Abstract base class for all AI detection analyzers
17
- */
18
- export abstract class BaseAnalyzer {
19
- protected config: DetectionConfig;
20
- protected startTime = 0;
21
-
22
- /**
23
- * Create a new base analyzer
24
- * @param config Detection configuration
25
- */
26
- constructor(config: DetectionConfig) {
27
- this.config = config;
28
- }
29
-
30
- /**
31
- * Analyze the submission for AI-generated patterns
32
- * @param submission Code submission to analyze
33
- * @returns Analysis result specific to this analyzer
34
- */
35
- abstract analyze(submission: CodeSubmission): Promise<any>;
36
-
37
- /**
38
- * Get the analyzer name
39
- * @returns Analyzer identifier
40
- */
41
- abstract getAnalyzerName(): string;
42
-
43
- /**
44
- * Check if this analyzer is enabled in configuration
45
- * @returns True if analyzer should run
46
- */
47
- isEnabled(): boolean {
48
- return this.config.enabledAnalyzers.includes(this.getAnalyzerName() as any);
49
- }
50
-
51
- /**
52
- * Start timing analysis
53
- */
54
- protected startTimer(): void {
55
- this.startTime = Date.now();
56
- }
57
-
58
- /**
59
- * Get elapsed time since timer start
60
- * @returns Elapsed time in milliseconds
61
- */
62
- protected getElapsedTime(): number {
63
- return Date.now() - this.startTime;
64
- }
65
-
66
- /**
67
- * Create a detected pattern object
68
- * @param id Pattern identifier
69
- * @param name Human-readable name
70
- * @param confidence Confidence level
71
- * @param score Numerical score
72
- * @param description Pattern description
73
- * @param evidenceData Supporting evidence
74
- * @returns Detected pattern object
75
- */
76
- protected createDetectedPattern(
77
- id: string,
78
- name: string,
79
- confidence: 'high' | 'medium' | 'low',
80
- score: number,
81
- description: string,
82
- evidenceData: Record<string, any>,
83
- ): DetectedPattern {
84
- return {
85
- id,
86
- name,
87
- confidence,
88
- score: Math.min(1.0, Math.max(0.0, score)), // Clamp between 0 and 1
89
- evidence: {
90
- type: this.getAnalyzerName() as any,
91
- data: evidenceData,
92
- context: `Detected by ${this.getAnalyzerName()} analyzer`,
93
- },
94
- description,
95
- };
96
- }
97
-
98
- /**
99
- * Create a pattern detection result
100
- * @param detected Whether pattern was detected
101
- * @param score Confidence score
102
- * @param evidence Supporting evidence
103
- * @returns Pattern detection result
104
- */
105
- protected createPatternResult(
106
- detected: boolean,
107
- score: number,
108
- evidence?: Record<string, any>,
109
- ): PatternDetectionResult {
110
- return {
111
- detected,
112
- score: Math.min(1.0, Math.max(0.0, score)),
113
- evidence,
114
- };
115
- }
116
-
117
- /**
118
- * Calculate uniformity of a numeric array
119
- * Used for detecting suspiciously uniform patterns in code
120
- * @param values Array of numeric values
121
- * @returns Uniformity score from 0.0 to 1.0 (higher = more uniform)
122
- */
123
- protected calculateUniformity(values: number[]): number {
124
- if (values.length < 2) return 0;
125
-
126
- const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
127
- const variance = values.reduce((sum, val) => sum + (val - mean) ** 2, 0) / values.length;
128
- const standardDeviation = Math.sqrt(variance);
129
-
130
- // Convert to uniformity score (inverse of coefficient of variation)
131
- if (mean === 0) return 1; // All values are 0, perfectly uniform
132
- const coefficientOfVariation = standardDeviation / mean;
133
-
134
- // Return uniformity score (higher = more uniform)
135
- return Math.max(0, 1 - Math.min(1, coefficientOfVariation));
136
- }
137
-
138
- /**
139
- * Calculate variance of a numeric array
140
- * @param values Array of numeric values
141
- * @param mean Pre-calculated mean (optional)
142
- * @returns Variance value
143
- */
144
- protected calculateVariance(values: number[], mean?: number): number {
145
- if (values.length < 2) return 0;
146
-
147
- const avgValue = mean ?? values.reduce((sum, val) => sum + val, 0) / values.length;
148
- return values.reduce((sum, val) => sum + (val - avgValue) ** 2, 0) / values.length;
149
- }
150
-
151
- /**
152
- * Extract sections from markdown or text content
153
- * @param content Text content to analyze
154
- * @returns Array of section headers found
155
- */
156
- protected extractSections(content: string): string[] {
157
- const sections: string[] = [];
158
- const lines = content.split('\n');
159
-
160
- for (const line of lines) {
161
- const trimmed = line.trim();
162
-
163
- // Markdown headers
164
- if (trimmed.startsWith('#')) {
165
- const headerText = trimmed.replace(/^#+\s*/, '').replace(/\s*#+\s*$/, '');
166
- if (headerText) {
167
- sections.push(headerText);
168
- }
169
- }
170
-
171
- // Underlined headers (=== or ---)
172
- else if (trimmed.match(/^[=-]{3,}$/)) {
173
- const prevLineIdx = lines.indexOf(line) - 1;
174
- if (prevLineIdx >= 0) {
175
- const prevLine = lines[prevLineIdx].trim();
176
- if (prevLine && !prevLine.startsWith('#')) {
177
- sections.push(prevLine);
178
- }
179
- }
180
- }
181
- }
182
-
183
- return sections;
184
- }
185
-
186
- /**
187
- * Count badges in markdown content
188
- * @param content Markdown content
189
- * @returns Number of badges found
190
- */
191
- protected countBadges(content: string): number {
192
- // Common badge patterns
193
- const badgePatterns = [
194
- /!\[.*?\]\(https:\/\/img\.shields\.io/g,
195
- /!\[.*?\]\(https:\/\/badge\.fury\.io/g,
196
- /!\[.*?\]\(https:\/\/travis-ci/g,
197
- /!\[.*?\]\(https:\/\/ci\.appveyor/g,
198
- /!\[.*?\]\(https:\/\/codecov\.io/g,
199
- /!\[.*?\]\(https:\/\/coveralls\.io/g,
200
- ];
201
-
202
- let badgeCount = 0;
203
- for (const pattern of badgePatterns) {
204
- const matches = content.match(pattern);
205
- if (matches) {
206
- badgeCount += matches.length;
207
- }
208
- }
209
-
210
- return badgeCount;
211
- }
212
-
213
- /**
214
- * Count generic phrases that suggest AI generation
215
- * @param content Text content to analyze
216
- * @returns Number of generic phrases found
217
- */
218
- protected countGenericPhrases(content: string): number {
219
- const genericPhrases = [
220
- /this project provides/gi,
221
- /easy to use/gi,
222
- /getting started/gi,
223
- /simply install/gi,
224
- /contributions are welcome/gi,
225
- /feel free to/gi,
226
- /comprehensive solution/gi,
227
- /powerful and flexible/gi,
228
- ];
229
-
230
- let phraseCount = 0;
231
- for (const pattern of genericPhrases) {
232
- const matches = content.match(pattern);
233
- if (matches) {
234
- phraseCount += matches.length;
235
- }
236
- }
237
-
238
- return phraseCount;
239
- }
240
-
241
- /**
242
- * Validate that a score is within valid range
243
- * @param score Score to validate
244
- * @returns Clamped score between 0.0 and 1.0
245
- */
246
- protected validateScore(score: number): number {
247
- return Math.min(1.0, Math.max(0.0, score));
248
- }
249
-
250
- /**
251
- * Check if analysis should timeout
252
- * @returns True if analysis has exceeded time limit
253
- */
254
- protected shouldTimeout(): boolean {
255
- return this.getElapsedTime() > this.config.maxAnalysisTime;
256
- }
257
-
258
- /**
259
- * Create timeout error
260
- * @returns Error object for timeout
261
- */
262
- protected createTimeoutError(): Error {
263
- return new Error(
264
- `${this.getAnalyzerName()} analysis timed out after ${this.config.maxAnalysisTime}ms`,
265
- );
266
- }
267
- }