@angular-modernizer/adapter-mcp 0.2.0 → 1.0.0

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 (255) hide show
  1. package/README.md +188 -235
  2. package/dist/cli.js +77 -27
  3. package/dist/index.d.ts +11 -3
  4. package/dist/index.js +10 -2
  5. package/dist/mcp-watcher.d.ts +6 -1
  6. package/dist/mcp-watcher.js +14 -10
  7. package/dist/server/limited-stdio-transport.d.ts +68 -0
  8. package/dist/server/limited-stdio-transport.js +115 -0
  9. package/dist/server/mcp-server.d.ts +41 -12
  10. package/dist/server/mcp-server.js +113 -94
  11. package/dist/server/package-version.d.ts +16 -0
  12. package/dist/server/package-version.js +37 -0
  13. package/dist/server/sdk-server.d.ts +70 -0
  14. package/dist/server/sdk-server.js +113 -0
  15. package/dist/server/stdio-guard.d.ts +20 -0
  16. package/dist/server/stdio-guard.js +48 -0
  17. package/dist/server/tool-registry.d.ts +3 -2
  18. package/dist/server/tool-registry.js +5 -5
  19. package/dist/tools/analyze-build-impact.d.ts +346 -14
  20. package/dist/tools/analyze-build-impact.js +315 -31
  21. package/dist/tools/analyze-core-to-shared.d.ts +134 -4
  22. package/dist/tools/analyze-core-to-shared.js +113 -9
  23. package/dist/tools/analyze-parser-performance.d.ts +200 -7
  24. package/dist/tools/analyze-parser-performance.js +108 -47
  25. package/dist/tools/analyze-project.d.ts +267 -5
  26. package/dist/tools/analyze-project.js +196 -8
  27. package/dist/tools/check-incremental-compatibility.d.ts +61 -1
  28. package/dist/tools/check-incremental-compatibility.js +58 -2
  29. package/dist/tools/collect-feedback.d.ts +199 -10
  30. package/dist/tools/collect-feedback.js +171 -99
  31. package/dist/tools/compare-health.d.ts +356 -0
  32. package/dist/tools/compare-health.js +472 -0
  33. package/dist/tools/extract-libraries.d.ts +156 -4
  34. package/dist/tools/extract-libraries.js +115 -10
  35. package/dist/tools/find-angular-symbol.d.ts +98 -9
  36. package/dist/tools/find-angular-symbol.js +104 -12
  37. package/dist/tools/find-component-hosts.d.ts +684 -0
  38. package/dist/tools/find-component-hosts.js +441 -0
  39. package/dist/tools/find-usages.d.ts +99 -4
  40. package/dist/tools/find-usages.js +131 -11
  41. package/dist/tools/get-bootstrap-execution.d.ts +258 -0
  42. package/dist/tools/get-bootstrap-execution.js +324 -0
  43. package/dist/tools/get-call-graph.d.ts +139 -4
  44. package/dist/tools/get-call-graph.js +123 -13
  45. package/dist/tools/get-operation-progress-tool.d.ts +114 -2
  46. package/dist/tools/get-operation-progress-tool.js +114 -7
  47. package/dist/tools/get-operation-progress.d.ts +1 -1
  48. package/dist/tools/get-operation-progress.js +5 -5
  49. package/dist/tools/helpers/analysis-output.d.ts +177 -0
  50. package/dist/tools/helpers/analysis-output.js +165 -0
  51. package/dist/tools/helpers/build-schemas.d.ts +36 -0
  52. package/dist/tools/helpers/build-schemas.js +23 -0
  53. package/dist/tools/helpers/citation-file-source.d.ts +10 -0
  54. package/dist/tools/helpers/citation-file-source.js +82 -0
  55. package/dist/tools/helpers/compact-output.d.ts +61 -0
  56. package/dist/tools/helpers/compact-output.js +83 -0
  57. package/dist/tools/helpers/finding-window.d.ts +43 -0
  58. package/dist/tools/helpers/finding-window.js +64 -0
  59. package/dist/tools/helpers/health-delta.d.ts +86 -0
  60. package/dist/tools/helpers/health-delta.js +239 -0
  61. package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
  62. package/dist/tools/helpers/investigation-schemas.js +48 -0
  63. package/dist/tools/helpers/library-imports.d.ts +57 -0
  64. package/dist/tools/helpers/library-imports.js +151 -0
  65. package/dist/tools/helpers/load-source-files.d.ts +30 -0
  66. package/dist/tools/helpers/load-source-files.js +34 -0
  67. package/dist/tools/helpers/output-contract.d.ts +32 -0
  68. package/dist/tools/helpers/output-contract.js +32 -0
  69. package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
  70. package/dist/tools/helpers/platform-root-resolver.js +75 -48
  71. package/dist/tools/helpers/process-output.d.ts +19 -0
  72. package/dist/tools/helpers/process-output.js +31 -0
  73. package/dist/tools/helpers/project-cache.d.ts +184 -0
  74. package/dist/tools/helpers/project-cache.js +331 -0
  75. package/dist/tools/helpers/project-decorators.d.ts +14 -0
  76. package/dist/tools/helpers/project-decorators.js +22 -0
  77. package/dist/tools/helpers/rule-matcher.js +5 -0
  78. package/dist/tools/helpers/rule-runner.d.ts +72 -0
  79. package/dist/tools/helpers/rule-runner.js +131 -0
  80. package/dist/tools/helpers/scan-cache.d.ts +22 -0
  81. package/dist/tools/helpers/scan-cache.js +34 -0
  82. package/dist/tools/helpers/scan-plan.d.ts +48 -0
  83. package/dist/tools/helpers/scan-plan.js +166 -0
  84. package/dist/tools/helpers/scope-paths.d.ts +17 -0
  85. package/dist/tools/helpers/scope-paths.js +32 -0
  86. package/dist/tools/helpers/stack-frame-file-index.d.ts +10 -0
  87. package/dist/tools/helpers/stack-frame-file-index.js +71 -0
  88. package/dist/tools/helpers/tool-context.d.ts +60 -0
  89. package/dist/tools/helpers/tool-context.js +82 -0
  90. package/dist/tools/helpers/transform-safety.d.ts +40 -0
  91. package/dist/tools/helpers/transform-safety.js +87 -0
  92. package/dist/tools/helpers/validation-output.d.ts +53 -0
  93. package/dist/tools/helpers/validation-output.js +48 -0
  94. package/dist/tools/inspect-form-group.d.ts +324 -0
  95. package/dist/tools/inspect-form-group.js +279 -0
  96. package/dist/tools/inspect-i18n.d.ts +466 -0
  97. package/dist/tools/inspect-i18n.js +400 -0
  98. package/dist/tools/inspect-template.d.ts +320 -0
  99. package/dist/tools/inspect-template.js +324 -0
  100. package/dist/tools/learn-patterns.d.ts +122 -1
  101. package/dist/tools/learn-patterns.js +97 -2
  102. package/dist/tools/list-imports.d.ts +128 -11
  103. package/dist/tools/list-imports.js +128 -8
  104. package/dist/tools/orchestrate-migration.d.ts +129 -5
  105. package/dist/tools/orchestrate-migration.js +166 -12
  106. package/dist/tools/parse-stack-trace.d.ts +59 -2
  107. package/dist/tools/parse-stack-trace.js +52 -4
  108. package/dist/tools/plan-migration.d.ts +418 -1
  109. package/dist/tools/plan-migration.js +355 -8
  110. package/dist/tools/resolve-type.d.ts +42 -1
  111. package/dist/tools/resolve-type.js +37 -4
  112. package/dist/tools/review-feedback.d.ts +206 -11
  113. package/dist/tools/review-feedback.js +132 -51
  114. package/dist/tools/rollback-changes.d.ts +79 -2
  115. package/dist/tools/rollback-changes.js +66 -14
  116. package/dist/tools/run-angular-cli.d.ts +45 -2
  117. package/dist/tools/run-angular-cli.js +67 -7
  118. package/dist/tools/run-build.d.ts +114 -2
  119. package/dist/tools/run-build.js +117 -8
  120. package/dist/tools/run-schematic.d.ts +70 -2
  121. package/dist/tools/run-schematic.js +104 -10
  122. package/dist/tools/scan-all.d.ts +24 -16
  123. package/dist/tools/scan-all.js +145 -137
  124. package/dist/tools/scan-angular.d.ts +20 -11
  125. package/dist/tools/scan-angular.js +52 -24
  126. package/dist/tools/scan-architecture.d.ts +42 -14
  127. package/dist/tools/scan-architecture.js +206 -163
  128. package/dist/tools/scan-solid.d.ts +20 -11
  129. package/dist/tools/scan-solid.js +52 -24
  130. package/dist/tools/search-codebase.d.ts +85 -1
  131. package/dist/tools/search-codebase.js +61 -4
  132. package/dist/tools/server-status.d.ts +370 -0
  133. package/dist/tools/server-status.js +369 -0
  134. package/dist/tools/suggest-improvements.d.ts +97 -5
  135. package/dist/tools/suggest-improvements.js +80 -44
  136. package/dist/tools/trace-output-flow.d.ts +791 -0
  137. package/dist/tools/trace-output-flow.js +668 -0
  138. package/dist/tools/transform-code-batch.d.ts +3 -0
  139. package/dist/tools/transform-code-batch.js +10 -5
  140. package/dist/tools/transform-code.d.ts +335 -12
  141. package/dist/tools/transform-code.js +649 -608
  142. package/dist/tools/validate-before-transform.d.ts +116 -2
  143. package/dist/tools/validate-before-transform.js +55 -2
  144. package/dist/tools/validate-project-compatibility.d.ts +64 -2
  145. package/dist/tools/validate-project-compatibility.js +67 -4
  146. package/dist/tools/validate-transformation.d.ts +220 -2
  147. package/dist/tools/validate-transformation.js +113 -15
  148. package/dist/tools/verify-citations.d.ts +181 -0
  149. package/dist/tools/verify-citations.js +218 -0
  150. package/dist/types.d.ts +45 -1
  151. package/dist/utils/format-tool-response.d.ts +22 -59
  152. package/dist/utils/format-tool-response.js +25 -134
  153. package/package.json +30 -13
  154. package/dist/cli.d.ts.map +0 -1
  155. package/dist/cli.js.map +0 -1
  156. package/dist/core/project-analyzer.d.ts.map +0 -1
  157. package/dist/core/project-analyzer.js.map +0 -1
  158. package/dist/index.d.ts.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/mcp-watcher.d.ts.map +0 -1
  161. package/dist/mcp-watcher.js.map +0 -1
  162. package/dist/server/json-rpc-handler.d.ts +0 -57
  163. package/dist/server/json-rpc-handler.d.ts.map +0 -1
  164. package/dist/server/json-rpc-handler.js +0 -222
  165. package/dist/server/json-rpc-handler.js.map +0 -1
  166. package/dist/server/mcp-server.d.ts.map +0 -1
  167. package/dist/server/mcp-server.js.map +0 -1
  168. package/dist/server/tool-registry.d.ts.map +0 -1
  169. package/dist/server/tool-registry.js.map +0 -1
  170. package/dist/streaming/progress-store.d.ts.map +0 -1
  171. package/dist/streaming/progress-store.js.map +0 -1
  172. package/dist/tools/analyze-build-impact.d.ts.map +0 -1
  173. package/dist/tools/analyze-build-impact.js.map +0 -1
  174. package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
  175. package/dist/tools/analyze-core-to-shared.js.map +0 -1
  176. package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
  177. package/dist/tools/analyze-parser-performance.js.map +0 -1
  178. package/dist/tools/analyze-project.d.ts.map +0 -1
  179. package/dist/tools/analyze-project.js.map +0 -1
  180. package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
  181. package/dist/tools/check-incremental-compatibility.js.map +0 -1
  182. package/dist/tools/collect-feedback.d.ts.map +0 -1
  183. package/dist/tools/collect-feedback.js.map +0 -1
  184. package/dist/tools/extract-libraries.d.ts.map +0 -1
  185. package/dist/tools/extract-libraries.js.map +0 -1
  186. package/dist/tools/find-angular-symbol.d.ts.map +0 -1
  187. package/dist/tools/find-angular-symbol.js.map +0 -1
  188. package/dist/tools/find-usages.d.ts.map +0 -1
  189. package/dist/tools/find-usages.js.map +0 -1
  190. package/dist/tools/get-call-graph.d.ts.map +0 -1
  191. package/dist/tools/get-call-graph.js.map +0 -1
  192. package/dist/tools/get-operation-progress-tool.d.ts.map +0 -1
  193. package/dist/tools/get-operation-progress-tool.js.map +0 -1
  194. package/dist/tools/get-operation-progress.d.ts.map +0 -1
  195. package/dist/tools/get-operation-progress.js.map +0 -1
  196. package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
  197. package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
  198. package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
  199. package/dist/tools/helpers/find-ts-config.js.map +0 -1
  200. package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
  201. package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
  202. package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
  203. package/dist/tools/helpers/rule-matcher.js.map +0 -1
  204. package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
  205. package/dist/tools/helpers/suggestion-generator.js.map +0 -1
  206. package/dist/tools/learn-patterns.d.ts.map +0 -1
  207. package/dist/tools/learn-patterns.js.map +0 -1
  208. package/dist/tools/list-imports.d.ts.map +0 -1
  209. package/dist/tools/list-imports.js.map +0 -1
  210. package/dist/tools/orchestrate-migration.d.ts.map +0 -1
  211. package/dist/tools/orchestrate-migration.js.map +0 -1
  212. package/dist/tools/parse-stack-trace.d.ts.map +0 -1
  213. package/dist/tools/parse-stack-trace.js.map +0 -1
  214. package/dist/tools/plan-migration.d.ts.map +0 -1
  215. package/dist/tools/plan-migration.js.map +0 -1
  216. package/dist/tools/resolve-type.d.ts.map +0 -1
  217. package/dist/tools/resolve-type.js.map +0 -1
  218. package/dist/tools/review-feedback.d.ts.map +0 -1
  219. package/dist/tools/review-feedback.js.map +0 -1
  220. package/dist/tools/rollback-changes.d.ts.map +0 -1
  221. package/dist/tools/rollback-changes.js.map +0 -1
  222. package/dist/tools/run-angular-cli.d.ts.map +0 -1
  223. package/dist/tools/run-angular-cli.js.map +0 -1
  224. package/dist/tools/run-build.d.ts.map +0 -1
  225. package/dist/tools/run-build.js.map +0 -1
  226. package/dist/tools/run-schematic.d.ts.map +0 -1
  227. package/dist/tools/run-schematic.js.map +0 -1
  228. package/dist/tools/scan-all.d.ts.map +0 -1
  229. package/dist/tools/scan-all.js.map +0 -1
  230. package/dist/tools/scan-angular.d.ts.map +0 -1
  231. package/dist/tools/scan-angular.js.map +0 -1
  232. package/dist/tools/scan-architecture.d.ts.map +0 -1
  233. package/dist/tools/scan-architecture.js.map +0 -1
  234. package/dist/tools/scan-solid.d.ts.map +0 -1
  235. package/dist/tools/scan-solid.js.map +0 -1
  236. package/dist/tools/search-codebase.d.ts.map +0 -1
  237. package/dist/tools/search-codebase.js.map +0 -1
  238. package/dist/tools/shared/scan-types.d.ts.map +0 -1
  239. package/dist/tools/shared/scan-types.js.map +0 -1
  240. package/dist/tools/suggest-improvements.d.ts.map +0 -1
  241. package/dist/tools/suggest-improvements.js.map +0 -1
  242. package/dist/tools/transform-code-batch.d.ts.map +0 -1
  243. package/dist/tools/transform-code-batch.js.map +0 -1
  244. package/dist/tools/transform-code.d.ts.map +0 -1
  245. package/dist/tools/transform-code.js.map +0 -1
  246. package/dist/tools/validate-before-transform.d.ts.map +0 -1
  247. package/dist/tools/validate-before-transform.js.map +0 -1
  248. package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
  249. package/dist/tools/validate-project-compatibility.js.map +0 -1
  250. package/dist/tools/validate-transformation.d.ts.map +0 -1
  251. package/dist/tools/validate-transformation.js.map +0 -1
  252. package/dist/types.d.ts.map +0 -1
  253. package/dist/types.js.map +0 -1
  254. package/dist/utils/format-tool-response.d.ts.map +0 -1
  255. package/dist/utils/format-tool-response.js.map +0 -1
@@ -2,12 +2,11 @@
2
2
  * @angular-modernizer/adapter-mcp - Comprehensive Scan Tool
3
3
  *
4
4
  * MCP tool for comprehensive scanning with all plugins:
5
- * - SolidPlugin (5 rules): SOLID principles
6
- * - AngularPlugin (17 rules): Angular best practices
7
- * - ArchitecturePlugin (13 rules): Architectural issues
8
- * Total: 35 rules
5
+ * - SolidPlugin (7 rules): SOLID principles
6
+ * - AngularPlugin (28 rules): Angular best practices
7
+ * - ArchitecturePlugin (17 rules): Architectural issues
8
+ * Total: 52 rules
9
9
  */
10
- /* eslint-disable @typescript-eslint/no-unsafe-member-access */
11
10
  /* eslint-disable @typescript-eslint/no-unsafe-assignment */
12
11
  import { findTsConfig } from './helpers/find-ts-config.js';
13
12
  import { Kernel, MultiCacheFallbackManager, RealFileSystemAdapter, createToolCacheConfig, createMultiCacheConfig, loadConfig, } from '@angular-modernizer/core';
@@ -18,14 +17,35 @@ import { ContextFactory } from '@angular-modernizer/plugin-system';
18
17
  import { createPublicApi } from '@angular-modernizer/api';
19
18
  import { glob } from 'glob';
20
19
  import { relative } from 'node:path';
20
+ import { existsSync, statSync } from 'node:fs';
21
+ import { FindingWindow } from './helpers/finding-window.js';
22
+ import { cancelledExecution, fileProgressMessage, yieldIfCancellable, } from './helpers/tool-context.js';
23
+ import { loadSourceFiles } from './helpers/load-source-files.js';
24
+ import { describeScan, SCAN_EXECUTION_SCHEMA, scanOutputSchema, } from './helpers/analysis-output.js';
25
+ import { dependenciesUnchanged, templateDependencies, } from './helpers/scan-cache.js';
21
26
  /**
22
- * Comprehensive scan with all available plugins (35 rules total).
27
+ * Version of the cache entries scan-all writes. Entries from before the
28
+ * per-analyzed-file layout (findings filed under their template, files without
29
+ * findings missing) would read as complete; the version invalidates them.
30
+ */
31
+ const SCAN_ALL_CACHE_VERSION = 'scan-all-2';
32
+ /**
33
+ * Comprehensive scan with all available plugins (52 rules total).
23
34
  */
24
35
  export class ScanAllTool {
25
36
  name = 'scan-all';
26
- description = 'Comprehensive code quality scan with all plugins (SOLID, Angular, Architecture - 35 rules total)';
37
+ title = 'Scan All Rules';
38
+ annotations = {
39
+ readOnlyHint: true,
40
+ destructiveHint: false,
41
+ idempotentHint: true,
42
+ openWorldHint: false,
43
+ };
44
+ description = 'Comprehensive code quality scan with all plugins (SOLID 7, Angular 28, Architecture 17: 52 rules total). ' +
45
+ 'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
27
46
  inputSchema = {
28
47
  type: 'object',
48
+ additionalProperties: false,
29
49
  properties: {
30
50
  rootPath: {
31
51
  type: 'string',
@@ -34,7 +54,7 @@ export class ScanAllTool {
34
54
  rules: {
35
55
  type: 'array',
36
56
  items: { type: 'string' },
37
- description: 'Specific rules to run (optional, runs all 35 if not specified)',
57
+ description: 'Specific rules to run (optional, runs all 52 if not specified)',
38
58
  },
39
59
  includePatterns: {
40
60
  type: 'array',
@@ -95,7 +115,11 @@ export class ScanAllTool {
95
115
  },
96
116
  required: ['rootPath'],
97
117
  };
98
- async execute(args) {
118
+ outputSchema = scanOutputSchema({
119
+ cache: { type: 'object' },
120
+ execution: SCAN_EXECUTION_SCHEMA,
121
+ });
122
+ async execute(args, ctx = {}) {
99
123
  const params = args;
100
124
  const config = this.loadConfig(params.rootPath);
101
125
  const mergedParams = { ...config, ...params };
@@ -144,7 +168,10 @@ export class ScanAllTool {
144
168
  });
145
169
  allFiles.push(...files);
146
170
  }
147
- const uniqueFiles = Array.from(new Set(allFiles));
171
+ // glob returns files in a different order on every call; sorted, the batches
172
+ // and with them the findings of rules that look across files are the same
173
+ // in every cold run.
174
+ const uniqueFiles = Array.from(new Set(allFiles)).sort();
148
175
  const filesToAnalyze = uniqueFiles; // Analyze ALL files found (batch processing prevents memory issues)
149
176
  const maxFiles = mergedParams.maxFiles ?? 100; // Batch size (default 100)
150
177
  // Initialize kernel
@@ -155,32 +182,18 @@ export class ScanAllTool {
155
182
  .getAllPlugins()
156
183
  .flatMap((p) => p.getAnalysisRules());
157
184
  // ============================================================================
158
- // CROSS-CACHE READ SYSTEM (UNIDIRECTIONAL)
185
+ // CACHE READ
159
186
  // ============================================================================
160
- // Before analyzing files, check if cached results exist in ANY cache directory.
161
- // This provides massive token savings when running scan-all after individual scans.
162
- //
163
- // Cache read order (first cache wins):
164
- // 1. .angular-modernizer-cache/all/ (primary cache for scan-all)
165
- // 2. .angular-modernizer-cache/solid/ (fallback to SOLID scan cache)
166
- // 3. .angular-modernizer-cache/angular/ (fallback to Angular scan cache)
167
- // 4. .angular-modernizer-cache/architecture/ (fallback to Architecture scan cache)
168
- //
169
- // Performance benefits (Phase 3):
170
- // - Before: scan-solid (63s) + scan-architecture (203s) + scan-all (360s) = 626s
171
- // - After: scan-solid (63s) + scan-architecture (203s) + scan-all (~5s) = 271s
172
- // - Savings: 355 seconds (57% time reduction)
173
- //
174
- // Performance (when only scan-all cache exists):
175
- // - First run: 359.8s (analyzes all files, writes cache)
176
- // - Second run: 24.2s (14.9x speedup, 93.3% faster, reads from cache)
177
- //
178
- // UNIDIRECTIONAL: Only scan-all reads from individual caches, not vice versa.
179
- // Individual scans remain independent and focused on their specific rule categories.
187
+ // scan-all reads only its own cache (.angular-modernizer-cache/all/). The
188
+ // caches of scan-solid, scan-angular and scan-architecture hold only their
189
+ // plugin's findings and a different cache version: opening them here
190
+ // returned no hits and invalidated (deleted) their entries.
180
191
  // ============================================================================
181
192
  const fileSystem = new RealFileSystemAdapter();
182
- const multiCacheManager = new MultiCacheFallbackManager(fileSystem, ['all', 'solid', 'angular', 'architecture'], // Check in this order
183
- createMultiCacheConfig(mergedParams.rootPath));
193
+ const multiCacheManager = new MultiCacheFallbackManager(fileSystem, ['all'], {
194
+ ...createMultiCacheConfig(mergedParams.rootPath),
195
+ version: SCAN_ALL_CACHE_VERSION,
196
+ });
184
197
  await multiCacheManager.initialize();
185
198
  // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
186
199
  const fullConfig = loadConfig(mergedParams.rootPath);
@@ -188,13 +201,16 @@ export class ScanAllTool {
188
201
  const cachedResults = []; // eslint-disable-line @typescript-eslint/no-explicit-any
189
202
  const filesToProcess = [];
190
203
  const cacheHitsBySource = {};
204
+ // The cache holds every rule's findings per analyzed file, so an entry
205
+ // without findings is a hit as well.
206
+ const ownCache = multiCacheManager.getAllCaches()[0].manager;
191
207
  for (const filePath of filesToAnalyze) {
192
- const cached = await multiCacheManager.getAnalysisResult(filePath);
193
- if (cached?.results && cached.results.length > 0) {
208
+ const cached = await readCachedFindings(filePath, ownCache);
209
+ if (cached !== null) {
194
210
  // File is cached in one of the cache directories
195
211
  cachedResults.push(...cached.results);
196
212
  // Track which cache was used for logging
197
- const source = cached.source ?? 'unknown';
213
+ const source = cached.source;
198
214
  cacheHitsBySource[source] = (cacheHitsBySource[source] ?? 0) + 1;
199
215
  }
200
216
  else {
@@ -228,20 +244,23 @@ export class ScanAllTool {
228
244
  const totalBatches = Math.ceil(totalFiles / batchSize);
229
245
  console.info(`\nProcessing ${totalFiles} files in ${totalBatches} batch(es) of ${batchSize} files each`);
230
246
  // Separate arrays for two concerns:
231
- // - allResultsForCache: all violations from newly-analyzed files (needed for cache writes)
232
- // - results: violations from cache + in-window violations from new files (bounded, for return)
233
- // PERF-1: heap is bounded because results only grows up to offset+maxResults entries.
247
+ // - entriesForCache: per newly-analyzed file its violations (also those on its template) and template files
248
+ // - window: rule filter, totals and the requested page of cached and new violations
249
+ // PERF-1: heap is bounded because the page holds at most maxResults entries.
234
250
  const paginationOffset = mergedParams.resultOffset ?? 0;
235
251
  const paginationLimit = mergedParams.maxResults ?? 1000;
236
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
- const allResultsForCache = [];
238
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
239
- const results = [...cachedResults];
252
+ const entriesForCache = new Map();
253
+ // Cached and newly analyzed findings go through the same window: rule
254
+ // filter, summary totals, then the requested page.
255
+ const window = new FindingWindow(mergedParams.rules, paginationOffset, paginationLimit);
256
+ for (const cached of cachedResults) {
257
+ window.add(cached);
258
+ }
240
259
  let filesAnalyzed = cachedResults.length;
241
- // Running count of valid violations seen (cached + newly analyzed).
242
- let totalViolationCount = cachedResults.filter((r) => r['ruleId'] && r['filePath']).length;
243
- // Process each batch
244
- for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
260
+ let cancelled = false;
261
+ const progressTotal = cachedResults.length + totalFiles;
262
+ // Process each batch; cancellation is checked between files
263
+ for (let batchNum = 0; batchNum < totalBatches && !cancelled; batchNum++) {
245
264
  const batchStart = batchNum * batchSize;
246
265
  const batchEnd = Math.min(batchStart + batchSize, totalFiles);
247
266
  const batchFiles = filesToProcess.slice(batchStart, batchEnd);
@@ -253,21 +272,28 @@ export class ScanAllTool {
253
272
  for (const file of existingFiles) {
254
273
  project.removeSourceFile(file);
255
274
  }
256
- // Add current batch files
257
- for (const filePath of batchFiles) {
258
- try {
259
- project.addSourceFileAtPath(filePath);
260
- }
261
- catch (error) {
262
- console.warn(`Failed to add file ${filePath}:`, error);
263
- }
275
+ // Add current batch files, keeping their sorted order: findings must
276
+ // come out in the order a warm run reads them from the cache, or pages
277
+ // computed cold and warm overlap. A cancel during the load stops the scan.
278
+ const loaded = await loadSourceFiles(project, batchFiles, { signal: ctx.signal });
279
+ if (loaded.cancelled) {
280
+ cancelled = true;
281
+ break;
264
282
  }
283
+ const batchSourceFiles = loaded.sourceFiles;
265
284
  console.info(`Batch ${batchNum + 1}: Project now has ${project.getSourceFiles().length} source files`);
266
285
  // Create PublicApi for this batch
267
286
  const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any
268
287
  // Analyze files in this batch
269
288
  let batchViolationCount = 0;
270
- for (const sourceFile of project.getSourceFiles()) {
289
+ let batchFilesAnalyzed = 0;
290
+ for (const sourceFile of batchSourceFiles) {
291
+ await yieldIfCancellable(ctx.signal);
292
+ if (ctx.signal?.aborted === true) {
293
+ cancelled = true;
294
+ break;
295
+ }
296
+ const fileResults = [];
271
297
  for (const rule of allRules) {
272
298
  try {
273
299
  const ruleResults = await rule.analyze(ContextFactory.createAnalysisContext({
@@ -279,7 +305,7 @@ export class ScanAllTool {
279
305
  for (const result of ruleResults) {
280
306
  const entry = {
281
307
  ruleId: result.ruleId,
282
- severity: rule.severity,
308
+ severity: result.severity ?? rule.severity,
283
309
  message: result.message,
284
310
  filePath: result.filePath,
285
311
  line: result.line,
@@ -289,13 +315,8 @@ export class ScanAllTool {
289
315
  metadata: result.metadata,
290
316
  };
291
317
  // Always accumulate for cache writes.
292
- allResultsForCache.push(entry);
293
- // Only store in the paginated return array if inside the requested window.
294
- totalViolationCount++;
295
- if (totalViolationCount > paginationOffset &&
296
- results.length < paginationOffset + paginationLimit) {
297
- results.push(entry);
298
- }
318
+ fileResults.push(entry);
319
+ window.add(entry);
299
320
  batchViolationCount++;
300
321
  }
301
322
  }
@@ -303,11 +324,19 @@ export class ScanAllTool {
303
324
  console.warn(`Failed to analyze with rule ${rule.id}:`, error);
304
325
  }
305
326
  }
327
+ const sourcePath = sourceFile.getFilePath();
328
+ entriesForCache.set(sourcePath, {
329
+ results: fileResults,
330
+ dependencies: templateDependencies(sourcePath, sourceFile.getFullText(), fileResults.map((r) => r.filePath), existsSync),
331
+ });
332
+ batchFilesAnalyzed++;
333
+ ctx.progress?.(filesAnalyzed + batchFilesAnalyzed, progressTotal, fileProgressMessage(filesAnalyzed + batchFilesAnalyzed, progressTotal, window.getTotals().totalViolations));
306
334
  }
307
- filesAnalyzed += batchFiles.length;
335
+ // Files that failed to load count as analyzed, as before
336
+ filesAnalyzed += cancelled ? batchFilesAnalyzed : batchFiles.length;
308
337
  console.info(`Batch ${batchNum + 1}: Found ${batchViolationCount} violations in ${batchFiles.length} files`);
309
338
  }
310
- console.info(`\nBatch processing complete: ${totalBatches} batch(es), ${filesAnalyzed} total files analyzed, ${totalViolationCount} total violations`);
339
+ console.info(`\nBatch processing complete: ${totalBatches} batch(es), ${filesAnalyzed} total files analyzed, ${window.getTotals().totalViolations} total violations`);
311
340
  // ============================================================================
312
341
  // CACHE WRITE SYSTEM (Enhanced with MultiCacheFallbackManager)
313
342
  // ============================================================================
@@ -330,32 +359,22 @@ export class ScanAllTool {
330
359
  // - Each file analyzed with ALL rules = most expensive analysis
331
360
  // - Cache hit eliminates analysis for ALL 35 rules per file
332
361
  // - 93.3% time saved on second run (359.8s → 24.2s)
333
- //
334
- // Enhancement: Cache can now be read from individual tool caches
335
- // when running scan-all after individual scans (57% time reduction overall).
336
362
  // ============================================================================
337
- // Group newly-analyzed results by file path for cache writes.
338
- const resultsByFile = new Map();
339
- for (const result of allResultsForCache) {
340
- const filePath = result.filePath;
341
- if (!resultsByFile.has(filePath)) {
342
- resultsByFile.set(filePath, []);
343
- }
344
- resultsByFile.get(filePath).push(result);
345
- }
346
- // Write each file's results to PRIMARY cache only (multiCacheManager writes to first cache)
347
- for (const [filePath, fileResults] of resultsByFile.entries()) {
348
- await multiCacheManager.setAnalysisResult(filePath, fileResults);
363
+ // One entry per analyzed file, also without findings, so a warm run does not
364
+ // analyze it again in a different batch. Findings on a template stay with the
365
+ // component file that produced them; the template is a dependency.
366
+ // Writes go to the PRIMARY cache only (multiCacheManager writes to first cache).
367
+ for (const [filePath, entry] of entriesForCache) {
368
+ await multiCacheManager.setAnalysisResult(filePath, entry.results, entry.dependencies);
349
369
  }
350
370
  // Log cache effectiveness
351
371
  const writeStats = multiCacheManager.getStats();
352
- console.info(`Cached ${resultsByFile.size} files to primary cache (hit rate: ${writeStats.hitRate.toFixed(1)}%)`);
353
- // results[] is already bounded to the pagination window (PERF-1).
354
- // Apply rule filter and map for the MCP response.
355
- let paginatedViolations = results
356
- .filter((r) => r.ruleId && r.filePath)
372
+ console.info(`Cached ${entriesForCache.size} files to primary cache (hit rate: ${writeStats.hitRate.toFixed(1)}%)`);
373
+ // The window holds only the requested page of the filtered findings.
374
+ const paginatedViolations = window
375
+ .getPage()
357
376
  .map((r, index) => ({
358
- id: `all-${index}`,
377
+ id: `all-${paginationOffset + index}`,
359
378
  ruleId: r.ruleId,
360
379
  severity: r.severity,
361
380
  message: r.message,
@@ -368,15 +387,21 @@ export class ScanAllTool {
368
387
  : undefined,
369
388
  metadata: r.metadata,
370
389
  }));
371
- if (mergedParams.rules?.length) {
372
- paginatedViolations = paginatedViolations.filter((v) => mergedParams.rules.includes(v.ruleId));
373
- }
374
390
  const offset = paginationOffset;
375
- const maxResults = paginationLimit;
376
- // totalViolationCount tracks all violations seen; use it for accurate pagination metadata.
377
- const totalViolations = totalViolationCount;
378
- // Calculate summary
379
- const summary = this.calculateSummary(paginatedViolations, filesToAnalyze.length);
391
+ const totals = window.getTotals();
392
+ const counts = {
393
+ ...totals,
394
+ analyzedFiles: cancelled ? filesAnalyzed : filesToAnalyze.length,
395
+ };
396
+ const execution = cancelled
397
+ ? cancelledExecution(filesAnalyzed, filesToAnalyze.length - filesAnalyzed)
398
+ : undefined;
399
+ const pagination = {
400
+ totalResults: totals.totalViolations,
401
+ returnedResults: paginatedViolations.length,
402
+ offset,
403
+ hasMore: window.hasMore(),
404
+ };
380
405
  const duration = Date.now() - startTime;
381
406
  // Get all rule IDs from the rules we executed
382
407
  const allRuleIds = allRules.map((r) => r.id);
@@ -384,7 +409,7 @@ export class ScanAllTool {
384
409
  const finalStats = multiCacheManager.getStats();
385
410
  return {
386
411
  violations: paginatedViolations,
387
- summary,
412
+ counts,
388
413
  metadata: {
389
414
  rulesExecuted: allRuleIds,
390
415
  duration,
@@ -399,23 +424,7 @@ export class ScanAllTool {
399
424
  },
400
425
  },
401
426
  // Cache statistics with source breakdown
402
- //
403
- // IMPORTANT: Understanding cache statistics
404
- // ==========================================
405
- // - hitRate: Shows PRIMARY cache hit rate (first cache directory: /all/)
406
- // - hitsBySource: Shows FALLBACK cache hits (solid/angular/architecture)
407
- //
408
- // Why hitRate can be 0% while hitsBySource has values:
409
- // - If /all/ cache is deleted/empty, hitRate = 0% (primary cache empty)
410
- // - But fallback caches (solid/angular/architecture) can provide cached results
411
- // - hitsBySource tracks which fallback caches were used
412
- //
413
- // Example Test 3 scenario:
414
- // - Delete /all/ cache → hitRate: 0% (primary cache empty)
415
- // - But hitsBySource: {"solid": 630, "architecture": 10} (640 fallback hits!)
416
- // - Result: Only 2,118 files analyzed (not 2,758) = Phase 3 working! ✅
417
- //
418
- // This is CORRECT Phase 3 behavior - fallback system saved 640 file analyses.
427
+ // hitRate and hitsBySource refer to the own cache (/all/) only.
419
428
  cache: {
420
429
  totalFilesChecked: filesToAnalyze.length,
421
430
  filesFromCache: cachedResults.length,
@@ -435,12 +444,9 @@ export class ScanAllTool {
435
444
  throughput: filesToAnalyze.length / (duration / 1000),
436
445
  }
437
446
  : undefined,
438
- pagination: {
439
- totalResults: totalViolations,
440
- returnedResults: paginatedViolations.length,
441
- offset,
442
- hasMore: offset + maxResults < totalViolations,
443
- },
447
+ pagination,
448
+ ...(execution === undefined ? {} : { execution }),
449
+ summary: describeScan(counts, paginatedViolations, pagination, execution === undefined ? [] : [execution.note]),
444
450
  };
445
451
  }
446
452
  /**
@@ -463,24 +469,26 @@ export class ScanAllTool {
463
469
  }
464
470
  return {};
465
471
  }
466
- calculateSummary(violations, analyzedFiles) {
467
- const bySeverity = {};
468
- const byCategory = {};
469
- const byRule = {};
470
- for (const violation of violations) {
471
- bySeverity[violation.severity] =
472
- (bySeverity[violation.severity] ?? 0) + 1;
473
- byCategory[violation.category] =
474
- (byCategory[violation.category] ?? 0) + 1;
475
- byRule[violation.ruleId] = (byRule[violation.ruleId] ?? 0) + 1;
476
- }
477
- return {
478
- totalViolations: violations.length,
479
- analyzedFiles,
480
- bySeverity,
481
- byCategory,
482
- byRule,
483
- };
472
+ }
473
+ /**
474
+ * Cached findings of one file, or `null` when it must be analyzed. An own
475
+ * entry is authoritative even without findings, but stale once one of its
476
+ * template dependencies changed.
477
+ */
478
+ async function readCachedFindings(filePath, ownCache) {
479
+ const own = await ownCache.getAnalysisResult(filePath);
480
+ if (own === null) {
481
+ return null;
482
+ }
483
+ const fresh = dependenciesUnchanged(own.dependencies, own.metadata.cachedAt, modifiedAt);
484
+ return fresh ? { results: own.results, source: 'all' } : null;
485
+ }
486
+ function modifiedAt(path) {
487
+ try {
488
+ return statSync(path).mtimeMs;
489
+ }
490
+ catch {
491
+ return undefined;
484
492
  }
485
493
  }
486
494
  //# sourceMappingURL=scan-all.js.map
@@ -2,9 +2,11 @@
2
2
  * @angular-modernizer/adapter-mcp - Scan Angular Best Practices Tool
3
3
  *
4
4
  * MCP tool for scanning Angular codebases for Angular-specific best practice violations.
5
- * Runs only the AngularPlugin (17 rules: OnPush, TrackBy, Performance, RxJS, etc.).
5
+ * Runs only the AngularPlugin (28 rules: OnPush, TrackBy, Performance, RxJS, etc.).
6
6
  */
7
- import type { MCPTool } from '../types.js';
7
+ import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
8
+ import { type ScanCounts } from './helpers/analysis-output.js';
9
+ import { type CancelledExecution } from './helpers/tool-context.js';
8
10
  interface ScanAngularResult {
9
11
  violations: {
10
12
  id: string;
@@ -18,13 +20,12 @@ interface ScanAngularResult {
18
20
  suggestedFix?: string;
19
21
  metadata?: Record<string, unknown>;
20
22
  }[];
21
- summary: {
22
- totalViolations: number;
23
- analyzedFiles: number;
24
- bySeverity: Record<string, number>;
25
- byCategory: Record<string, number>;
26
- byRule: Record<string, number>;
27
- };
23
+ /** Counts over all violations, independent of the page. */
24
+ counts: ScanCounts;
25
+ /** Human-readable summary for LLM consumption. */
26
+ summary: string;
27
+ /** Set when the client cancelled the scan; counts cover the analyzed files. */
28
+ execution?: CancelledExecution;
28
29
  metadata: {
29
30
  rulesExecuted: string[];
30
31
  duration: number;
@@ -51,9 +52,12 @@ interface ScanAngularResult {
51
52
  */
52
53
  export declare class ScanAngularTool implements MCPTool {
53
54
  readonly name = "scan-angular";
54
- readonly description = "Scan for Angular best practice violations (OnPush, TrackBy, Performance, RxJS, etc.)";
55
+ readonly title = "Scan Angular Patterns";
56
+ readonly annotations: ToolAnnotations;
57
+ readonly description: string;
55
58
  readonly inputSchema: {
56
59
  type: string;
60
+ additionalProperties: boolean;
57
61
  properties: {
58
62
  rootPath: {
59
63
  type: string;
@@ -120,7 +124,12 @@ export declare class ScanAngularTool implements MCPTool {
120
124
  };
121
125
  required: string[];
122
126
  };
123
- execute(args: Record<string, unknown>): Promise<ScanAngularResult>;
127
+ readonly outputSchema: {
128
+ type: "object";
129
+ properties: Record<string, unknown>;
130
+ required: string[];
131
+ };
132
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<ScanAngularResult>;
124
133
  /**
125
134
  * Load configuration from .angular-modernizer.json file.
126
135
  * Only loads from the provided root path to avoid cache directory issues.