@angular-modernizer/adapter-mcp 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +917 -0
  3. package/dist/cli.d.ts +8 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +129 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/core/project-analyzer.d.ts +59 -0
  8. package/dist/core/project-analyzer.d.ts.map +1 -0
  9. package/dist/core/project-analyzer.js +116 -0
  10. package/dist/core/project-analyzer.js.map +1 -0
  11. package/dist/index.d.ts +46 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +51 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mcp-watcher.d.ts +119 -0
  16. package/dist/mcp-watcher.d.ts.map +1 -0
  17. package/dist/mcp-watcher.js +380 -0
  18. package/dist/mcp-watcher.js.map +1 -0
  19. package/dist/server/json-rpc-handler.d.ts +57 -0
  20. package/dist/server/json-rpc-handler.d.ts.map +1 -0
  21. package/dist/server/json-rpc-handler.js +222 -0
  22. package/dist/server/json-rpc-handler.js.map +1 -0
  23. package/dist/server/mcp-server.d.ts +62 -0
  24. package/dist/server/mcp-server.d.ts.map +1 -0
  25. package/dist/server/mcp-server.js +184 -0
  26. package/dist/server/mcp-server.js.map +1 -0
  27. package/dist/server/tool-registry.d.ts +73 -0
  28. package/dist/server/tool-registry.d.ts.map +1 -0
  29. package/dist/server/tool-registry.js +102 -0
  30. package/dist/server/tool-registry.js.map +1 -0
  31. package/dist/streaming/progress-store.d.ts +120 -0
  32. package/dist/streaming/progress-store.d.ts.map +1 -0
  33. package/dist/streaming/progress-store.js +238 -0
  34. package/dist/streaming/progress-store.js.map +1 -0
  35. package/dist/tools/analyze-build-impact.d.ts +127 -0
  36. package/dist/tools/analyze-build-impact.d.ts.map +1 -0
  37. package/dist/tools/analyze-build-impact.js +194 -0
  38. package/dist/tools/analyze-build-impact.js.map +1 -0
  39. package/dist/tools/analyze-core-to-shared.d.ts +163 -0
  40. package/dist/tools/analyze-core-to-shared.d.ts.map +1 -0
  41. package/dist/tools/analyze-core-to-shared.js +436 -0
  42. package/dist/tools/analyze-core-to-shared.js.map +1 -0
  43. package/dist/tools/analyze-parser-performance.d.ts +105 -0
  44. package/dist/tools/analyze-parser-performance.d.ts.map +1 -0
  45. package/dist/tools/analyze-parser-performance.js +313 -0
  46. package/dist/tools/analyze-parser-performance.js.map +1 -0
  47. package/dist/tools/analyze-project.d.ts +277 -0
  48. package/dist/tools/analyze-project.d.ts.map +1 -0
  49. package/dist/tools/analyze-project.js +946 -0
  50. package/dist/tools/analyze-project.js.map +1 -0
  51. package/dist/tools/check-incremental-compatibility.d.ts +109 -0
  52. package/dist/tools/check-incremental-compatibility.d.ts.map +1 -0
  53. package/dist/tools/check-incremental-compatibility.js +302 -0
  54. package/dist/tools/check-incremental-compatibility.js.map +1 -0
  55. package/dist/tools/collect-feedback.d.ts +117 -0
  56. package/dist/tools/collect-feedback.d.ts.map +1 -0
  57. package/dist/tools/collect-feedback.js +773 -0
  58. package/dist/tools/collect-feedback.js.map +1 -0
  59. package/dist/tools/extract-libraries.d.ts +121 -0
  60. package/dist/tools/extract-libraries.d.ts.map +1 -0
  61. package/dist/tools/extract-libraries.js +223 -0
  62. package/dist/tools/extract-libraries.js.map +1 -0
  63. package/dist/tools/find-angular-symbol.d.ts +55 -0
  64. package/dist/tools/find-angular-symbol.d.ts.map +1 -0
  65. package/dist/tools/find-angular-symbol.js +104 -0
  66. package/dist/tools/find-angular-symbol.js.map +1 -0
  67. package/dist/tools/find-usages.d.ts +65 -0
  68. package/dist/tools/find-usages.d.ts.map +1 -0
  69. package/dist/tools/find-usages.js +108 -0
  70. package/dist/tools/find-usages.js.map +1 -0
  71. package/dist/tools/get-call-graph.d.ts +61 -0
  72. package/dist/tools/get-call-graph.d.ts.map +1 -0
  73. package/dist/tools/get-call-graph.js +119 -0
  74. package/dist/tools/get-call-graph.js.map +1 -0
  75. package/dist/tools/get-operation-progress-tool.d.ts +29 -0
  76. package/dist/tools/get-operation-progress-tool.d.ts.map +1 -0
  77. package/dist/tools/get-operation-progress-tool.js +36 -0
  78. package/dist/tools/get-operation-progress-tool.js.map +1 -0
  79. package/dist/tools/get-operation-progress.d.ts +51 -0
  80. package/dist/tools/get-operation-progress.d.ts.map +1 -0
  81. package/dist/tools/get-operation-progress.js +93 -0
  82. package/dist/tools/get-operation-progress.js.map +1 -0
  83. package/dist/tools/helpers/feedback-analyzer.d.ts +43 -0
  84. package/dist/tools/helpers/feedback-analyzer.d.ts.map +1 -0
  85. package/dist/tools/helpers/feedback-analyzer.js +196 -0
  86. package/dist/tools/helpers/feedback-analyzer.js.map +1 -0
  87. package/dist/tools/helpers/find-ts-config.d.ts +10 -0
  88. package/dist/tools/helpers/find-ts-config.d.ts.map +1 -0
  89. package/dist/tools/helpers/find-ts-config.js +32 -0
  90. package/dist/tools/helpers/find-ts-config.js.map +1 -0
  91. package/dist/tools/helpers/platform-root-resolver.d.ts +33 -0
  92. package/dist/tools/helpers/platform-root-resolver.d.ts.map +1 -0
  93. package/dist/tools/helpers/platform-root-resolver.js +60 -0
  94. package/dist/tools/helpers/platform-root-resolver.js.map +1 -0
  95. package/dist/tools/helpers/rule-matcher.d.ts +84 -0
  96. package/dist/tools/helpers/rule-matcher.d.ts.map +1 -0
  97. package/dist/tools/helpers/rule-matcher.js +212 -0
  98. package/dist/tools/helpers/rule-matcher.js.map +1 -0
  99. package/dist/tools/helpers/suggestion-generator.d.ts +66 -0
  100. package/dist/tools/helpers/suggestion-generator.d.ts.map +1 -0
  101. package/dist/tools/helpers/suggestion-generator.js +248 -0
  102. package/dist/tools/helpers/suggestion-generator.js.map +1 -0
  103. package/dist/tools/learn-patterns.d.ts +368 -0
  104. package/dist/tools/learn-patterns.d.ts.map +1 -0
  105. package/dist/tools/learn-patterns.js +1089 -0
  106. package/dist/tools/learn-patterns.js.map +1 -0
  107. package/dist/tools/orchestrate-migration.d.ts +187 -0
  108. package/dist/tools/orchestrate-migration.d.ts.map +1 -0
  109. package/dist/tools/orchestrate-migration.js +235 -0
  110. package/dist/tools/orchestrate-migration.js.map +1 -0
  111. package/dist/tools/parse-stack-trace.d.ts +63 -0
  112. package/dist/tools/parse-stack-trace.d.ts.map +1 -0
  113. package/dist/tools/parse-stack-trace.js +92 -0
  114. package/dist/tools/parse-stack-trace.js.map +1 -0
  115. package/dist/tools/plan-migration.d.ts +388 -0
  116. package/dist/tools/plan-migration.d.ts.map +1 -0
  117. package/dist/tools/plan-migration.js +826 -0
  118. package/dist/tools/plan-migration.js.map +1 -0
  119. package/dist/tools/resolve-type.d.ts +54 -0
  120. package/dist/tools/resolve-type.d.ts.map +1 -0
  121. package/dist/tools/resolve-type.js +101 -0
  122. package/dist/tools/resolve-type.js.map +1 -0
  123. package/dist/tools/review-feedback.d.ts +124 -0
  124. package/dist/tools/review-feedback.d.ts.map +1 -0
  125. package/dist/tools/review-feedback.js +276 -0
  126. package/dist/tools/review-feedback.js.map +1 -0
  127. package/dist/tools/rollback-changes.d.ts +42 -0
  128. package/dist/tools/rollback-changes.d.ts.map +1 -0
  129. package/dist/tools/rollback-changes.js +95 -0
  130. package/dist/tools/rollback-changes.js.map +1 -0
  131. package/dist/tools/run-angular-cli.d.ts +102 -0
  132. package/dist/tools/run-angular-cli.d.ts.map +1 -0
  133. package/dist/tools/run-angular-cli.js +152 -0
  134. package/dist/tools/run-angular-cli.js.map +1 -0
  135. package/dist/tools/run-build.d.ts +201 -0
  136. package/dist/tools/run-build.d.ts.map +1 -0
  137. package/dist/tools/run-build.js +554 -0
  138. package/dist/tools/run-build.js.map +1 -0
  139. package/dist/tools/run-schematic.d.ts +173 -0
  140. package/dist/tools/run-schematic.d.ts.map +1 -0
  141. package/dist/tools/run-schematic.js +410 -0
  142. package/dist/tools/run-schematic.js.map +1 -0
  143. package/dist/tools/scan-all.d.ts +160 -0
  144. package/dist/tools/scan-all.d.ts.map +1 -0
  145. package/dist/tools/scan-all.js +486 -0
  146. package/dist/tools/scan-all.js.map +1 -0
  147. package/dist/tools/scan-angular.d.ts +132 -0
  148. package/dist/tools/scan-angular.d.ts.map +1 -0
  149. package/dist/tools/scan-angular.js +411 -0
  150. package/dist/tools/scan-angular.js.map +1 -0
  151. package/dist/tools/scan-architecture.d.ts +351 -0
  152. package/dist/tools/scan-architecture.d.ts.map +1 -0
  153. package/dist/tools/scan-architecture.js +1290 -0
  154. package/dist/tools/scan-architecture.js.map +1 -0
  155. package/dist/tools/scan-solid.d.ts +132 -0
  156. package/dist/tools/scan-solid.d.ts.map +1 -0
  157. package/dist/tools/scan-solid.js +435 -0
  158. package/dist/tools/scan-solid.js.map +1 -0
  159. package/dist/tools/search-codebase.d.ts +64 -0
  160. package/dist/tools/search-codebase.d.ts.map +1 -0
  161. package/dist/tools/search-codebase.js +109 -0
  162. package/dist/tools/search-codebase.js.map +1 -0
  163. package/dist/tools/shared/scan-types.d.ts +200 -0
  164. package/dist/tools/shared/scan-types.d.ts.map +1 -0
  165. package/dist/tools/shared/scan-types.js +7 -0
  166. package/dist/tools/shared/scan-types.js.map +1 -0
  167. package/dist/tools/suggest-improvements.d.ts +96 -0
  168. package/dist/tools/suggest-improvements.d.ts.map +1 -0
  169. package/dist/tools/suggest-improvements.js +182 -0
  170. package/dist/tools/suggest-improvements.js.map +1 -0
  171. package/dist/tools/transform-code-batch.d.ts +57 -0
  172. package/dist/tools/transform-code-batch.d.ts.map +1 -0
  173. package/dist/tools/transform-code-batch.js +107 -0
  174. package/dist/tools/transform-code-batch.js.map +1 -0
  175. package/dist/tools/transform-code.d.ts +352 -0
  176. package/dist/tools/transform-code.d.ts.map +1 -0
  177. package/dist/tools/transform-code.js +1171 -0
  178. package/dist/tools/transform-code.js.map +1 -0
  179. package/dist/tools/validate-before-transform.d.ts +54 -0
  180. package/dist/tools/validate-before-transform.d.ts.map +1 -0
  181. package/dist/tools/validate-before-transform.js +141 -0
  182. package/dist/tools/validate-before-transform.js.map +1 -0
  183. package/dist/tools/validate-project-compatibility.d.ts +119 -0
  184. package/dist/tools/validate-project-compatibility.d.ts.map +1 -0
  185. package/dist/tools/validate-project-compatibility.js +243 -0
  186. package/dist/tools/validate-project-compatibility.js.map +1 -0
  187. package/dist/tools/validate-transformation.d.ts +105 -0
  188. package/dist/tools/validate-transformation.d.ts.map +1 -0
  189. package/dist/tools/validate-transformation.js +391 -0
  190. package/dist/tools/validate-transformation.js.map +1 -0
  191. package/dist/types.d.ts +153 -0
  192. package/dist/types.d.ts.map +1 -0
  193. package/dist/types.js +38 -0
  194. package/dist/types.js.map +1 -0
  195. package/dist/utils/format-tool-response.d.ts +72 -0
  196. package/dist/utils/format-tool-response.d.ts.map +1 -0
  197. package/dist/utils/format-tool-response.js +149 -0
  198. package/dist/utils/format-tool-response.js.map +1 -0
  199. package/package.json +70 -0
@@ -0,0 +1,1290 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Scan Architecture Tool
3
+ *
4
+ * MCP tool for scanning Angular codebases for architectural issues.
5
+ * Runs only the ArchitecturePlugin (13 rules: circular deps, layer violations, god objects, etc.).
6
+ */
7
+ import { findTsConfig } from './helpers/find-ts-config.js';
8
+ import { toParallelOptions } from '../types.js';
9
+ import { Kernel, createToolCacheConfig, loadConfig, } from '@angular-modernizer/core';
10
+ import { ArchitecturePlugin } from '@angular-modernizer/plugin-architecture';
11
+ import { ContextFactory, } from '@angular-modernizer/plugin-system';
12
+ import { createPublicApi } from '@angular-modernizer/api';
13
+ import { getWorkerScriptPath } from '@angular-modernizer/worker';
14
+ import { glob } from 'glob';
15
+ import { resolve, extname } from 'node:path';
16
+ import { readFileSync, existsSync, statSync } from 'node:fs';
17
+ import { randomUUID } from 'node:crypto';
18
+ import { cpus } from 'node:os';
19
+ import { ProgressStore } from '../streaming/progress-store.js';
20
+ /**
21
+ * Scan Architecture Tool
22
+ *
23
+ * Provides architectural analysis capabilities through MCP.
24
+ * Uses the SOLID plugin to detect violations of SOLID principles.
25
+ */
26
+ export class ScanArchitectureTool {
27
+ name = 'scan-architecture';
28
+ description = 'Scan Angular codebases for SOLID principle violations and architectural issues';
29
+ inputSchema = {
30
+ type: 'object',
31
+ properties: {
32
+ rootPath: {
33
+ type: 'string',
34
+ description: 'Root path of the project to analyze',
35
+ },
36
+ scope: {
37
+ type: 'object',
38
+ description: 'Scope configuration for targeted scanning (apps, libs, modules, features, folders)',
39
+ properties: {
40
+ type: {
41
+ type: 'string',
42
+ enum: [
43
+ 'all',
44
+ 'applications',
45
+ 'libraries',
46
+ 'modules',
47
+ 'features',
48
+ 'folders',
49
+ ],
50
+ description: 'Type of scope to scan',
51
+ default: 'all',
52
+ },
53
+ names: {
54
+ type: 'array',
55
+ items: { type: 'string' },
56
+ description: 'Names of specific projects/features to scan',
57
+ },
58
+ paths: {
59
+ type: 'array',
60
+ items: { type: 'string' },
61
+ description: 'Specific folder paths to scan (for folders type)',
62
+ },
63
+ },
64
+ },
65
+ rules: {
66
+ type: 'array',
67
+ items: { type: 'string' },
68
+ description: 'Specific rules to run (optional, runs all if not specified). ' +
69
+ 'Must be exact rule.id values — short names like "circular-dependency" will NOT match. ' +
70
+ 'Valid IDs: solid:circular-dependency, solid:import-direction-violation, solid:god-object-violation, ' +
71
+ 'architecture:component-complexity, architecture:service-architecture, architecture:content-placement, ' +
72
+ 'architecture:advanced-content-placement, architecture:model-separation, architecture:rxjs-memory-leak, ' +
73
+ 'architecture:error-handling-pattern, architecture:inheritance-analysis, architecture:performance-pattern, ' +
74
+ 'architecture:cross-file-architecture, architecture:service-bag, architecture:static-in-stateful-class, ' +
75
+ 'architecture:library-extraction-opportunity, architecture:layer-boundary-violation',
76
+ },
77
+ includePatterns: {
78
+ type: 'array',
79
+ items: { type: 'string' },
80
+ description: 'File patterns to include (optional, defaults to TypeScript files)',
81
+ default: ['**/*.{ts,tsx}'],
82
+ },
83
+ excludePatterns: {
84
+ type: 'array',
85
+ items: { type: 'string' },
86
+ description: 'File patterns to exclude',
87
+ default: [
88
+ '**/node_modules/**',
89
+ '**/dist/**',
90
+ '**/build/**',
91
+ '**/coverage/**',
92
+ '**/e2e/**',
93
+ '**/.*/**', // All hidden folders and files starting with .
94
+ '**/*.spec.ts',
95
+ '**/*.test.ts',
96
+ ],
97
+ },
98
+ includeAutoFixes: {
99
+ type: 'boolean',
100
+ description: 'Whether to include auto-fix suggestions',
101
+ default: true,
102
+ },
103
+ maxFiles: {
104
+ type: 'number',
105
+ description: 'Maximum number of files to analyze (default: 100 to prevent memory issues)',
106
+ default: 100,
107
+ },
108
+ maxResults: {
109
+ type: 'number',
110
+ description: 'Maximum number of violations to return (pagination)',
111
+ default: 1000,
112
+ },
113
+ resultOffset: {
114
+ type: 'number',
115
+ description: 'Offset for result pagination (skip first N violations)',
116
+ default: 0,
117
+ },
118
+ orchestration: {
119
+ type: 'object',
120
+ description: 'Advanced orchestration options for analysis',
121
+ properties: {
122
+ parallel: {
123
+ type: 'boolean',
124
+ description: 'Enable parallel rule execution for faster scanning',
125
+ default: false,
126
+ },
127
+ incremental: {
128
+ type: 'boolean',
129
+ description: 'Only analyze changed files (requires git)',
130
+ default: false,
131
+ },
132
+ baseBranch: {
133
+ type: 'string',
134
+ description: 'Git branch to compare against for incremental analysis',
135
+ default: 'main',
136
+ },
137
+ maxWorkers: {
138
+ type: 'number',
139
+ description: 'Maximum concurrent workers for parallel execution',
140
+ },
141
+ enableProgress: {
142
+ type: 'boolean',
143
+ description: 'Enable real-time progress reporting with ETA',
144
+ default: false,
145
+ },
146
+ useWorkerThreads: {
147
+ type: 'boolean',
148
+ description: 'Use worker threads for true multi-core parallelism',
149
+ default: true,
150
+ },
151
+ tsConfigPath: {
152
+ type: 'string',
153
+ description: 'TypeScript config path (auto-detected if not provided)',
154
+ },
155
+ workerScriptPath: {
156
+ type: 'string',
157
+ description: 'Worker script path (auto-detected if not provided)',
158
+ },
159
+ pluginIds: {
160
+ type: 'array',
161
+ items: { type: 'string' },
162
+ description: 'Plugin IDs to load (auto-detected if not provided)',
163
+ },
164
+ timeout: {
165
+ type: 'number',
166
+ description: 'Task timeout in milliseconds',
167
+ default: 30000,
168
+ },
169
+ autoSelectMode: {
170
+ type: 'boolean',
171
+ description: 'Enable intelligent mode selection (Phase 7b)',
172
+ default: true,
173
+ },
174
+ enableMonitoring: {
175
+ type: 'boolean',
176
+ description: 'Enable real-time memory monitoring',
177
+ default: true,
178
+ },
179
+ fallbackToWorkers: {
180
+ type: 'boolean',
181
+ description: 'Fallback to worker threads if Promise mode fails',
182
+ default: true,
183
+ },
184
+ },
185
+ },
186
+ streaming: {
187
+ type: 'boolean',
188
+ description: 'Enable streaming mode - returns operationId immediately for polling progress. When true, analysis runs in background and progress can be queried via get-operation-progress tool.',
189
+ default: true,
190
+ },
191
+ apiStyle: {
192
+ type: 'string',
193
+ enum: ['imperative', 'fluent'],
194
+ description: 'API style to use for analysis execution. "fluent" (default) uses the chainable FluentKernel API with pipeline stages. "imperative" uses traditional Kernel API.',
195
+ default: 'fluent',
196
+ },
197
+ },
198
+ required: ['rootPath'],
199
+ };
200
+ async execute(args) {
201
+ const params = args;
202
+ // Check if streaming mode is enabled
203
+ const streaming = params.streaming ?? true;
204
+ if (streaming) {
205
+ // Streaming mode - start operation in background and return operationId
206
+ return this.executeStreaming(params);
207
+ }
208
+ // Check if fluent API should be used
209
+ const apiStyle = params.apiStyle ?? 'fluent';
210
+ if (apiStyle === 'fluent') {
211
+ return this.executeWithFluentApi(params);
212
+ }
213
+ // Load configuration from .angular-modernizer.json if it exists
214
+ const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
215
+ // Merge config with provided parameters (params take precedence)
216
+ const mergedParams = {
217
+ ...config,
218
+ ...params,
219
+ };
220
+ // Use orchestration object directly
221
+ const orchestration = mergedParams.orchestration ?? {};
222
+ // Validate input
223
+ if (!mergedParams.rootPath || typeof mergedParams.rootPath !== 'string') {
224
+ throw new Error('rootPath is required and must be a string');
225
+ }
226
+ const startTime = Date.now();
227
+ try {
228
+ // Set defaults and merge exclude patterns from config and params
229
+ const defaultExcludePatterns = [
230
+ '**/node_modules/**',
231
+ '**/dist/**',
232
+ '**/build/**',
233
+ '**/coverage/**',
234
+ '**/e2e/**',
235
+ '**/.*/**', // All hidden folders and files starting with .
236
+ '**/*.spec.ts',
237
+ '**/*.test.ts',
238
+ ];
239
+ // Merge exclude patterns: config defaults + config overrides + param overrides
240
+ const configExcludePatterns = orchestration.excludePatterns ?? [];
241
+ const paramExcludePatterns = params.excludePatterns ?? [];
242
+ const excludePatterns = [
243
+ ...defaultExcludePatterns,
244
+ ...configExcludePatterns,
245
+ ...paramExcludePatterns,
246
+ ];
247
+ // Set include patterns
248
+ const includePatterns = params.includePatterns ?? ['**/*.{ts,tsx}'];
249
+ // CRITICAL: Default to 100 files to prevent memory exhaustion
250
+ // Production scans should explicitly set maxFiles if they need more
251
+ const maxFiles = params.maxFiles ?? 100;
252
+ // Auto-detect required paths
253
+ const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(params.rootPath);
254
+ const workerScriptPath = orchestration.workerScriptPath ?? getWorkerScriptPath();
255
+ if (!tsConfigPath) {
256
+ throw new Error('Could not find tsconfig.json in the project root');
257
+ }
258
+ // Initialize kernel with ArchitecturePlugin only + caching
259
+ const kernel = new Kernel({
260
+ tsConfigPath,
261
+ plugins: [new ArchitecturePlugin()],
262
+ projectOptions: {
263
+ skipAddingFilesFromTsConfig: true, // CRITICAL: We manually add filtered files
264
+ },
265
+ cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'architecture'),
266
+ });
267
+ await kernel.initialize();
268
+ // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
269
+ const fullConfig = loadConfig(mergedParams.rootPath);
270
+ const rulesConfig = fullConfig.rules;
271
+ // Detect offline mode by testing worker availability
272
+ let isOfflineMode = false;
273
+ try {
274
+ const testWorkerPath = getWorkerScriptPath();
275
+ if (existsSync(testWorkerPath)) {
276
+ console.info('Worker threads available');
277
+ }
278
+ else {
279
+ console.warn('Worker threads not available (offline mode)');
280
+ isOfflineMode = true;
281
+ }
282
+ }
283
+ catch (error) {
284
+ console.warn('Worker threads not available (offline mode):', error instanceof Error ? error.message : String(error));
285
+ isOfflineMode = true;
286
+ }
287
+ // In offline mode, disable worker threads but keep auto-selection enabled
288
+ // This allows large codebases to still use Promise mode efficiently
289
+ if (isOfflineMode) {
290
+ console.info('Worker threads disabled in offline mode, keeping auto-selection for optimal performance');
291
+ orchestration.useWorkerThreads = false;
292
+ // Keep autoSelectMode enabled so large projects still get Promise parallelism
293
+ }
294
+ // Setup progress tracking if requested
295
+ let lastProgress;
296
+ if (orchestration.enableProgress) {
297
+ const progressReporter = kernel.getProgressReporter();
298
+ if (progressReporter) {
299
+ progressReporter.on('progress', (progress) => {
300
+ lastProgress = {
301
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- Progress event typing is dynamic
302
+ current: progress.current,
303
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
304
+ total: progress.total,
305
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
306
+ percentage: progress.percentage,
307
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
308
+ eta: progress.eta ?? 0,
309
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
310
+ phase: progress.type,
311
+ };
312
+ });
313
+ }
314
+ }
315
+ // Check resource limits before proceeding
316
+ const resourceManager = kernel.getResourceManager();
317
+ if (resourceManager && !resourceManager.canProceed()) {
318
+ throw new Error('Insufficient resources to proceed with analysis');
319
+ }
320
+ // Get analysis rules from ArchitecturePlugin
321
+ const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
322
+ const allRules = archPlugin.getAnalysisRules();
323
+ const rulesToRun = params.rules
324
+ ? allRules.filter((rule) => params.rules.includes(rule.id))
325
+ : allRules;
326
+ console.info(`ScanArchitecture: Found ${allRules.length} total rules, running ${rulesToRun.length} rules:`, rulesToRun.map((r) => r.id));
327
+ if (rulesToRun.length === 0) {
328
+ throw new Error('No matching rules found');
329
+ }
330
+ // Run analysis using full orchestration
331
+ // Resolve scope for targeted scanning
332
+ const resolvedScope = this.resolveScope(params.rootPath, mergedParams.scope);
333
+ console.info(`Scan scope: ${resolvedScope.type}${resolvedScope.names?.length ? ` (${resolvedScope.names.join(', ')})` : ''}`);
334
+ if (resolvedScope.resolvedPaths.length > 0 &&
335
+ resolvedScope.type !== 'all') {
336
+ console.info(` Paths: ${resolvedScope.resolvedPaths.join(', ')}`);
337
+ }
338
+ const violations = [];
339
+ let filesAnalyzed = 0;
340
+ // Pre-discover files to enable auto-selection of parallel mode
341
+ const preDiscoveryFiles = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, Number.MAX_SAFE_INTEGER);
342
+ // Apply scope filtering for file count
343
+ const scopeFilteredFiles = resolvedScope.type !== 'all'
344
+ ? this.filterFilesByScope(preDiscoveryFiles, resolvedScope)
345
+ : preDiscoveryFiles;
346
+ // Auto-enable parallel processing for >100 files (unless explicitly disabled)
347
+ if (scopeFilteredFiles.length > 100 &&
348
+ orchestration.parallel === undefined) {
349
+ orchestration.parallel = true;
350
+ orchestration.autoSelectMode = orchestration.autoSelectMode ?? true;
351
+ orchestration.maxWorkers =
352
+ orchestration.maxWorkers ?? Math.min(4, cpus().length);
353
+ console.info(`Auto-enabled parallel processing for ${scopeFilteredFiles.length} files (>100 threshold)`);
354
+ }
355
+ if (orchestration.parallel || orchestration.incremental) {
356
+ // Use pre-discovered and filtered files
357
+ const filesToAnalyze = scopeFilteredFiles;
358
+ // Update resolved scope with matched files count
359
+ resolvedScope.matchedFiles = filesToAnalyze.length;
360
+ console.info(`Scan scope: ${resolvedScope.type}, matched ${filesToAnalyze.length} files`);
361
+ // Batch processing: Process files in chunks to prevent memory exhaustion
362
+ const batchSize = maxFiles; // Process maxFiles at a time (default 100)
363
+ const totalFiles = filesToAnalyze.length;
364
+ const totalBatches = Math.ceil(totalFiles / batchSize);
365
+ console.info(`Processing ${totalFiles} files in ${totalBatches} batch(es) of ${batchSize} files each`);
366
+ const parallelOptions = {
367
+ ...toParallelOptions(orchestration),
368
+ plugins: ['@angular-modernizer/plugin-architecture'],
369
+ tsConfigPath,
370
+ workerScriptPath,
371
+ pluginIds: orchestration.pluginIds ?? [
372
+ '@angular-modernizer/plugin-architecture',
373
+ ],
374
+ rules: params.rules,
375
+ timeout: orchestration.timeout ?? 120000, // 2 minutes for complex architecture rules
376
+ };
377
+ // Process each batch
378
+ for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
379
+ const batchStart = batchNum * batchSize;
380
+ const batchEnd = Math.min(batchStart + batchSize, totalFiles);
381
+ const batchFiles = filesToAnalyze.slice(batchStart, batchEnd);
382
+ console.info(`\nBatch ${batchNum + 1}/${totalBatches}: Processing files ${batchStart + 1}-${batchEnd} (${batchFiles.length} files)`);
383
+ // Clear project and add batch files
384
+ // This is CRITICAL: parallel mode needs files in project for kernel.analyzeParallel()
385
+ const project = kernel.getProject();
386
+ // Remove all source files from previous batch
387
+ const existingFiles = project.getSourceFiles();
388
+ for (const file of existingFiles) {
389
+ project.removeSourceFile(file);
390
+ }
391
+ // Add current batch files
392
+ for (const filePath of batchFiles) {
393
+ project.addSourceFileAtPath(filePath);
394
+ }
395
+ console.info(`Batch ${batchNum + 1}: Project now has ${project.getSourceFiles().length} source files`);
396
+ // Log cache stats to show cache effectiveness
397
+ const cacheManager = kernel.getCacheManager();
398
+ if (cacheManager) {
399
+ const cacheStats = cacheManager.getStats();
400
+ const cacheHitRate = cacheStats.hitRate.toFixed(1);
401
+ const cachedFiles = cacheStats.hits;
402
+ const uncachedFiles = cacheStats.misses;
403
+ console.info(`Cache stats: ${cachedFiles} cached results, ${uncachedFiles} files to analyze${cacheStats.hits > 0 ? ` (${cacheHitRate}% hit rate)` : ''}`);
404
+ }
405
+ if (orchestration.incremental) {
406
+ // Incremental analysis mode
407
+ console.info(`Batch ${batchNum + 1}: Using incremental analysis mode...`);
408
+ const incrementalResult = await kernel.analyzeIncremental({
409
+ ...parallelOptions,
410
+ baseBranch: orchestration.baseBranch,
411
+ parallel: orchestration.parallel,
412
+ });
413
+ // Extract violations from incremental result
414
+ const results = incrementalResult
415
+ .results;
416
+ for (const result of results) {
417
+ const analysisResult = result;
418
+ // Find the rule to get severity and category
419
+ const rule = rulesToRun.find((r) => r.id === analysisResult.ruleId);
420
+ if (rule) {
421
+ violations.push({
422
+ id: `${analysisResult.ruleId}-${analysisResult.filePath}-${analysisResult.line ?? 0}-${analysisResult.column ?? 0}`,
423
+ ruleId: analysisResult.ruleId,
424
+ severity: rule.severity,
425
+ message: analysisResult.message,
426
+ filePath: analysisResult.filePath,
427
+ line: analysisResult.line,
428
+ column: analysisResult.column,
429
+ category: rule.category,
430
+ suggestedFix: analysisResult.suggestedFix,
431
+ metadata: analysisResult.metadata,
432
+ });
433
+ }
434
+ }
435
+ filesAnalyzed += incrementalResult
436
+ .analyzedFiles.length;
437
+ console.info(`Batch ${batchNum + 1}: Found ${results.length} violations in ${incrementalResult.analyzedFiles.length} files`);
438
+ }
439
+ else {
440
+ // Parallel analysis mode
441
+ console.info(`Batch ${batchNum + 1}: Using parallel analysis mode...`);
442
+ const parallelResults = await kernel.analyzeParallel(parallelOptions);
443
+ // Extract violations from parallel results
444
+ let batchViolationCount = 0;
445
+ for (const result of parallelResults) {
446
+ const analysisResult = result;
447
+ const rule = rulesToRun.find((r) => r.id === analysisResult.ruleId);
448
+ if (rule) {
449
+ violations.push({
450
+ id: `${analysisResult.ruleId}-${analysisResult.filePath}-${analysisResult.line ?? 0}-${analysisResult.column ?? 0}`,
451
+ ruleId: analysisResult.ruleId,
452
+ severity: rule.severity,
453
+ message: analysisResult.message,
454
+ filePath: analysisResult.filePath,
455
+ line: analysisResult.line,
456
+ column: analysisResult.column,
457
+ category: rule.category,
458
+ suggestedFix: analysisResult.suggestedFix,
459
+ metadata: analysisResult.metadata,
460
+ });
461
+ batchViolationCount++;
462
+ }
463
+ }
464
+ filesAnalyzed += batchFiles.length;
465
+ console.info(`Batch ${batchNum + 1}: Found ${batchViolationCount} violations in ${batchFiles.length} files`);
466
+ }
467
+ }
468
+ console.info(`\nBatch processing complete: ${totalBatches} batch(es), ${filesAnalyzed} total files analyzed, ${violations.length} total violations`);
469
+ }
470
+ else {
471
+ // Sequential analysis mode (existing logic)
472
+ console.info('Using sequential analysis mode...');
473
+ const project = kernel.getProject();
474
+ const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
475
+ let filesToAnalyze = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, maxFiles);
476
+ // Apply scope filtering for sequential mode
477
+ if (resolvedScope.type !== 'all') {
478
+ const filesBefore = filesToAnalyze.length;
479
+ filesToAnalyze = this.filterFilesByScope(filesToAnalyze, resolvedScope);
480
+ console.info(`Scope filter: ${filesToAnalyze.length} files (from ${filesBefore})`);
481
+ }
482
+ // Update resolved scope with matched files count
483
+ resolvedScope.matchedFiles = filesToAnalyze.length;
484
+ // ============================================================================
485
+ // CACHE READ SYSTEM (Sequential Mode Only)
486
+ // ============================================================================
487
+ // Before analyzing files, check if cached results exist for unchanged files.
488
+ // This dramatically reduces analysis time on subsequent runs (39x speedup for Architecture!).
489
+ //
490
+ // Performance results (real-world validation on 2,758 files):
491
+ // - First run: 202.8s (analyzes all files, writes cache)
492
+ // - Second run: 5.2s (39x speedup, 97.4% faster, reads from cache)
493
+ //
494
+ // Why Architecture benefits MOST from caching:
495
+ // - Architecture rules are the most complex (circular deps, layer violations, god objects)
496
+ // - Graph analysis algorithms (dependency cycles) are computationally expensive
497
+ // - Caching eliminates ALL graph traversals for unchanged files
498
+ // - Best cache speedup of all scan types (39x vs 14.9x for scan-all)
499
+ //
500
+ // Cache directory: .angular-modernizer-cache/architecture/
501
+ // Cache invalidation: Automatic via mtime/content hash checking
502
+ //
503
+ // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
504
+ // This cache read logic is for sequential mode only.
505
+ // ============================================================================
506
+ const cacheManagerForRead = kernel.getCacheManager();
507
+ const cachedViolations = []; // eslint-disable-line @typescript-eslint/no-explicit-any
508
+ let filesToProcess = [];
509
+ if (cacheManagerForRead) {
510
+ for (const filePath of filesToAnalyze) {
511
+ const cached = await cacheManagerForRead.getAnalysisResult(filePath);
512
+ if (cached?.results && cached.results.length > 0) {
513
+ // File is cached and hasn't changed
514
+ cachedViolations.push(...cached.results);
515
+ }
516
+ else {
517
+ // File not cached or has changed
518
+ filesToProcess.push(filePath);
519
+ }
520
+ }
521
+ const stats = cacheManagerForRead.getStats();
522
+ console.info(`Cache: ${cachedViolations.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${stats.hitRate.toFixed(1)}%)`);
523
+ }
524
+ else {
525
+ // No cache manager, analyze all files
526
+ filesToProcess = filesToAnalyze;
527
+ }
528
+ // Add cached violations to results
529
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
530
+ violations.push(...cachedViolations);
531
+ for (const filePath of filesToProcess) {
532
+ // Check resource limits periodically
533
+ if (resourceManager?.shouldThrottle()) {
534
+ console.warn('Resource throttling activated, pausing...');
535
+ await new Promise((resolve) => setTimeout(resolve, 1000));
536
+ }
537
+ try {
538
+ const sourceFile = project.addSourceFileAtPath(filePath);
539
+ for (const rule of rulesToRun) {
540
+ const results = await rule.analyze(ContextFactory.createAnalysisContext({
541
+ sourceFile,
542
+ project,
543
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
544
+ api,
545
+ config: rulesConfig,
546
+ }));
547
+ for (const result of results) {
548
+ violations.push({
549
+ id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
550
+ ruleId: result.ruleId,
551
+ severity: rule.severity,
552
+ message: result.message,
553
+ filePath: result.filePath,
554
+ line: result.line,
555
+ column: result.column,
556
+ category: rule.category,
557
+ suggestedFix: result.suggestedFix,
558
+ metadata: result.metadata,
559
+ });
560
+ }
561
+ }
562
+ }
563
+ catch (error) {
564
+ console.warn(`Error analyzing ${filePath}:`, error);
565
+ }
566
+ }
567
+ filesAnalyzed = filesToAnalyze.length;
568
+ // ============================================================================
569
+ // CACHE WRITE SYSTEM (Sequential Mode Only)
570
+ // ============================================================================
571
+ // After analyzing all files, write results to cache for future runs.
572
+ // This enables Phase 2 (cache reads) to skip unchanged files on subsequent runs.
573
+ //
574
+ // Cache directory: .angular-modernizer-cache/architecture/
575
+ // Cache entry format: Same as scan-solid (metadata + results[] + dependencies)
576
+ //
577
+ // Performance impact:
578
+ // - First run: Writes cache (adds ~1-2% overhead)
579
+ // - Second run: Reads cache (39x speedup - BEST improvement of all scan types!)
580
+ //
581
+ // Why Architecture benefits most from caching:
582
+ // - Architecture rules are computationally expensive:
583
+ // * Circular dependency detection requires graph traversals
584
+ // * Layer violation detection requires project-wide dependency analysis
585
+ // * God object detection requires complex metric calculations
586
+ // - Cache hit eliminates ALL graph algorithms and dependency traversals
587
+ // - 97.4% time saved on second run (202.8s → 5.2s)
588
+ //
589
+ // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
590
+ // This cache write logic is for sequential mode only.
591
+ // ============================================================================
592
+ const cacheManager = kernel.getCacheManager();
593
+ if (cacheManager) {
594
+ // Group violations by file path
595
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
596
+ const resultsByFile = new Map();
597
+ for (const violation of violations) {
598
+ const filePath = violation.filePath;
599
+ if (!resultsByFile.has(filePath)) {
600
+ resultsByFile.set(filePath, []);
601
+ }
602
+ resultsByFile.get(filePath).push(violation);
603
+ }
604
+ // Write each file's results to cache
605
+ for (const [filePath, fileResults] of resultsByFile.entries()) {
606
+ await cacheManager.setAnalysisResult(filePath, fileResults);
607
+ }
608
+ // Log cache effectiveness
609
+ const stats = cacheManager.getStats();
610
+ console.info(`Cache: Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
611
+ }
612
+ }
613
+ // Calculate summary (before pagination)
614
+ const summary = this.calculateSummary(violations);
615
+ const duration = Date.now() - startTime;
616
+ // Apply pagination to violations
617
+ const totalViolations = violations.length;
618
+ const maxResults = params.maxResults ?? 1000;
619
+ const resultOffset = params.resultOffset ?? 0;
620
+ const paginatedViolations = violations.slice(resultOffset, resultOffset + maxResults);
621
+ const paginationMetadata = {
622
+ totalResults: totalViolations,
623
+ returnedResults: paginatedViolations.length,
624
+ offset: resultOffset,
625
+ hasMore: resultOffset + maxResults < totalViolations,
626
+ };
627
+ // Gather orchestration stats using full Phase 6d/7b options
628
+ let orchestrationMetrics;
629
+ if (orchestration.parallel || orchestration.incremental) {
630
+ const stats = kernel.getOrchestrationStats();
631
+ orchestrationMetrics = {
632
+ parallel: orchestration.parallel ?? false,
633
+ incremental: orchestration.incremental ?? false,
634
+ useWorkerThreads: orchestration.useWorkerThreads,
635
+ autoSelectMode: orchestration.autoSelectMode,
636
+ filesAnalyzed,
637
+ filesSkipped: stats?.incremental.skippedFiles ?? 0,
638
+ cacheHitRate: stats?.incremental.cacheHitRate ?? 0,
639
+ duration,
640
+ throughput: filesAnalyzed > 0 ? filesAnalyzed / (duration / 1000) : 0,
641
+ workerStats: stats
642
+ ? {
643
+ completedTasks: stats.parallelExecution.completedTasks,
644
+ averageTaskDuration: stats.parallelExecution.averageTaskDuration,
645
+ totalCpuTime: stats.parallelExecution.totalCpuTime,
646
+ }
647
+ : undefined,
648
+ resourceUsage: orchestration.resourceLimits
649
+ ? {
650
+ maxWorkers: orchestration.resourceLimits.maxWorkers,
651
+ maxMemory: orchestration.resourceLimits.maxMemory,
652
+ }
653
+ : undefined,
654
+ };
655
+ }
656
+ const result = {
657
+ violations: paginatedViolations,
658
+ summary: {
659
+ ...summary,
660
+ analyzedFiles: filesAnalyzed,
661
+ },
662
+ metadata: {
663
+ rulesExecuted: rulesToRun.map((r) => r.id),
664
+ duration,
665
+ projectRoot: params.rootPath,
666
+ },
667
+ scope: resolvedScope.type !== 'all' ? resolvedScope : undefined,
668
+ pagination: paginationMetadata,
669
+ orchestration: orchestrationMetrics,
670
+ progress: lastProgress,
671
+ };
672
+ return result;
673
+ }
674
+ catch (error) {
675
+ throw new Error(`Architecture scan failed: ${error instanceof Error ? error.message : String(error)}`);
676
+ }
677
+ }
678
+ /**
679
+ * Execute analysis using fluent API.
680
+ */
681
+ async executeWithFluentApi(params) {
682
+ // Validate input
683
+ if (!params.rootPath || typeof params.rootPath !== 'string') {
684
+ throw new Error('rootPath is required and must be a string');
685
+ }
686
+ const startTime = Date.now();
687
+ try {
688
+ // Set defaults for exclude patterns
689
+ const defaultExcludePatterns = [
690
+ '**/node_modules/**',
691
+ '**/dist/**',
692
+ '**/build/**',
693
+ '**/coverage/**',
694
+ '**/e2e/**',
695
+ '**/.*/**',
696
+ '**/*.spec.ts',
697
+ '**/*.test.ts',
698
+ ];
699
+ const excludePatterns = [
700
+ ...defaultExcludePatterns,
701
+ ...(params.excludePatterns ?? []),
702
+ ];
703
+ const includePatterns = params.includePatterns ?? ['**/*.{ts,tsx}'];
704
+ // Find TypeScript config
705
+ const tsConfigPath = findTsConfig(params.rootPath);
706
+ if (!tsConfigPath) {
707
+ throw new Error('Could not find tsconfig.json in the project root');
708
+ }
709
+ // Initialize kernel with ArchitecturePlugin
710
+ const kernel = new Kernel({
711
+ tsConfigPath,
712
+ plugins: [new ArchitecturePlugin()],
713
+ projectOptions: {
714
+ skipAddingFilesFromTsConfig: true,
715
+ },
716
+ cacheConfig: createToolCacheConfig(params.rootPath, 'architecture'),
717
+ });
718
+ await kernel.initialize();
719
+ // Get analysis rules from ArchitecturePlugin
720
+ const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
721
+ const allRules = archPlugin.getAnalysisRules();
722
+ const rulesToRun = params.rules
723
+ ? allRules.filter((rule) => params.rules.includes(rule.id))
724
+ : allRules;
725
+ console.info(`ScanArchitecture (Fluent): Found ${allRules.length} total rules, running ${rulesToRun.length} rules:`, rulesToRun.map((r) => r.id));
726
+ if (rulesToRun.length === 0) {
727
+ throw new Error('No matching rules found');
728
+ }
729
+ // Find files to analyze — resolve scope BEFORE applying maxFiles cap so
730
+ // that scope filtering happens on the full set, not on an arbitrary prefix.
731
+ const maxFiles = params.maxFiles ?? 100;
732
+ const resolvedScope = this.resolveScope(params.rootPath, params.scope);
733
+ const allDiscoveredFiles = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, Number.MAX_SAFE_INTEGER);
734
+ const scopeFiltered = resolvedScope.type !== 'all'
735
+ ? this.filterFilesByScope(allDiscoveredFiles, resolvedScope)
736
+ : allDiscoveredFiles;
737
+ const filesToAnalyze = scopeFiltered.slice(0, maxFiles);
738
+ console.info(`Found ${filesToAnalyze.length} files to analyze` +
739
+ (resolvedScope.type !== 'all'
740
+ ? ` (scope: ${resolvedScope.type}, ${scopeFiltered.length} matched before cap)`
741
+ : ''));
742
+ if (filesToAnalyze.length === 0) {
743
+ throw new Error('No files found to analyze');
744
+ }
745
+ // Load config from .angular-modernizer.json so config-driven rules (e.g.
746
+ // architecture:layer-boundary-violation) receive their layers/rule overrides.
747
+ const fullConfig = loadConfig(params.rootPath);
748
+ const rulesConfig = fullConfig.rules ?? {};
749
+ // Run rules directly — FluentKernel creates contexts without user config,
750
+ // causing config-driven rules to return 0 violations (Bug 1/3).
751
+ const project = kernel.getProject();
752
+ const api = createPublicApi(project);
753
+ const violations = [];
754
+ let filesAnalyzed = 0;
755
+ for (const filePath of filesToAnalyze) {
756
+ try {
757
+ const sourceFile = project.addSourceFileAtPath(filePath);
758
+ for (const rule of rulesToRun) {
759
+ const results = await rule.analyze(ContextFactory.createAnalysisContext({
760
+ sourceFile,
761
+ project,
762
+ api: api,
763
+ config: rulesConfig,
764
+ }));
765
+ for (const result of results) {
766
+ violations.push({
767
+ id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
768
+ ruleId: result.ruleId,
769
+ severity: rule.severity,
770
+ message: result.message,
771
+ filePath: result.filePath,
772
+ line: result.line,
773
+ column: result.column,
774
+ category: rule.category,
775
+ suggestedFix: result.suggestedFix,
776
+ metadata: result.metadata,
777
+ });
778
+ }
779
+ }
780
+ filesAnalyzed++;
781
+ }
782
+ catch (error) {
783
+ console.warn(`Error analyzing ${filePath}:`, error);
784
+ }
785
+ }
786
+ const duration = Date.now() - startTime;
787
+ const summary = this.calculateSummary(violations);
788
+ return {
789
+ violations,
790
+ summary: {
791
+ ...summary,
792
+ analyzedFiles: filesAnalyzed,
793
+ },
794
+ metadata: {
795
+ rulesExecuted: rulesToRun.map((r) => r.id),
796
+ duration,
797
+ projectRoot: params.rootPath,
798
+ },
799
+ pipeline: ['analyze'],
800
+ intermediateResults: {
801
+ analyze: {
802
+ success: true,
803
+ violations: violations.length,
804
+ message: `Analysis completed with ${violations.length} violations`,
805
+ },
806
+ },
807
+ };
808
+ }
809
+ catch (error) {
810
+ throw new Error(`Architecture analysis failed: ${error instanceof Error ? error.message : String(error)}`);
811
+ }
812
+ }
813
+ /**
814
+ * Execute streaming analysis - returns operationId immediately.
815
+ * Analysis runs in background with progress stored in ProgressStore.
816
+ */
817
+ async executeStreaming(params) {
818
+ const operationId = randomUUID();
819
+ const store = ProgressStore.getInstance();
820
+ // Validate input
821
+ if (!params.rootPath || typeof params.rootPath !== 'string') {
822
+ throw new Error('rootPath is required and must be a string');
823
+ }
824
+ // Create operation in store
825
+ store.createOperation(operationId, {
826
+ operationId,
827
+ type: 'analysis',
828
+ startTime: Date.now(),
829
+ });
830
+ // Start analysis in background (don't await)
831
+ this.runStreamingAnalysis(operationId, params).catch((error) => {
832
+ // Mark operation as failed if error occurs
833
+ store.markFailed(operationId, error instanceof Error ? error.message : String(error));
834
+ });
835
+ // Return operationId immediately
836
+ return {
837
+ operationId,
838
+ violations: [],
839
+ summary: {
840
+ totalViolations: 0,
841
+ analyzedFiles: 0,
842
+ bySeverity: {},
843
+ byCategory: {},
844
+ byRule: {},
845
+ },
846
+ metadata: {
847
+ rulesExecuted: [],
848
+ duration: 0,
849
+ projectRoot: params.rootPath,
850
+ },
851
+ };
852
+ }
853
+ /**
854
+ * Run streaming analysis in background.
855
+ */
856
+ async runStreamingAnalysis(operationId, params) {
857
+ const store = ProgressStore.getInstance();
858
+ // Add start event
859
+ store.addEvent(operationId, {
860
+ phase: 'analyzing',
861
+ message: `Starting architecture scan of ${params.rootPath}`,
862
+ percentage: 0,
863
+ timestamp: Date.now(),
864
+ });
865
+ // Load configuration
866
+ const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
867
+ const mergedParams = {
868
+ ...config,
869
+ ...params,
870
+ };
871
+ const orchestration = mergedParams.orchestration ?? {};
872
+ // Find tsconfig
873
+ const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(params.rootPath);
874
+ if (!tsConfigPath) {
875
+ throw new Error('Could not find tsconfig.json in the project root');
876
+ }
877
+ // Add progress event
878
+ store.addEvent(operationId, {
879
+ phase: 'analyzing',
880
+ message: 'Initializing kernel...',
881
+ percentage: 10,
882
+ timestamp: Date.now(),
883
+ });
884
+ // Initialize kernel
885
+ const kernel = new Kernel({
886
+ tsConfigPath,
887
+ plugins: [new ArchitecturePlugin()],
888
+ projectOptions: {
889
+ skipAddingFilesFromTsConfig: true,
890
+ },
891
+ cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'architecture'),
892
+ });
893
+ await kernel.initialize();
894
+ // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
895
+ const streamingFullConfig = loadConfig(params.rootPath);
896
+ const streamingRulesConfig = streamingFullConfig.rules;
897
+ // Add progress event
898
+ store.addEvent(operationId, {
899
+ phase: 'analyzing',
900
+ message: 'Finding files to analyze...',
901
+ percentage: 20,
902
+ timestamp: Date.now(),
903
+ });
904
+ // Find files to analyze
905
+ const includePatterns = params.includePatterns ?? ['**/*.{ts,tsx}'];
906
+ const defaultExcludePatterns = [
907
+ '**/node_modules/**',
908
+ '**/dist/**',
909
+ '**/build/**',
910
+ '**/coverage/**',
911
+ '**/e2e/**',
912
+ '**/.*/**',
913
+ '**/*.spec.ts',
914
+ '**/*.test.ts',
915
+ ];
916
+ const excludePatterns = [
917
+ ...defaultExcludePatterns,
918
+ ...(params.excludePatterns ?? []),
919
+ ];
920
+ const maxFiles = params.maxFiles ?? 100;
921
+ const streamingResolvedScope = this.resolveScope(params.rootPath, params.scope);
922
+ const streamingAllFiles = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, Number.MAX_SAFE_INTEGER);
923
+ const streamingScopeFiltered = streamingResolvedScope.type !== 'all'
924
+ ? this.filterFilesByScope(streamingAllFiles, streamingResolvedScope)
925
+ : streamingAllFiles;
926
+ const filesToAnalyze = streamingScopeFiltered.slice(0, maxFiles);
927
+ // Add progress event
928
+ store.addEvent(operationId, {
929
+ phase: 'analyzing',
930
+ message: `Analyzing ${filesToAnalyze.length} files...`,
931
+ percentage: 30,
932
+ timestamp: Date.now(),
933
+ });
934
+ // Get rules
935
+ const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
936
+ const allRules = archPlugin.getAnalysisRules();
937
+ const rulesToRun = params.rules
938
+ ? allRules.filter((rule) => params.rules.includes(rule.id))
939
+ : allRules;
940
+ // Analyze files
941
+ const project = kernel.getProject();
942
+ const api = createPublicApi(project);
943
+ const violations = [];
944
+ let filesProcessed = 0;
945
+ for (const filePath of filesToAnalyze) {
946
+ if (store.isCancelled(operationId)) {
947
+ break;
948
+ }
949
+ try {
950
+ const sourceFile = project.addSourceFileAtPath(filePath);
951
+ for (const rule of rulesToRun) {
952
+ const results = await rule.analyze(ContextFactory.createAnalysisContext({
953
+ sourceFile,
954
+ project,
955
+ api: api,
956
+ config: streamingRulesConfig,
957
+ }));
958
+ for (const result of results) {
959
+ violations.push({
960
+ id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
961
+ ruleId: result.ruleId,
962
+ severity: rule.severity,
963
+ message: result.message,
964
+ filePath: result.filePath,
965
+ line: result.line,
966
+ column: result.column,
967
+ category: rule.category,
968
+ suggestedFix: result.suggestedFix,
969
+ metadata: result.metadata,
970
+ });
971
+ }
972
+ }
973
+ filesProcessed++;
974
+ const percentage = 30 + Math.round((filesProcessed / filesToAnalyze.length) * 60);
975
+ // Add progress event every 10 files
976
+ if (filesProcessed % 10 === 0 ||
977
+ filesProcessed === filesToAnalyze.length) {
978
+ store.addEvent(operationId, {
979
+ phase: 'analyzing',
980
+ message: `Analyzed ${filesProcessed}/${filesToAnalyze.length} files, found ${violations.length} violations`,
981
+ percentage,
982
+ timestamp: Date.now(),
983
+ });
984
+ }
985
+ }
986
+ catch (error) {
987
+ console.warn(`Error analyzing ${filePath}:`, error);
988
+ }
989
+ }
990
+ // Add completion event
991
+ store.addEvent(operationId, {
992
+ phase: 'complete',
993
+ message: `Analysis complete: ${violations.length} violations found in ${filesProcessed} files`,
994
+ percentage: 100,
995
+ timestamp: Date.now(),
996
+ });
997
+ // Store full result so get-operation-progress can return violations
998
+ const summary = this.calculateSummary(violations);
999
+ store.setResult(operationId, {
1000
+ violations,
1001
+ summary: {
1002
+ ...summary,
1003
+ analyzedFiles: filesProcessed,
1004
+ },
1005
+ metadata: {
1006
+ rulesExecuted: rulesToRun.map((r) => r.id),
1007
+ duration: Date.now() - store.getMetadata(operationId).startTime,
1008
+ projectRoot: params.rootPath,
1009
+ },
1010
+ });
1011
+ // Mark complete
1012
+ store.markComplete(operationId);
1013
+ }
1014
+ /**
1015
+ * Find files to analyze based on patterns.
1016
+ */
1017
+ async findFilesToAnalyze(rootPath, includePatterns, excludePatterns, maxFiles) {
1018
+ const allFiles = [];
1019
+ for (const pattern of includePatterns) {
1020
+ const files = await glob(pattern, {
1021
+ cwd: rootPath,
1022
+ absolute: true,
1023
+ ignore: excludePatterns,
1024
+ });
1025
+ allFiles.push(...files);
1026
+ }
1027
+ // Remove duplicates and limit
1028
+ const uniqueFiles = [...new Set(allFiles)].slice(0, maxFiles);
1029
+ // Filter to only TypeScript files and ensure they are actual files (not directories)
1030
+ return uniqueFiles.filter((file) => {
1031
+ const isTsFile = ['.ts', '.tsx'].includes(extname(file));
1032
+ if (!isTsFile) {
1033
+ return false;
1034
+ }
1035
+ try {
1036
+ const stats = statSync(file);
1037
+ return stats.isFile();
1038
+ }
1039
+ catch (error) {
1040
+ // If we can't stat the file, skip it
1041
+ console.warn(`Cannot access file ${file}:`, error);
1042
+ return false;
1043
+ }
1044
+ });
1045
+ }
1046
+ /**
1047
+ * Calculate summary statistics from violations.
1048
+ */
1049
+ calculateSummary(violations) {
1050
+ const bySeverity = {};
1051
+ const byCategory = {};
1052
+ const byRule = {};
1053
+ for (const violation of violations) {
1054
+ bySeverity[violation.severity] =
1055
+ (bySeverity[violation.severity] ?? 0) + 1;
1056
+ byCategory[violation.category] =
1057
+ (byCategory[violation.category] ?? 0) + 1;
1058
+ byRule[violation.ruleId] = (byRule[violation.ruleId] ?? 0) + 1;
1059
+ }
1060
+ return {
1061
+ totalViolations: violations.length,
1062
+ bySeverity,
1063
+ byCategory,
1064
+ byRule,
1065
+ };
1066
+ }
1067
+ /**
1068
+ * Load configuration from .angular-modernizer.json file.
1069
+ * Only loads from the provided root path to avoid cache directory issues.
1070
+ */
1071
+ loadConfig(providedRootPath) {
1072
+ // Only load config if rootPath is explicitly provided
1073
+ // This prevents accidentally using process.cwd() which may point to the MCP server directory
1074
+ if (!providedRootPath) {
1075
+ return {};
1076
+ }
1077
+ const configPath = resolve(providedRootPath, '.angular-modernizer.json');
1078
+ if (existsSync(configPath)) {
1079
+ try {
1080
+ // Disable no-unsafe-assignment: JSON.parse() returns 'any' but config structure is validated below
1081
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1082
+ const config = JSON.parse(readFileSync(configPath, 'utf-8'));
1083
+ // Disable no-unsafe-member-access: Optional chaining safely handles missing properties
1084
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
1085
+ const scanArchitectureConfig = config['scan-architecture'];
1086
+ if (scanArchitectureConfig &&
1087
+ typeof scanArchitectureConfig === 'object') {
1088
+ return scanArchitectureConfig;
1089
+ }
1090
+ }
1091
+ catch (error) {
1092
+ console.warn(`Error loading config from ${configPath}:`, error);
1093
+ }
1094
+ }
1095
+ return {};
1096
+ }
1097
+ /**
1098
+ * Resolve scope configuration to actual file paths.
1099
+ * Reads angular.json to find project paths.
1100
+ */
1101
+ resolveScope(rootPath, scope) {
1102
+ // Default to scanning all
1103
+ if (!scope || scope.type === 'all') {
1104
+ return {
1105
+ type: 'all',
1106
+ resolvedPaths: [rootPath],
1107
+ matchedFiles: 0, // Will be calculated later
1108
+ };
1109
+ }
1110
+ const resolvedPaths = [];
1111
+ const angularJsonPath = resolve(rootPath, 'angular.json');
1112
+ // Parse angular.json to get project information
1113
+ const angularProjects = [];
1114
+ if (existsSync(angularJsonPath)) {
1115
+ try {
1116
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1117
+ const angularJson = JSON.parse(readFileSync(angularJsonPath, 'utf-8'));
1118
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1119
+ const projects = angularJson.projects;
1120
+ if (projects) {
1121
+ for (const [name, config] of Object.entries(projects)) {
1122
+ angularProjects.push({
1123
+ name,
1124
+ projectType: config.projectType ?? 'application',
1125
+ root: config.root ?? '',
1126
+ sourceRoot: config.sourceRoot,
1127
+ });
1128
+ }
1129
+ }
1130
+ }
1131
+ catch (error) {
1132
+ console.warn('Error parsing angular.json for scope resolution:', error);
1133
+ }
1134
+ }
1135
+ switch (scope.type) {
1136
+ case 'applications': {
1137
+ const apps = angularProjects.filter((p) => p.projectType === 'application');
1138
+ const targetApps = scope.names?.length
1139
+ ? apps.filter((app) => scope.names.includes(app.name))
1140
+ : apps;
1141
+ for (const app of targetApps) {
1142
+ const appPath = app.sourceRoot ?? app.root;
1143
+ resolvedPaths.push(resolve(rootPath, appPath));
1144
+ }
1145
+ return {
1146
+ type: 'applications',
1147
+ names: targetApps.map((a) => a.name),
1148
+ resolvedPaths,
1149
+ matchedFiles: 0,
1150
+ };
1151
+ }
1152
+ case 'libraries': {
1153
+ const libs = angularProjects.filter((p) => p.projectType === 'library');
1154
+ const targetLibs = scope.names?.length
1155
+ ? libs.filter((lib) => scope.names.includes(lib.name))
1156
+ : libs;
1157
+ for (const lib of targetLibs) {
1158
+ const libPath = lib.sourceRoot ?? lib.root;
1159
+ if (libPath) {
1160
+ resolvedPaths.push(resolve(rootPath, libPath));
1161
+ }
1162
+ }
1163
+ return {
1164
+ type: 'libraries',
1165
+ names: targetLibs.map((l) => l.name),
1166
+ resolvedPaths,
1167
+ matchedFiles: 0,
1168
+ };
1169
+ }
1170
+ case 'features': {
1171
+ // Features are typically in src/app/features/* or projects/*/src/lib/*
1172
+ const featurePaths = [
1173
+ 'src/app/features',
1174
+ 'src/features',
1175
+ ...angularProjects
1176
+ .filter((p) => p.projectType === 'library')
1177
+ .map((p) => `${p.sourceRoot ?? p.root}/lib`),
1178
+ ];
1179
+ for (const basePath of featurePaths) {
1180
+ const fullBasePath = resolve(rootPath, basePath);
1181
+ if (existsSync(fullBasePath)) {
1182
+ if (scope.names?.length) {
1183
+ // Scan specific features
1184
+ for (const featureName of scope.names) {
1185
+ const featurePath = resolve(fullBasePath, featureName);
1186
+ if (existsSync(featurePath)) {
1187
+ resolvedPaths.push(featurePath);
1188
+ }
1189
+ }
1190
+ }
1191
+ else {
1192
+ // Scan all features in this directory
1193
+ resolvedPaths.push(fullBasePath);
1194
+ }
1195
+ }
1196
+ }
1197
+ return {
1198
+ type: 'features',
1199
+ names: scope.names,
1200
+ resolvedPaths,
1201
+ matchedFiles: 0,
1202
+ };
1203
+ }
1204
+ case 'modules': {
1205
+ // Modules are Angular NgModules - scan by module name pattern
1206
+ // Look for *.module.ts files in common locations
1207
+ const modulePaths = [
1208
+ 'src/app',
1209
+ ...angularProjects
1210
+ .filter((p) => p.projectType === 'application')
1211
+ .map((p) => p.sourceRoot ?? p.root),
1212
+ ...angularProjects
1213
+ .filter((p) => p.projectType === 'library')
1214
+ .map((p) => p.sourceRoot ?? p.root),
1215
+ ].filter(Boolean);
1216
+ if (scope.names?.length) {
1217
+ // Scan specific modules by name
1218
+ // Module names like 'shared', 'core', 'feature-x' map to:
1219
+ // - src/app/shared/ (SharedModule)
1220
+ // - src/app/core/ (CoreModule)
1221
+ // - src/app/feature-x/ (FeatureXModule)
1222
+ for (const moduleName of scope.names) {
1223
+ for (const basePath of modulePaths) {
1224
+ const modulePath = resolve(rootPath, basePath, moduleName);
1225
+ if (existsSync(modulePath)) {
1226
+ resolvedPaths.push(modulePath);
1227
+ }
1228
+ // Also check for module in features folder
1229
+ const featureModulePath = resolve(rootPath, basePath, 'features', moduleName);
1230
+ if (existsSync(featureModulePath)) {
1231
+ resolvedPaths.push(featureModulePath);
1232
+ }
1233
+ }
1234
+ }
1235
+ }
1236
+ else {
1237
+ // Scan all module directories (folders containing *.module.ts)
1238
+ for (const basePath of modulePaths) {
1239
+ const fullBasePath = resolve(rootPath, basePath);
1240
+ if (existsSync(fullBasePath)) {
1241
+ resolvedPaths.push(fullBasePath);
1242
+ }
1243
+ }
1244
+ }
1245
+ return {
1246
+ type: 'modules',
1247
+ names: scope.names,
1248
+ resolvedPaths: [...new Set(resolvedPaths)], // Remove duplicates
1249
+ matchedFiles: 0,
1250
+ };
1251
+ }
1252
+ case 'folders': {
1253
+ if (scope.paths?.length) {
1254
+ for (const folderPath of scope.paths) {
1255
+ const fullPath = resolve(rootPath, folderPath);
1256
+ if (existsSync(fullPath)) {
1257
+ resolvedPaths.push(fullPath);
1258
+ }
1259
+ }
1260
+ }
1261
+ return {
1262
+ type: 'folders',
1263
+ paths: scope.paths,
1264
+ resolvedPaths,
1265
+ matchedFiles: 0,
1266
+ };
1267
+ }
1268
+ default:
1269
+ return {
1270
+ type: 'all',
1271
+ resolvedPaths: [rootPath],
1272
+ matchedFiles: 0,
1273
+ };
1274
+ }
1275
+ }
1276
+ /**
1277
+ * Filter files based on resolved scope paths.
1278
+ */
1279
+ filterFilesByScope(files, resolvedScope) {
1280
+ if (resolvedScope.type === 'all' ||
1281
+ resolvedScope.resolvedPaths.length === 0) {
1282
+ return files;
1283
+ }
1284
+ return files.filter((file) => {
1285
+ return resolvedScope.resolvedPaths.some((scopePath) => file.startsWith(scopePath) ||
1286
+ file.startsWith(scopePath.replaceAll('\\', '/')));
1287
+ });
1288
+ }
1289
+ }
1290
+ //# sourceMappingURL=scan-architecture.js.map