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,104 +0,0 @@
1
- /**
2
- * @fileoverview Token and cost estimation handler for code review
3
- *
4
- * This module handles token usage estimation and cost analysis for code review
5
- * using the TokenAnalyzer plus legacy fallbacks.
6
- */
7
-
8
- import type { ReviewOptions } from '../../types/review';
9
- import { estimateFromFilePaths } from '../../utils/estimationUtils';
10
- import logger from '../../utils/logger';
11
- import type { FileInfo } from '../fileDiscovery';
12
- import { getProviderDisplayInfo } from '../utils/ModelInfoUtils';
13
-
14
- /**
15
- * Perform token usage and cost estimation for review
16
- *
17
- * @param fileInfos Array of file information objects
18
- * @param filesToReview Array of file paths
19
- * @param options Review options
20
- * @param modelName Model name to use for estimation
21
- * @returns Promise that resolves when estimation is complete
22
- */
23
- export async function performEstimation(
24
- fileInfos: FileInfo[],
25
- filesToReview: string[],
26
- options: ReviewOptions,
27
- modelName: string,
28
- ): Promise<void> {
29
- logger.info('Calculating token usage and cost estimates...');
30
-
31
- try {
32
- // Ensure we have at least some files to analyze
33
- if (fileInfos.length === 0) {
34
- throw new Error(
35
- 'No files could be read for review. Please check file permissions and paths.',
36
- );
37
- }
38
-
39
- // Use the new TokenAnalyzer for more comprehensive analysis
40
- const { TokenAnalyzer } = await import('../../analysis/tokens');
41
- const { estimateMultiPassReviewCost } = await import('../../utils/estimationUtils');
42
-
43
- const tokenAnalysisOptions = {
44
- reviewType: options.type,
45
- modelName: modelName,
46
- contextMaintenanceFactor: options.contextMaintenanceFactor || 0.15,
47
- forceSinglePass: options.forceSinglePass,
48
- batchTokenLimit: options.batchTokenLimit,
49
- };
50
-
51
- const tokenAnalysis = TokenAnalyzer.analyzeFiles(fileInfos, tokenAnalysisOptions);
52
-
53
- // Get cost estimate based on token analysis
54
- const costEstimation = await estimateMultiPassReviewCost(fileInfos, options.type, modelName, {
55
- passCount: tokenAnalysis.chunkingRecommendation.chunkingRecommended
56
- ? tokenAnalysis.estimatedPassesNeeded
57
- : 1,
58
- contextMaintenanceFactor: tokenAnalysisOptions.contextMaintenanceFactor,
59
- });
60
-
61
- // Get provider and model information
62
- const providerInfo = getProviderDisplayInfo(modelName);
63
-
64
- // Display a summary without file details
65
- logger.info(
66
- `\n=== Token Usage and Cost Estimation ===\n\nProvider: ${providerInfo.provider}\nModel: ${providerInfo.model}\nFiles: ${tokenAnalysis.fileCount} (${(tokenAnalysis.totalSizeInBytes / 1024 / 1024).toFixed(2)} MB total)\n\nToken Information:\n Input Tokens: ${costEstimation.inputTokens.toLocaleString()}\n Estimated Output Tokens: ${costEstimation.outputTokens.toLocaleString()}\n Total Tokens: ${costEstimation.totalTokens.toLocaleString()}\n Context Window Size: ${tokenAnalysis.contextWindowSize.toLocaleString()}\n Context Utilization: ${((tokenAnalysis.estimatedTotalTokens / tokenAnalysis.contextWindowSize) * 100).toFixed(2)}%\n\n${
67
- tokenAnalysis.chunkingRecommendation.chunkingRecommended
68
- ? `Multi-Pass Analysis:\n Chunking Required: Yes\n Reason: ${tokenAnalysis.chunkingRecommendation.reason || 'Content exceeds context window'}\n Estimated Passes: ${tokenAnalysis.estimatedPassesNeeded}`
69
- : `Multi-Pass Analysis:\n Chunking Required: No\n Reason: ${tokenAnalysis.chunkingRecommendation.reason || 'Content fits within context window'}`
70
- }\n\nEstimated Cost: ${costEstimation.formattedCost || 'Unable to estimate cost'}\n\nNote: This is an estimate based on approximate token counts and may vary\n based on the actual content and model behavior.\n`,
71
- );
72
-
73
- // If chunking is recommended, inform the user that it will be automatic
74
- if (tokenAnalysis.chunkingRecommendation.chunkingRecommended) {
75
- logger.info(
76
- '\nImportant: Multi-pass review will be automatically enabled when needed. No flag required.',
77
- );
78
-
79
- // If forceSinglePass is enabled, inform the user
80
- if (options.forceSinglePass) {
81
- logger.info(
82
- '\nNote: --force-single-pass is enabled, which will override the chunking recommendation.',
83
- );
84
- logger.info(
85
- " This may result in token limit errors if the content exceeds the model's context window.",
86
- );
87
- }
88
- }
89
- } catch (_error) {
90
- // Fall back to the legacy estimator if TokenAnalyzer fails
91
- logger.warn('Advanced token analysis failed, falling back to basic estimation');
92
-
93
- // Estimate token usage and cost using the legacy estimator
94
- const estimation = await estimateFromFilePaths(filesToReview, options.type, modelName);
95
-
96
- // Get provider and model information
97
- const providerInfo = getProviderDisplayInfo(modelName);
98
-
99
- // Display the estimation results without file details
100
- logger.info(
101
- `\n=== Token Usage and Cost Estimation ===\n\nReview Type: ${options.type}\nProvider: ${providerInfo.provider}\nModel: ${providerInfo.model}\nFiles: ${estimation.fileCount} (${(estimation.totalFileSize / 1024 / 1024).toFixed(2)} MB total)\n\nToken Usage:\n Input Tokens: ${estimation.inputTokens.toLocaleString()}\n Estimated Output Tokens: ${estimation.outputTokens.toLocaleString()}\n Total Tokens: ${estimation.totalTokens.toLocaleString()}\n\nEstimated Cost: ${estimation.formattedCost}\n\nNote: This is an estimate based on approximate token counts and may vary\n based on the actual content and model behavior.\n`,
102
- );
103
- }
104
- }
@@ -1,204 +0,0 @@
1
- /**
2
- * @fileoverview File processing handler for code review
3
- *
4
- * This module handles file discovery, content reading, and error processing
5
- * for code review operations.
6
- */
7
-
8
- import type { ReviewOptions } from '../../types/review';
9
- import logger from '../../utils/logger';
10
- import { discoverFiles, type FileInfo, readFilesContent } from '../fileDiscovery';
11
-
12
- /**
13
- * Discover files for review based on target path and options
14
- *
15
- * @param target Path to file or directory to review
16
- * @param projectPath Current working directory
17
- * @param options Review options
18
- * @returns Array of file paths to review
19
- */
20
- export async function discoverFilesForReview(
21
- target: string,
22
- projectPath: string,
23
- options: ReviewOptions,
24
- ): Promise<string[]> {
25
- // Ensure target is defined with a default of "." for current directory
26
- const effectiveTarget = target || '.';
27
-
28
- try {
29
- const filesToReview = await discoverFiles(effectiveTarget, projectPath, options.includeTests);
30
-
31
- // Log the number of files discovered
32
- logger.info(`Discovered ${filesToReview.length} files to review`);
33
-
34
- if (filesToReview.length === 0) {
35
- logger.warn(`No files found for review in ${effectiveTarget}`);
36
- logger.info('This could be due to:');
37
- logger.info('1. The path does not exist or is not accessible');
38
- logger.info('2. All files are excluded by .gitignore patterns');
39
- logger.info('3. There are no supported file types in the specified path');
40
-
41
- if (!options.includeTests) {
42
- logger.info('4. Test files are excluded by default. Use --include-tests to include them');
43
- }
44
- }
45
-
46
- // In debug mode, list the first few files discovered
47
- if (options.debug && filesToReview.length > 0) {
48
- const maxFilesToLog = 10;
49
- logger.debug(`First ${Math.min(filesToReview.length, maxFilesToLog)} files to review:`);
50
- for (let i = 0; i < Math.min(filesToReview.length, maxFilesToLog); i++) {
51
- logger.debug(` - ${filesToReview[i]}`);
52
- }
53
-
54
- if (filesToReview.length > maxFilesToLog) {
55
- logger.debug(` ... and ${filesToReview.length - maxFilesToLog} more files`);
56
- }
57
- }
58
-
59
- return filesToReview;
60
- } catch (error) {
61
- // Handle file discovery errors
62
- logger.error(
63
- `Failed to discover files for review: ${
64
- error instanceof Error ? error.message : String(error)
65
- }`,
66
- );
67
-
68
- if (error instanceof Error && error.stack) {
69
- logger.debug(`Error stack trace: ${error.stack}`);
70
- }
71
-
72
- throw new Error(
73
- `Could not discover files to review in ${effectiveTarget}. Please verify the path exists and is accessible.`,
74
- );
75
- }
76
- }
77
-
78
- /**
79
- * Read content of discovered files
80
- *
81
- * @param filesToReview Array of file paths to read
82
- * @param projectPath Current working directory
83
- * @returns Object containing file infos and any errors encountered
84
- */
85
- export async function readFilesForReview(
86
- filesToReview: string[],
87
- projectPath: string,
88
- ): Promise<{ fileInfos: FileInfo[]; errors: Array<{ path: string; error: string }> }> {
89
- try {
90
- logger.info('Reading file contents...');
91
- const result = await readFilesContent(filesToReview, projectPath);
92
-
93
- // Log statistics about the read operation
94
- logger.info(
95
- `Successfully read ${result.fileInfos.length} out of ${filesToReview.length} files`,
96
- );
97
-
98
- // If we have errors reading files, report them but continue
99
- if (result.errors.length > 0) {
100
- logger.warn(`Failed to read ${result.errors.length} file(s):`);
101
-
102
- // Log the first 10 errors
103
- const maxErrorsToLog = 10;
104
- result.errors.slice(0, maxErrorsToLog).forEach((error) => {
105
- logger.warn(` ${error.path}: ${error.error}`);
106
- });
107
-
108
- // If there are more errors, just mention the count
109
- if (result.errors.length > maxErrorsToLog) {
110
- logger.warn(` ... and ${result.errors.length - maxErrorsToLog} more errors`);
111
- }
112
- }
113
-
114
- // Ensure we have at least some files to review
115
- if (result.fileInfos.length === 0) {
116
- const errorMessage = 'No files could be read for review.';
117
- logger.error(errorMessage);
118
-
119
- // Provide more detailed guidance based on the errors
120
- if (result.errors.length > 0) {
121
- logger.error('Errors encountered while reading files:');
122
- const commonErrorPatterns = {
123
- permission: ['permission denied', 'EACCES'],
124
- notFound: ['no such file', 'ENOENT'],
125
- encoding: ['encoding', 'invalid byte', 'character'],
126
- size: ['too large', 'exceeds', 'size limit'],
127
- };
128
-
129
- // Categorize errors to provide better guidance
130
- const categorizedErrors = {
131
- permission: 0,
132
- notFound: 0,
133
- encoding: 0,
134
- size: 0,
135
- other: 0,
136
- };
137
-
138
- result.errors.forEach((error) => {
139
- const errorLowerCase = error.error.toLowerCase();
140
- let categorized = false;
141
-
142
- for (const [category, patterns] of Object.entries(commonErrorPatterns)) {
143
- if (patterns.some((pattern) => errorLowerCase.includes(pattern.toLowerCase()))) {
144
- categorizedErrors[category as keyof typeof categorizedErrors]++;
145
- categorized = true;
146
- break;
147
- }
148
- }
149
-
150
- if (!categorized) {
151
- categorizedErrors.other++;
152
- }
153
- });
154
-
155
- // Provide guidance based on error categories
156
- if (categorizedErrors.permission > 0) {
157
- logger.error(
158
- ` - ${categorizedErrors.permission} file(s) could not be read due to permission issues. Check file permissions.`,
159
- );
160
- }
161
- if (categorizedErrors.notFound > 0) {
162
- logger.error(
163
- ` - ${categorizedErrors.notFound} file(s) were not found. The file list may be out of date.`,
164
- );
165
- }
166
- if (categorizedErrors.encoding > 0) {
167
- logger.error(
168
- ` - ${categorizedErrors.encoding} file(s) had encoding issues. These might be binary files not suitable for review.`,
169
- );
170
- }
171
- if (categorizedErrors.size > 0) {
172
- logger.error(` - ${categorizedErrors.size} file(s) were too large to process.`);
173
- }
174
- if (categorizedErrors.other > 0) {
175
- logger.error(` - ${categorizedErrors.other} file(s) failed due to other issues.`);
176
- }
177
- }
178
-
179
- throw new Error(`${errorMessage} Please check file permissions and paths.`);
180
- }
181
-
182
- return result;
183
- } catch (error) {
184
- // Handle file reading errors not caught by readFilesContent
185
- if (error instanceof Error && error.message.includes('No files could be read')) {
186
- // This is an error we created above, so just rethrow it
187
- throw error;
188
- }
189
- // This is an unexpected error
190
- logger.error(
191
- `Unexpected error when reading file contents: ${
192
- error instanceof Error ? error.message : String(error)
193
- }`,
194
- );
195
-
196
- if (error instanceof Error && error.stack) {
197
- logger.debug(`Error stack trace: ${error.stack}`);
198
- }
199
-
200
- throw new Error(
201
- `Failed to read files for review: ${error instanceof Error ? error.message : String(error)}`,
202
- );
203
- }
204
- }
@@ -1,125 +0,0 @@
1
- /**
2
- * @fileoverview Output handling for code review results
3
- *
4
- * This module handles saving and displaying code review results
5
- * in different formats.
6
- */
7
-
8
- import * as path from 'node:path';
9
- import type { ReviewOptions, ReviewResult } from '../../types/review';
10
- import logger from '../../utils/logger';
11
- import { displayReviewInteractively } from '../InteractiveDisplayManager';
12
- import { saveReviewOutput } from '../OutputManager';
13
-
14
- // Define TokenUsage interface for this module
15
- interface TokenUsage {
16
- input: number;
17
- output: number;
18
- total: number;
19
- }
20
-
21
- /**
22
- * Handle review output based on options
23
- *
24
- * @param reviewResult Review result to handle
25
- * @param options Review options
26
- * @param outputBaseDir Base directory for output
27
- * @returns Promise that resolves when output handling is complete
28
- */
29
- export async function handleReviewOutput(
30
- reviewResult: ReviewResult,
31
- options: ReviewOptions,
32
- outputBaseDir: string,
33
- ): Promise<void> {
34
- // Save review output to file
35
- if (options.output !== 'none') {
36
- try {
37
- const targetName = path.basename(options.target || '.');
38
- const modelName = options.model || 'unknown-model';
39
-
40
- const outputPath = await saveReviewOutput(
41
- reviewResult,
42
- options,
43
- outputBaseDir,
44
- modelName,
45
- targetName,
46
- );
47
-
48
- logger.info(`Review saved to: ${outputPath}`);
49
-
50
- // Display review interactively if requested
51
- if (options.interactive) {
52
- try {
53
- await displayReviewInteractively(outputPath, process.cwd(), options);
54
- } catch (error) {
55
- logger.error(
56
- `Failed to display review interactively: ${
57
- error instanceof Error ? error.message : String(error)
58
- }`,
59
- );
60
- }
61
- }
62
- } catch (error) {
63
- logger.error(
64
- `Failed to save review output: ${error instanceof Error ? error.message : String(error)}`,
65
- );
66
- }
67
- }
68
-
69
- // Log completion message
70
- logger.info('Review completed successfully');
71
-
72
- // Log cost information if available
73
- if (reviewResult.cost) {
74
- // Use formattedCost if available, otherwise fall back to string representation
75
- const costDisplay =
76
- typeof reviewResult.cost === 'object' && reviewResult.cost.formattedCost
77
- ? reviewResult.cost.formattedCost
78
- : reviewResult.cost;
79
- logger.info(`Estimated cost: ${costDisplay}`);
80
- }
81
-
82
- // Log token usage if available
83
- if ((reviewResult as any).tokenUsage) {
84
- const { input, output, total } = (reviewResult as any).tokenUsage as TokenUsage;
85
- logger.info(`Token usage: ${input} input + ${output} output = ${total} total`);
86
- }
87
- }
88
-
89
- /**
90
- * Create output directory for review
91
- *
92
- * @param projectPath Project path
93
- * @param options Review options
94
- * @returns Output base directory
95
- */
96
- export function createOutputDirectory(
97
- projectPath: string,
98
- options: { outputDir?: string; configOutputDir?: string },
99
- ): string {
100
- // Get the output directory from options, config, or default
101
- const defaultOutputDir = 'cr-aia-docs';
102
- const configOutputDir = options.configOutputDir || defaultOutputDir;
103
- const outputDir = options.outputDir || configOutputDir;
104
-
105
- // Basic security validation: prevent obvious path traversal attempts
106
- if (outputDir.includes('..')) {
107
- throw new Error('Output directory path cannot contain ".." for security reasons');
108
- }
109
-
110
- // Determine if the path is absolute or relative
111
- let outputBaseDir: string;
112
-
113
- if (path.isAbsolute(outputDir)) {
114
- outputBaseDir = outputDir;
115
- } else {
116
- outputBaseDir = path.resolve(projectPath, outputDir);
117
- }
118
-
119
- // Log the output directory
120
- if (options.outputDir) {
121
- logger.info(`Using custom output directory: ${outputBaseDir}`);
122
- }
123
-
124
- return outputBaseDir;
125
- }
@@ -1,104 +0,0 @@
1
- /**
2
- * @fileoverview Review execution handler for code review
3
- *
4
- * This module handles the execution of code reviews using different strategies
5
- * based on review type and options.
6
- */
7
-
8
- import * as path from 'node:path';
9
- import type { TokenAnalysisResult } from '../../analysis/tokens';
10
- import { StrategyFactory } from '../../strategies/StrategyFactory';
11
- import type { ReviewOptions, ReviewResult } from '../../types/review';
12
- import logger from '../../utils/logger';
13
- import type { FileInfo } from '../fileDiscovery';
14
-
15
- /**
16
- * Execute code review using appropriate strategy
17
- *
18
- * @param fileInfos Array of file information objects
19
- * @param options Review options
20
- * @param apiClientConfig API client configuration
21
- * @param projectDocs Project documentation
22
- * @param semanticResult Semantic analysis result (if available)
23
- * @param tokenAnalysis Token analysis result (if available)
24
- * @returns Promise that resolves to review result
25
- */
26
- export async function executeReview(
27
- fileInfos: FileInfo[],
28
- options: ReviewOptions,
29
- apiClientConfig: { modelName: string; [key: string]: unknown },
30
- projectDocs: unknown = null,
31
- tokenAnalysis: TokenAnalysisResult | null = null,
32
- ): Promise<ReviewResult> {
33
- // Determine if we need multi-pass review based on token analysis
34
- const needsMultiPass = determineIfMultiPassNeeded(options, tokenAnalysis);
35
-
36
- // Update options to enable multi-pass if needed
37
- const effectiveOptions = { ...options };
38
- if (needsMultiPass && !options.forceSinglePass) {
39
- logger.info('Token analysis indicates multi-pass review is needed');
40
- logger.info(
41
- `Content has ${tokenAnalysis?.estimatedTotalTokens?.toLocaleString() || 'unknown'} tokens, exceeding model context window`,
42
- );
43
- effectiveOptions.multiPass = true;
44
- }
45
-
46
- // Create strategy based on review type and updated options
47
- const strategy = StrategyFactory.createStrategy(effectiveOptions);
48
-
49
- if (!strategy) {
50
- throw new Error(`Unsupported review type: ${options.type}`);
51
- }
52
-
53
- logger.info(`Using ${effectiveOptions.multiPass ? 'multi-pass' : options.type} review strategy`);
54
-
55
- if (needsMultiPass && options.forceSinglePass) {
56
- logger.warn('Multi-pass review recommended but single-pass forced by user');
57
- logger.warn('This may result in token limit errors or incomplete reviews');
58
- }
59
-
60
- // Get project name
61
- const projectPath = process.cwd();
62
- const projectName = path.basename(projectPath);
63
-
64
- // Execute the review with effective options (may have multiPass enabled)
65
- const reviewResult = await strategy.execute(
66
- fileInfos,
67
- projectName,
68
- projectDocs as any,
69
- effectiveOptions,
70
- apiClientConfig as any,
71
- );
72
-
73
- return reviewResult;
74
- }
75
-
76
- /**
77
- * Determine if multi-pass review is needed
78
- *
79
- * @param options Review options
80
- * @param tokenAnalysis Token analysis result (if available)
81
- * @returns Whether multi-pass review is needed
82
- */
83
- export function determineIfMultiPassNeeded(
84
- options: ReviewOptions,
85
- tokenAnalysis: TokenAnalysisResult | null,
86
- ): boolean {
87
- // If multi-pass is explicitly enabled, use it
88
- if (options.multiPass) {
89
- return true;
90
- }
91
-
92
- // If force single-pass is enabled, don't use multi-pass
93
- if (options.forceSinglePass) {
94
- return false;
95
- }
96
-
97
- // If we have token analysis, use its recommendation
98
- if (tokenAnalysis?.chunkingRecommendation) {
99
- return tokenAnalysis.chunkingRecommendation.chunkingRecommended;
100
- }
101
-
102
- // Default to false if we can't determine
103
- return false;
104
- }