@angular-modernizer/adapter-mcp 1.1.0 → 2.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 (144) hide show
  1. package/CHANGELOG.md +662 -0
  2. package/README.md +86 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +10 -1
  6. package/dist/index.js +1 -0
  7. package/dist/scan-host/scan-host.d.ts +7 -0
  8. package/dist/scan-host/scan-host.js +73 -10
  9. package/dist/scan-host/scan-protocol.d.ts +2 -0
  10. package/dist/scan-host/scan-worker.js +14 -8
  11. package/dist/server/limited-stdio-transport.d.ts +6 -3
  12. package/dist/server/limited-stdio-transport.js +26 -9
  13. package/dist/server/mcp-server.js +1 -1
  14. package/dist/server/sdk-server.d.ts +14 -3
  15. package/dist/server/sdk-server.js +54 -6
  16. package/dist/server/tool-registry.d.ts +3 -1
  17. package/dist/server/tool-registry.js +8 -3
  18. package/dist/streaming/progress-store.d.ts +19 -7
  19. package/dist/streaming/progress-store.js +19 -8
  20. package/dist/tools/analyze-build-impact.d.ts +9 -6
  21. package/dist/tools/analyze-build-impact.js +14 -7
  22. package/dist/tools/analyze-core-to-shared.d.ts +10 -6
  23. package/dist/tools/analyze-core-to-shared.js +63 -60
  24. package/dist/tools/analyze-parser-performance.d.ts +57 -13
  25. package/dist/tools/analyze-parser-performance.js +67 -6
  26. package/dist/tools/analyze-project.d.ts +35 -6
  27. package/dist/tools/analyze-project.js +141 -36
  28. package/dist/tools/check-incremental-compatibility.d.ts +30 -41
  29. package/dist/tools/check-incremental-compatibility.js +32 -264
  30. package/dist/tools/collect-feedback.js +15 -2
  31. package/dist/tools/extract-libraries.js +42 -27
  32. package/dist/tools/find-angular-symbol.d.ts +2 -2
  33. package/dist/tools/find-angular-symbol.js +6 -5
  34. package/dist/tools/find-component-hosts.d.ts +2 -2
  35. package/dist/tools/find-component-hosts.js +6 -5
  36. package/dist/tools/find-usages.d.ts +2 -2
  37. package/dist/tools/find-usages.js +24 -15
  38. package/dist/tools/get-bootstrap-execution.d.ts +2 -2
  39. package/dist/tools/get-bootstrap-execution.js +3 -3
  40. package/dist/tools/get-call-graph.d.ts +2 -2
  41. package/dist/tools/get-call-graph.js +18 -5
  42. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  43. package/dist/tools/get-operation-progress-tool.js +2 -2
  44. package/dist/tools/get-operation-progress.d.ts +4 -1
  45. package/dist/tools/get-operation-progress.js +6 -2
  46. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  47. package/dist/tools/helpers/analysis-output.js +22 -1
  48. package/dist/tools/helpers/build-cache.d.ts +27 -0
  49. package/dist/tools/helpers/build-cache.js +86 -0
  50. package/dist/tools/helpers/class-filter.d.ts +18 -0
  51. package/dist/tools/helpers/class-filter.js +30 -0
  52. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  53. package/dist/tools/helpers/cli-arguments.js +35 -0
  54. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  55. package/dist/tools/helpers/feedback-catalog.js +196 -0
  56. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  57. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  58. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  59. package/dist/tools/helpers/file-type-check.js +56 -0
  60. package/dist/tools/helpers/output-contract.d.ts +42 -0
  61. package/dist/tools/helpers/output-contract.js +54 -0
  62. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  63. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  64. package/dist/tools/helpers/project-cache.d.ts +78 -6
  65. package/dist/tools/helpers/project-cache.js +205 -15
  66. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  67. package/dist/tools/helpers/project-decorators.js +13 -6
  68. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  69. package/dist/tools/helpers/refresh-apply.js +460 -0
  70. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  71. package/dist/tools/helpers/refresh-inventory.js +610 -0
  72. package/dist/tools/helpers/rule-runner.js +3 -1
  73. package/dist/tools/helpers/scan-cache.d.ts +74 -5
  74. package/dist/tools/helpers/scan-cache.js +134 -6
  75. package/dist/tools/helpers/scan-engine.d.ts +30 -6
  76. package/dist/tools/helpers/scan-engine.js +131 -22
  77. package/dist/tools/helpers/scan-plan.d.ts +1 -1
  78. package/dist/tools/helpers/scan-plan.js +16 -2
  79. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  80. package/dist/tools/helpers/source-map-loader.js +226 -0
  81. package/dist/tools/helpers/template-check.d.ts +76 -0
  82. package/dist/tools/helpers/template-check.js +158 -0
  83. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  84. package/dist/tools/helpers/tool-cache.js +9 -3
  85. package/dist/tools/helpers/tool-context.d.ts +18 -0
  86. package/dist/tools/helpers/tool-context.js +29 -0
  87. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  88. package/dist/tools/helpers/transform-safety.js +357 -4
  89. package/dist/tools/inspect-form-group.d.ts +2 -2
  90. package/dist/tools/inspect-form-group.js +8 -3
  91. package/dist/tools/inspect-i18n.d.ts +2 -2
  92. package/dist/tools/inspect-i18n.js +3 -3
  93. package/dist/tools/inspect-template.d.ts +2 -2
  94. package/dist/tools/inspect-template.js +11 -5
  95. package/dist/tools/learn-patterns.d.ts +43 -28
  96. package/dist/tools/learn-patterns.js +83 -161
  97. package/dist/tools/list-imports.d.ts +2 -2
  98. package/dist/tools/list-imports.js +3 -3
  99. package/dist/tools/orchestrate-migration.d.ts +19 -1
  100. package/dist/tools/orchestrate-migration.js +52 -10
  101. package/dist/tools/parse-stack-trace.d.ts +48 -1
  102. package/dist/tools/parse-stack-trace.js +108 -9
  103. package/dist/tools/plan-migration.d.ts +2 -2
  104. package/dist/tools/plan-migration.js +25 -12
  105. package/dist/tools/refresh-state.d.ts +378 -0
  106. package/dist/tools/refresh-state.js +370 -0
  107. package/dist/tools/resolve-type.d.ts +2 -2
  108. package/dist/tools/resolve-type.js +13 -6
  109. package/dist/tools/review-feedback.d.ts +42 -7
  110. package/dist/tools/review-feedback.js +24 -17
  111. package/dist/tools/rollback-changes.d.ts +5 -0
  112. package/dist/tools/rollback-changes.js +7 -2
  113. package/dist/tools/run-angular-cli.js +36 -22
  114. package/dist/tools/run-build.d.ts +33 -28
  115. package/dist/tools/run-build.js +136 -438
  116. package/dist/tools/run-schematic.d.ts +8 -2
  117. package/dist/tools/run-schematic.js +80 -50
  118. package/dist/tools/scan-all.d.ts +31 -15
  119. package/dist/tools/scan-all.js +75 -109
  120. package/dist/tools/scan-angular.d.ts +27 -14
  121. package/dist/tools/scan-angular.js +70 -92
  122. package/dist/tools/scan-architecture.d.ts +29 -12
  123. package/dist/tools/scan-architecture.js +205 -135
  124. package/dist/tools/scan-solid.d.ts +27 -14
  125. package/dist/tools/scan-solid.js +73 -89
  126. package/dist/tools/search-codebase.d.ts +8 -3
  127. package/dist/tools/search-codebase.js +16 -10
  128. package/dist/tools/suggest-improvements.d.ts +34 -3
  129. package/dist/tools/suggest-improvements.js +34 -9
  130. package/dist/tools/trace-output-flow.d.ts +2 -2
  131. package/dist/tools/trace-output-flow.js +6 -5
  132. package/dist/tools/transform-code-batch.d.ts +9 -9
  133. package/dist/tools/transform-code.d.ts +161 -12
  134. package/dist/tools/transform-code.js +782 -197
  135. package/dist/tools/validate-before-transform.js +2 -1
  136. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  137. package/dist/tools/validate-project-compatibility.js +33 -225
  138. package/dist/tools/validate-transformation.d.ts +40 -26
  139. package/dist/tools/validate-transformation.js +115 -294
  140. package/dist/tools/verify-citations.js +8 -2
  141. package/dist/types.d.ts +9 -9
  142. package/dist/utils/format-tool-response.d.ts +3 -1
  143. package/dist/utils/format-tool-response.js +8 -3
  144. package/package.json +14 -13
@@ -1,7 +1,8 @@
1
1
  import { findTsConfig } from './helpers/find-ts-config.js';
2
- import { cancelledExecution, fileProgressMessage, yieldIfCancellable, } from './helpers/tool-context.js';
2
+ import { cancelledExecution, fileProgressMessage, finalFileProgress, yieldIfCancellable, } from './helpers/tool-context.js';
3
3
  import { runScan } from '../scan-host/scan-host.js';
4
4
  import { openToolCache } from './helpers/tool-cache.js';
5
+ import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, scanCacheVersion, templateDependencies, } from './helpers/scan-cache.js';
5
6
  import { loadSourceFiles } from './helpers/load-source-files.js';
6
7
  import { filterFilesByScopePaths } from './helpers/scope-paths.js';
7
8
  import { toParallelOptions } from '../types.js';
@@ -10,7 +11,7 @@ import { ArchitecturePlugin } from '@angular-modernizer/plugin-architecture';
10
11
  import { createPublicApi } from '@angular-modernizer/api';
11
12
  import { getWorkerScriptPath } from '@angular-modernizer/worker';
12
13
  import { glob } from 'glob';
13
- import { resolve, extname } from 'node:path';
14
+ import { resolve, extname, relative } from 'node:path';
14
15
  import { readFileSync, existsSync, statSync } from 'node:fs';
15
16
  import { randomUUID } from 'node:crypto';
16
17
  import { ProgressStore } from '../streaming/progress-store.js';
@@ -48,8 +49,8 @@ function withScanSummary(result) {
48
49
  }
49
50
  /**
50
51
  * MCP tool `scan-architecture`: scans for architectural issues. Runs only the
51
- * ArchitecturePlugin (17 rules: import cycles, layer violations, god objects
52
- * and others).
52
+ * rules of the ArchitecturePlugin (import cycles, layer violations, god
53
+ * objects and others).
53
54
  */
54
55
  export class ScanArchitectureTool {
55
56
  name = 'scan-architecture';
@@ -60,7 +61,7 @@ export class ScanArchitectureTool {
60
61
  idempotentHint: true,
61
62
  openWorldHint: false,
62
63
  };
63
- description = 'Scan Angular codebases for architectural issues with the 17 architecture rules: import cycles ' +
64
+ description = 'Scan Angular codebases for architectural issues with the architecture rules: import cycles ' +
64
65
  '(solid:circular-dependency, NG0919 risk), import direction, god objects, layer boundaries, content ' +
65
66
  'placement, service bags and more. Returns the violations directly; streaming: true (deprecated) runs in the background instead (poll get-operation-progress); ' +
66
67
  'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
@@ -111,7 +112,7 @@ export class ScanArchitectureTool {
111
112
  description: 'Specific rules to run (optional, runs all if not specified). ' +
112
113
  'Must be exact rule.id values — short names like "circular-dependency" will NOT match. ' +
113
114
  'Valid IDs: solid:circular-dependency, solid:import-direction-violation, solid:god-object-violation, ' +
114
- 'architecture:component-complexity, architecture:service-architecture, architecture:content-placement, ' +
115
+ 'architecture:component-complexity, architecture:service-architecture (deprecated, reports nothing), architecture:content-placement, ' +
115
116
  'architecture:advanced-content-placement, architecture:model-separation, architecture:rxjs-memory-leak, ' +
116
117
  'architecture:error-handling-pattern, architecture:inheritance-analysis, architecture:performance-pattern, ' +
117
118
  'architecture:cross-file-architecture, architecture:service-bag, architecture:static-in-stateful-class, ' +
@@ -138,14 +139,18 @@ export class ScanArchitectureTool {
138
139
  '**/*.test.ts',
139
140
  ],
140
141
  },
142
+ cache: {
143
+ ...SCAN_CACHE_MODE_SCHEMA,
144
+ description: "use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Only apiStyle 'imperative' has a cache, the default fluent path analyzes every file anyway. Read from the call only, never from the tools section",
145
+ },
141
146
  includeAutoFixes: {
142
147
  type: 'boolean',
143
- description: 'Whether to include auto-fix suggestions',
144
- default: true,
148
+ description: 'Deprecated, no effect: scan-architecture always returns the suggested fixes',
149
+ deprecated: true,
145
150
  },
146
151
  maxFiles: {
147
152
  type: 'number',
148
- description: 'Maximum number of files to analyze (default: 100 to prevent memory issues)',
153
+ description: 'Maximum number of files of the scope to analyze, taken in path order (default 100). When files are left out, execution.incomplete is true, stopReason max-files, skippedFiles and scopeFiles say how many.',
149
154
  default: 100,
150
155
  },
151
156
  maxResults: {
@@ -160,7 +165,7 @@ export class ScanArchitectureTool {
160
165
  },
161
166
  orchestration: {
162
167
  type: 'object',
163
- description: 'Deprecated, kept in 1.x: parallel and incremental run the old WorkerPool path on the main thread. On a large app it was no faster than the default path, blocked the server for seconds and took about four times the memory. Leave unset; the default path runs in the scan worker and answers cancellation at once.',
168
+ description: "Deprecated, kept in 2.x, read only with apiStyle 'imperative' (the default fluent path rejects it): parallel and incremental run the old WorkerPool path on the main thread. On a large app it was no faster than the default path, blocked the server for seconds and took about four times the memory. Leave unset; the default path runs in the scan worker and answers cancellation at once.",
164
169
  properties: {
165
170
  parallel: {
166
171
  type: 'boolean',
@@ -228,7 +233,7 @@ export class ScanArchitectureTool {
228
233
  },
229
234
  streaming: {
230
235
  type: 'boolean',
231
- description: 'Deprecated, kept in 1.x (default: false): returns operationId immediately, the analysis runs in the background and get-operation-progress returns the result. Synchronous calls report progress through MCP progress notifications and stop on cancellation.',
236
+ description: 'Deprecated, kept in 2.x (default: false): returns operationId immediately, the analysis runs in the background and get-operation-progress returns the result. Synchronous calls report progress through MCP progress notifications and stop on cancellation.',
232
237
  default: false,
233
238
  },
234
239
  apiStyle: {
@@ -259,6 +264,7 @@ export class ScanArchitectureTool {
259
264
  incomplete: { type: 'boolean' },
260
265
  stopReason: { type: 'string' },
261
266
  skippedFiles: { type: 'integer' },
267
+ scopeFiles: { type: 'integer' },
262
268
  ruleTimings: { type: 'array', items: { type: 'object' } },
263
269
  note: { type: 'string' },
264
270
  },
@@ -270,7 +276,13 @@ export class ScanArchitectureTool {
270
276
  intermediateResults: { type: 'object' },
271
277
  });
272
278
  async execute(args, ctx = {}) {
273
- const params = args;
279
+ const callParams = args;
280
+ // tools['scan-architecture'] of .angular-modernizer.json, overridden by
281
+ // the arguments of the call; all three paths read the merged parameters
282
+ const params = {
283
+ ...this.loadConfig(typeof callParams.rootPath === 'string' ? callParams.rootPath : undefined),
284
+ ...callParams,
285
+ };
274
286
  // Check if streaming mode is enabled
275
287
  const streaming = params.streaming ?? false;
276
288
  if (streaming) {
@@ -280,15 +292,14 @@ export class ScanArchitectureTool {
280
292
  // Check if fluent API should be used
281
293
  const apiStyle = params.apiStyle ?? 'fluent';
282
294
  if (apiStyle === 'fluent') {
295
+ // The fluent path has no orchestration; it used to ignore the argument
296
+ // without a word (incremental and parallel ran as a plain scan)
297
+ if (callParams.orchestration !== undefined) {
298
+ throw new Error("orchestration is read only with apiStyle 'imperative' (deprecated WorkerPool path); leave it unset for the default scan");
299
+ }
283
300
  return this.executeWithFluentApi(params, ctx);
284
301
  }
285
- // Load configuration from .angular-modernizer.json if it exists
286
- const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
287
- // Merge config with provided parameters (params take precedence)
288
- const mergedParams = {
289
- ...config,
290
- ...params,
291
- };
302
+ const mergedParams = params;
292
303
  // Use orchestration object directly
293
304
  const orchestration = mergedParams.orchestration ?? {};
294
305
  // Validate input
@@ -444,6 +455,8 @@ export class ScanArchitectureTool {
444
455
  '@angular-modernizer/plugin-architecture',
445
456
  ],
446
457
  rules: params.rules,
458
+ // rules['<id>'] options and suppressionComments for every rule
459
+ rulesConfig: (loadConfig(params.rootPath).rules ?? {}),
447
460
  timeout: orchestration.timeout ?? 120000, // 2 minutes for complex architecture rules
448
461
  };
449
462
  // Process each batch; cancellation is checked between batches
@@ -559,115 +572,101 @@ export class ScanArchitectureTool {
559
572
  else {
560
573
  // Sequential analysis mode (existing logic)
561
574
  console.info('Using sequential analysis mode...');
562
- let filesToAnalyze = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, maxFiles);
563
- // Apply scope filtering for sequential mode
575
+ // Scope first, then the cap: capping first left a scope outside the
576
+ // first maxFiles sorted project files with nothing to analyze
577
+ const filesToAnalyze = scopeFilteredFiles.slice(0, maxFiles);
564
578
  if (resolvedScope.type !== 'all') {
565
- const filesBefore = filesToAnalyze.length;
566
- filesToAnalyze = this.filterFilesByScope(filesToAnalyze, resolvedScope);
567
- console.info(`Scope filter: ${filesToAnalyze.length} files (from ${filesBefore})`);
579
+ console.info(`Scope filter: ${scopeFilteredFiles.length} files (from ${preDiscoveryFiles.length})`);
568
580
  }
569
581
  // Update resolved scope with matched files count
570
582
  resolvedScope.matchedFiles = filesToAnalyze.length;
571
583
  // ============================================================================
572
- // CACHE READ SYSTEM (Sequential Mode Only)
584
+ // CACHE (sequential mode only)
573
585
  // ============================================================================
574
- // Before analyzing files, check if cached results exist for unchanged files.
575
- // This dramatically reduces analysis time on subsequent runs (39x speedup for Architecture!).
576
- //
577
- // Performance results (real-world validation on 2,758 files):
578
- // - First run: 202.8s (analyzes all files, writes cache)
579
- // - Second run: 5.2s (39x speedup, 97.4% faster, reads from cache)
580
- //
581
- // Why Architecture benefits MOST from caching:
582
- // - Architecture rules are the most complex (circular deps, layer violations, god objects)
583
- // - Graph analysis algorithms (dependency cycles) are computationally expensive
584
- // - Caching eliminates ALL graph traversals for unchanged files
585
- // - Best cache speedup of all scan types (39x vs 14.9x for scan-all)
586
- //
587
- // Cache directory: .angular-modernizer-cache/architecture/
588
- // Cache invalidation: Automatic via mtime/content hash checking
589
- //
590
- // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
591
- // This cache read logic is for sequential mode only.
586
+ // One entry per analyzed file, also without findings, holding the
587
+ // findings of the rules with file scope. Rules with scope 'project'
588
+ // (library-extraction-opportunity, inheritance-analysis,
589
+ // model-separation) are never cached: they run over the whole scope on
590
+ // every call. Cached per file, a project-wide finding reported at a
591
+ // representative file was served again while a warm run reported it
592
+ // once more at another file (70 -> 74 -> 78 findings on a large app).
593
+ // The cache version carries the rule configuration (scanCacheVersion).
592
594
  // ============================================================================
593
- const cache = await openToolCache(mergedParams.rootPath, 'architecture');
594
- const cachedViolations = []; // eslint-disable-line @typescript-eslint/no-explicit-any
595
+ const cache = await openToolCache(mergedParams.rootPath, 'architecture', scanCacheVersion(ARCHITECTURE_CACHE_VERSION, mergedParams.rootPath));
596
+ // A run limited by rules holds only those rules' findings per file:
597
+ // it neither reads the cache nor writes entries a full run would
598
+ // take for complete
599
+ const useCache = params.rules === undefined;
600
+ // refresh analyzes every file and overwrites the entries; only the
601
+ // call's own argument counts, not the tools section
602
+ const cacheMode = scanCacheMode(args);
603
+ const findingsByFile = new Map();
595
604
  const filesToProcess = [];
596
605
  for (const filePath of filesToAnalyze) {
597
- const cached = await cache.getAnalysisResult(filePath);
598
- if (cached?.results && cached.results.length > 0) {
599
- // File is cached and hasn't changed
600
- cachedViolations.push(...cached.results);
606
+ const cached = useCache && cacheMode === 'use' ? await readCachedFindings(filePath, cache) : null;
607
+ if (cached !== null) {
608
+ findingsByFile.set(filePath, cached);
601
609
  }
602
610
  else {
603
- // File not cached or has changed
604
611
  filesToProcess.push(filePath);
605
612
  }
606
613
  }
607
- console.info(`Cache: ${cachedViolations.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
608
- // Add cached violations to results
609
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
610
- violations.push(...cachedViolations);
611
- const { run, ruleIds } = await this.runRules({
614
+ const cacheHits = filesToAnalyze.length - filesToProcess.length;
615
+ console.info(`Cache: ${cacheHits} files from cache, ${filesToProcess.length} files to analyze (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
616
+ const ruleFilter = params.rules === undefined ? {} : { ruleIds: params.rules };
617
+ const newEntries = new Map();
618
+ const fileRun = await this.runRules({
612
619
  tool: this.name,
613
620
  plugins: 'architecture',
614
621
  tsConfigPath,
615
622
  rootPath: mergedParams.rootPath,
616
623
  files: filesToProcess,
617
624
  mode: 'runner',
618
- ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
625
+ ...ruleFilter,
626
+ ruleScope: 'file',
619
627
  maxDurationMs,
620
628
  startTime,
621
- }, violations, ctx);
622
- rulesExecuted = ruleIds;
623
- execution = toExecution(run, maxDurationMs);
624
- filesAnalyzed = filesToAnalyze.length - run.skippedFiles;
625
- // ============================================================================
626
- // CACHE WRITE SYSTEM (Sequential Mode Only)
627
- // ============================================================================
628
- // After analyzing all files, write results to cache for future runs.
629
- // This enables Phase 2 (cache reads) to skip unchanged files on subsequent runs.
630
- //
631
- // Cache directory: .angular-modernizer-cache/architecture/
632
- // Cache entry format: Same as scan-solid (metadata + results[] + dependencies)
633
- //
634
- // Performance impact:
635
- // - First run: Writes cache (adds ~1-2% overhead)
636
- // - Second run: Reads cache (39x speedup - BEST improvement of all scan types!)
637
- //
638
- // Why Architecture benefits most from caching:
639
- // - Architecture rules are computationally expensive:
640
- // * Circular dependency detection requires graph traversals
641
- // * Layer violation detection requires project-wide dependency analysis
642
- // * God object detection requires complex metric calculations
643
- // - Cache hit eliminates ALL graph algorithms and dependency traversals
644
- // - 97.4% time saved on second run (202.8s → 5.2s)
645
- //
646
- // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
647
- // This cache write logic is for sequential mode only.
648
- // ============================================================================
649
- // Group violations by file path
650
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
651
- const resultsByFile = new Map();
652
- for (const violation of violations) {
653
- const filePath = violation.filePath;
654
- if (!resultsByFile.has(filePath)) {
655
- resultsByFile.set(filePath, []);
656
- }
657
- resultsByFile.get(filePath).push(violation);
629
+ }, [], ctx, newEntries);
630
+ const projectFindings = new Map();
631
+ const projectRun = fileRun.run.stopReason === 'cancelled'
632
+ ? undefined
633
+ : await this.runRules({
634
+ tool: this.name,
635
+ plugins: 'architecture',
636
+ tsConfigPath,
637
+ rootPath: mergedParams.rootPath,
638
+ files: filesToAnalyze,
639
+ mode: 'runner',
640
+ ...ruleFilter,
641
+ ruleScope: 'project',
642
+ maxDurationMs,
643
+ startTime,
644
+ }, [], ctx, projectFindings);
645
+ rulesExecuted = [...fileRun.ruleIds, ...(projectRun?.ruleIds ?? [])];
646
+ const run = combineRuns(fileRun.run, projectRun?.run);
647
+ execution = withFileCap(toExecution(run, maxDurationMs), scopeFilteredFiles.length, filesToAnalyze.length, maxFiles);
648
+ filesAnalyzed = cacheHits + fileRun.run.filesAnalyzed;
649
+ for (const [filePath, entry] of newEntries) {
650
+ findingsByFile.set(filePath, entry);
651
+ }
652
+ for (const [filePath, entry] of projectFindings) {
653
+ findingsByFile.set(filePath, [...(findingsByFile.get(filePath) ?? []), ...entry]);
658
654
  }
659
- // Write each file's results to cache
660
- for (const [filePath, fileResults] of resultsByFile.entries()) {
661
- await cache.setAnalysisResult(filePath, fileResults);
655
+ violations.push(...findingsInFileOrder(findingsByFile));
656
+ // A cancelled run writes nothing; entries of files the file pass
657
+ // analyzed are complete otherwise (file-scope findings only)
658
+ const writeCache = useCache && fileRun.run.stopReason !== 'cancelled';
659
+ if (writeCache) {
660
+ for (const [filePath, entry] of newEntries) {
661
+ await cache.setAnalysisResult(filePath, entry, cacheDependencies(filePath, entry));
662
+ }
662
663
  }
663
- // Log cache effectiveness
664
- const stats = cache.getStats();
665
- console.info(`Cache: Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
664
+ console.info(`Cache: Cached ${writeCache ? newEntries.size : 0} files (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
666
665
  }
667
666
  // Calculate summary (before pagination)
668
667
  const summary = this.calculateSummary(violations);
669
668
  const duration = Date.now() - startTime;
670
- const page = paginateViolations(violations, params);
669
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
671
670
  // Gather orchestration stats using full Phase 6d/7b options
672
671
  let orchestrationMetrics;
673
672
  if (parallelKernel !== undefined) {
@@ -724,7 +723,7 @@ export class ScanArchitectureTool {
724
723
  * and appends each file's findings to `violations`. A worker terminated by
725
724
  * a cancel leaves no run summary; it is rebuilt from the files received.
726
725
  */
727
- async runRules(spec, violations, ctx) {
726
+ async runRules(spec, violations, ctx, perFile) {
728
727
  const total = spec.files.length;
729
728
  let analyzed = 0;
730
729
  let found = 0;
@@ -735,11 +734,16 @@ export class ScanArchitectureTool {
735
734
  file: (event) => {
736
735
  // The runner mode sets the violation id
737
736
  violations.push(...event.findings);
737
+ perFile?.set(event.filePath, event.findings);
738
738
  analyzed++;
739
739
  found += event.findings.length;
740
740
  ctx.progress?.(analyzed, total, fileProgressMessage(analyzed, total, found));
741
741
  },
742
742
  }, { signal: ctx.signal });
743
+ if (!engine.cancelled) {
744
+ // the loop sent 0 first, then each analyzed count
745
+ finalFileProgress(ctx.progress, total, analyzed, found, total > 0 ? analyzed : undefined);
746
+ }
743
747
  const run = engine.run ?? {
744
748
  filesAnalyzed: analyzed,
745
749
  incomplete: true,
@@ -814,10 +818,10 @@ export class ScanArchitectureTool {
814
818
  startTime,
815
819
  }, violations, ctx);
816
820
  const filesAnalyzed = run.filesAnalyzed;
817
- const execution = toExecution(run, parseMaxDurationMs(params.maxDurationMs));
821
+ const execution = withFileCap(toExecution(run, parseMaxDurationMs(params.maxDurationMs)), scopeFiltered.length, filesToAnalyze.length, maxFiles);
818
822
  const duration = Date.now() - startTime;
819
823
  const summary = this.calculateSummary(violations);
820
- const page = paginateViolations(violations, params);
824
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
821
825
  return withScanSummary({
822
826
  violations: page.violations,
823
827
  counts: {
@@ -864,8 +868,11 @@ export class ScanArchitectureTool {
864
868
  });
865
869
  // Start analysis in background (don't await)
866
870
  this.runStreamingAnalysis(operationId, params).catch((error) => {
867
- // Mark operation as failed if error occurs
868
- store.markFailed(operationId, error instanceof Error ? error.message : String(error));
871
+ // Mark operation as failed if error occurs; the TTL sweep may have
872
+ // removed it already, and a throw here would end the server
873
+ if (store.hasOperation(operationId)) {
874
+ store.markFailed(operationId, error instanceof Error ? error.message : String(error));
875
+ }
869
876
  });
870
877
  // Return operationId immediately
871
878
  return {
@@ -899,12 +906,8 @@ export class ScanArchitectureTool {
899
906
  percentage: 0,
900
907
  timestamp: Date.now(),
901
908
  });
902
- // Load configuration
903
- const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
904
- const mergedParams = {
905
- ...config,
906
- ...params,
907
- };
909
+ // params already carry the tools['scan-architecture'] config (execute)
910
+ const mergedParams = params;
908
911
  const orchestration = mergedParams.orchestration ?? {};
909
912
  // Find tsconfig
910
913
  const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(params.rootPath);
@@ -1003,7 +1006,7 @@ export class ScanArchitectureTool {
1003
1006
  });
1004
1007
  violations.push(...run.violations);
1005
1008
  const filesProcessed = run.filesAnalyzed;
1006
- const execution = toExecution(run, maxDurationMs);
1009
+ const execution = withFileCap(toExecution(run, maxDurationMs), streamingScopeFiltered.length, filesToAnalyze.length, maxFiles);
1007
1010
  if (execution.note) {
1008
1011
  store.addEvent(operationId, {
1009
1012
  phase: 'analyzing',
@@ -1021,7 +1024,7 @@ export class ScanArchitectureTool {
1021
1024
  });
1022
1025
  // Store full result so get-operation-progress can return violations
1023
1026
  const summary = this.calculateSummary(violations);
1024
- const page = paginateViolations(violations, params);
1027
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
1025
1028
  store.setResult(operationId, withScanSummary({
1026
1029
  violations: page.violations,
1027
1030
  pagination: page.pagination,
@@ -1094,40 +1097,42 @@ export class ScanArchitectureTool {
1094
1097
  };
1095
1098
  }
1096
1099
  /**
1097
- * Load configuration from .angular-modernizer.json file.
1098
- * Only loads from the provided root path to avoid cache directory issues.
1100
+ * The `tools['scan-architecture']` section of `.angular-modernizer.json`.
1101
+ * Only loads from the provided root path, never from the server's cwd.
1099
1102
  */
1100
1103
  loadConfig(providedRootPath) {
1101
- // Only load config if rootPath is explicitly provided
1102
- // This prevents accidentally using process.cwd() which may point to the MCP server directory
1103
1104
  if (!providedRootPath) {
1104
1105
  return {};
1105
1106
  }
1106
- const configPath = resolve(providedRootPath, '.angular-modernizer.json');
1107
- if (existsSync(configPath)) {
1108
- try {
1109
- // Disable no-unsafe-assignment: JSON.parse() returns 'any' but config structure is validated below
1110
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1111
- const config = JSON.parse(readFileSync(configPath, 'utf-8'));
1112
- // Disable no-unsafe-member-access: Optional chaining safely handles missing properties
1113
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
1114
- const scanArchitectureConfig = config['scan-architecture'];
1115
- if (scanArchitectureConfig &&
1116
- typeof scanArchitectureConfig === 'object') {
1117
- return scanArchitectureConfig;
1118
- }
1119
- }
1120
- catch (error) {
1121
- console.warn(`Error loading config from ${configPath}:`, error);
1107
+ try {
1108
+ const toolConfig = loadConfig(providedRootPath).tools?.['scan-architecture'];
1109
+ if (toolConfig && typeof toolConfig === 'object') {
1110
+ return toolConfig;
1122
1111
  }
1123
1112
  }
1113
+ catch (error) {
1114
+ console.warn(`Error loading config:`, error);
1115
+ }
1124
1116
  return {};
1125
1117
  }
1126
1118
  /**
1127
- * Resolve scope configuration to actual file paths.
1128
- * Reads angular.json to find project paths.
1119
+ * Resolve scope configuration to actual file paths. A scope other than
1120
+ * `all` that resolves to no path is an error: the file filter treats an
1121
+ * empty path list as "everything", so such a scope used to scan the whole
1122
+ * project (its first `maxFiles` files) instead of nothing.
1129
1123
  */
1130
1124
  resolveScope(rootPath, scope) {
1125
+ const resolved = this.resolveScopePaths(rootPath, scope);
1126
+ if (resolved.type !== 'all' && resolved.resolvedPaths.length === 0) {
1127
+ const requested = [...(scope?.paths ?? []), ...(scope?.names ?? [])];
1128
+ throw new Error(`Scope '${resolved.type}'${requested.length > 0 ? ` (${requested.join(', ')})` : ''} matches no folder below ${rootPath}`);
1129
+ }
1130
+ return resolved;
1131
+ }
1132
+ /**
1133
+ * Paths a scope stands for. Reads angular.json to find project paths.
1134
+ */
1135
+ resolveScopePaths(rootPath, scope) {
1131
1136
  // Default to scanning all
1132
1137
  if (!scope || scope.type === 'all') {
1133
1138
  return {
@@ -1325,4 +1330,69 @@ function toExecution(run, maxDurationMs) {
1325
1330
  ...(note ? { note } : {}),
1326
1331
  };
1327
1332
  }
1333
+ /**
1334
+ * Marks a scan whose `maxFiles` cap left files of the scope out as
1335
+ * incomplete; it used to report `incomplete: false` and `skippedFiles: 0`, so
1336
+ * a whole-project audit over 100 of 3392 files read as complete.
1337
+ */
1338
+ function withFileCap(execution, scopeFiles, selectedFiles, maxFiles) {
1339
+ const cut = scopeFiles - selectedFiles;
1340
+ if (cut <= 0) {
1341
+ return execution;
1342
+ }
1343
+ const capNote = `maxFiles ${maxFiles}: ${selectedFiles} of ${scopeFiles} files in scope selected, ${cut} not analyzed. ` +
1344
+ `Raise maxFiles (argument or tools['scan-architecture'].maxFiles) or narrow the scope.`;
1345
+ return {
1346
+ ...execution,
1347
+ incomplete: true,
1348
+ stopReason: execution.stopReason ?? 'max-files',
1349
+ skippedFiles: execution.skippedFiles + cut,
1350
+ scopeFiles,
1351
+ note: execution.note === undefined ? capNote : `${execution.note} ${capNote}`,
1352
+ };
1353
+ }
1354
+ /**
1355
+ * Violations with `filePath` relative to the scanned root, as the other scans
1356
+ * return them; the rules and the cache work with absolute paths.
1357
+ */
1358
+ function relativeToRoot(violations, rootPath) {
1359
+ return violations.map((v) => ({ ...v, filePath: relative(rootPath, v.filePath) }));
1360
+ }
1361
+ /**
1362
+ * Version of the imperative path's cache entries: one entry per analyzed file
1363
+ * with the findings of the file-scope rules. Entries of the earlier layout
1364
+ * were filed under each finding's file and held project-wide findings;
1365
+ * `scan-architecture-3` drops solid:circular-dependency findings without
1366
+ * `cycleId` that carry the path of a long cycle on every file.
1367
+ */
1368
+ const ARCHITECTURE_CACHE_VERSION = 'scan-architecture-3';
1369
+ /** Files a cache entry depends on besides the analyzed file itself. */
1370
+ function cacheDependencies(filePath, findings) {
1371
+ let text = '';
1372
+ try {
1373
+ text = readFileSync(filePath, 'utf-8');
1374
+ }
1375
+ catch {
1376
+ // An unreadable file has no template dependencies
1377
+ }
1378
+ return templateDependencies(filePath, text, findings.map((f) => f.filePath), existsSync);
1379
+ }
1380
+ /**
1381
+ * The file pass and the project pass of the imperative path as one run: it
1382
+ * is incomplete when either pass stopped early.
1383
+ */
1384
+ function combineRuns(fileRun, projectRun) {
1385
+ if (projectRun === undefined) {
1386
+ return fileRun;
1387
+ }
1388
+ const stopReason = fileRun.stopReason ?? projectRun.stopReason;
1389
+ return {
1390
+ filesAnalyzed: fileRun.filesAnalyzed,
1391
+ incomplete: fileRun.incomplete || projectRun.incomplete,
1392
+ ...(stopReason === undefined ? {} : { stopReason }),
1393
+ skippedFiles: Math.max(fileRun.skippedFiles, projectRun.skippedFiles),
1394
+ ruleTimings: [...fileRun.ruleTimings, ...projectRun.ruleTimings].sort((a, b) => b.ms - a.ms),
1395
+ durationMs: fileRun.durationMs + projectRun.durationMs,
1396
+ };
1397
+ }
1328
1398
  //# sourceMappingURL=scan-architecture.js.map
@@ -41,7 +41,12 @@ export interface ScanSolidResult {
41
41
  /** Root path of the scanned project. */
42
42
  projectRoot: string;
43
43
  };
44
- /** Orchestration figures; set only when `orchestration.useWorkerThreads` is set. */
44
+ /** Deprecation notices of the call (`orchestration` has no effect). */
45
+ warnings?: string[];
46
+ /**
47
+ * @deprecated No longer set: the block claimed a parallel run that never
48
+ * happened. The scan always runs in the scan worker.
49
+ */
45
50
  orchestration?: {
46
51
  /** Whether the scan ran in parallel. */
47
52
  parallel: boolean;
@@ -72,7 +77,7 @@ export interface ScanSolidResult {
72
77
  }
73
78
  /**
74
79
  * MCP tool `scan-solid`: scans for SOLID principle violations. Runs only the
75
- * SolidPlugin (7 rules: DIP, SRP, LSP, OCP, ISP).
80
+ * rules of the SolidPlugin (DIP, SRP, LSP, OCP, ISP).
76
81
  */
77
82
  export declare class ScanSolidTool implements MCPTool {
78
83
  readonly name = "scan-solid";
@@ -114,6 +119,12 @@ export declare class ScanSolidTool implements MCPTool {
114
119
  description: string;
115
120
  default: string[];
116
121
  };
122
+ cache: {
123
+ readonly type: "string";
124
+ readonly enum: readonly ["use", "refresh"];
125
+ readonly default: "use";
126
+ readonly description: "use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Read from the call only, never from the tools section of .angular-modernizer.json";
127
+ };
117
128
  includeAutoFixes: {
118
129
  type: string;
119
130
  description: string;
@@ -135,17 +146,19 @@ export declare class ScanSolidTool implements MCPTool {
135
146
  default: number;
136
147
  };
137
148
  orchestration: {
138
- type: string;
139
- description: string;
140
- properties: {
141
- parallel: {
142
- type: string;
143
- description: string;
144
- default: boolean;
149
+ readonly type: "object";
150
+ readonly description: "Deprecated, no effect, kept in 2.x: the scan always runs in the scan worker and answers with a notice in warnings. Leave unset.";
151
+ readonly deprecated: true;
152
+ readonly properties: {
153
+ readonly parallel: {
154
+ readonly type: "boolean";
155
+ readonly description: "Deprecated, no effect.";
156
+ readonly deprecated: true;
145
157
  };
146
- maxWorkers: {
147
- type: string;
148
- description: string;
158
+ readonly maxWorkers: {
159
+ readonly type: "number";
160
+ readonly description: "Deprecated, no effect.";
161
+ readonly deprecated: true;
149
162
  };
150
163
  };
151
164
  };
@@ -163,8 +176,8 @@ export declare class ScanSolidTool implements MCPTool {
163
176
  };
164
177
  execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<ScanSolidResult>;
165
178
  /**
166
- * Load configuration from .angular-modernizer.json file.
167
- * Only loads from the provided root path to avoid cache directory issues.
179
+ * The `tools['scan-solid']` section of `.angular-modernizer.json`; arguments of
180
+ * the call override it.
168
181
  */
169
182
  private loadConfig;
170
183
  private calculateSummary;