@angular-modernizer/adapter-mcp 1.2.0 → 2.1.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 (138) hide show
  1. package/CHANGELOG.md +688 -0
  2. package/README.md +84 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +10 -0
  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 +7 -4
  21. package/dist/tools/analyze-build-impact.js +8 -3
  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 +55 -4
  27. package/dist/tools/analyze-project.js +104 -15
  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/compare-health.d.ts +40 -4
  32. package/dist/tools/compare-health.js +22 -5
  33. package/dist/tools/extract-libraries.js +42 -27
  34. package/dist/tools/find-angular-symbol.js +3 -2
  35. package/dist/tools/find-component-hosts.js +3 -2
  36. package/dist/tools/find-usages.js +21 -12
  37. package/dist/tools/get-call-graph.js +15 -2
  38. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  39. package/dist/tools/get-operation-progress-tool.js +2 -2
  40. package/dist/tools/get-operation-progress.d.ts +4 -1
  41. package/dist/tools/get-operation-progress.js +6 -2
  42. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  43. package/dist/tools/helpers/analysis-output.js +25 -1
  44. package/dist/tools/helpers/build-cache.d.ts +27 -0
  45. package/dist/tools/helpers/build-cache.js +86 -0
  46. package/dist/tools/helpers/class-filter.d.ts +18 -0
  47. package/dist/tools/helpers/class-filter.js +30 -0
  48. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  49. package/dist/tools/helpers/cli-arguments.js +35 -0
  50. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  51. package/dist/tools/helpers/feedback-catalog.js +196 -0
  52. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  53. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  54. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  55. package/dist/tools/helpers/file-type-check.js +56 -0
  56. package/dist/tools/helpers/health-delta.d.ts +6 -0
  57. package/dist/tools/helpers/health-delta.js +4 -1
  58. package/dist/tools/helpers/library-import-warning.d.ts +33 -0
  59. package/dist/tools/helpers/library-import-warning.js +38 -0
  60. package/dist/tools/helpers/library-imports.d.ts +38 -14
  61. package/dist/tools/helpers/library-imports.js +128 -23
  62. package/dist/tools/helpers/output-contract.d.ts +64 -0
  63. package/dist/tools/helpers/output-contract.js +67 -0
  64. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  65. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  66. package/dist/tools/helpers/project-cache.d.ts +5 -4
  67. package/dist/tools/helpers/project-cache.js +21 -16
  68. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  69. package/dist/tools/helpers/project-decorators.js +13 -6
  70. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  71. package/dist/tools/helpers/refresh-apply.js +460 -0
  72. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  73. package/dist/tools/helpers/refresh-inventory.js +631 -0
  74. package/dist/tools/helpers/rule-runner.js +3 -1
  75. package/dist/tools/helpers/scan-cache.d.ts +117 -5
  76. package/dist/tools/helpers/scan-cache.js +179 -6
  77. package/dist/tools/helpers/scan-engine.d.ts +43 -6
  78. package/dist/tools/helpers/scan-engine.js +141 -22
  79. package/dist/tools/helpers/scan-plan.js +16 -2
  80. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  81. package/dist/tools/helpers/source-map-loader.js +226 -0
  82. package/dist/tools/helpers/template-check.d.ts +76 -0
  83. package/dist/tools/helpers/template-check.js +158 -0
  84. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  85. package/dist/tools/helpers/tool-cache.js +9 -3
  86. package/dist/tools/helpers/tool-context.d.ts +18 -0
  87. package/dist/tools/helpers/tool-context.js +29 -0
  88. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  89. package/dist/tools/helpers/transform-safety.js +357 -4
  90. package/dist/tools/inspect-form-group.js +5 -0
  91. package/dist/tools/inspect-i18n.d.ts +1 -1
  92. package/dist/tools/inspect-template.js +8 -2
  93. package/dist/tools/learn-patterns.d.ts +43 -28
  94. package/dist/tools/learn-patterns.js +83 -161
  95. package/dist/tools/list-imports.d.ts +1 -1
  96. package/dist/tools/orchestrate-migration.d.ts +19 -1
  97. package/dist/tools/orchestrate-migration.js +52 -10
  98. package/dist/tools/parse-stack-trace.d.ts +48 -1
  99. package/dist/tools/parse-stack-trace.js +108 -9
  100. package/dist/tools/plan-migration.js +22 -10
  101. package/dist/tools/refresh-state.d.ts +378 -0
  102. package/dist/tools/refresh-state.js +370 -0
  103. package/dist/tools/resolve-type.js +10 -3
  104. package/dist/tools/review-feedback.d.ts +42 -7
  105. package/dist/tools/review-feedback.js +24 -17
  106. package/dist/tools/rollback-changes.d.ts +5 -0
  107. package/dist/tools/rollback-changes.js +7 -2
  108. package/dist/tools/run-angular-cli.js +36 -22
  109. package/dist/tools/run-build.d.ts +33 -28
  110. package/dist/tools/run-build.js +136 -438
  111. package/dist/tools/run-schematic.d.ts +8 -2
  112. package/dist/tools/run-schematic.js +80 -50
  113. package/dist/tools/scan-all.d.ts +37 -15
  114. package/dist/tools/scan-all.js +76 -115
  115. package/dist/tools/scan-angular.d.ts +33 -14
  116. package/dist/tools/scan-angular.js +77 -94
  117. package/dist/tools/scan-architecture.d.ts +37 -12
  118. package/dist/tools/scan-architecture.js +220 -139
  119. package/dist/tools/scan-solid.d.ts +33 -14
  120. package/dist/tools/scan-solid.js +80 -91
  121. package/dist/tools/search-codebase.d.ts +6 -1
  122. package/dist/tools/search-codebase.js +13 -7
  123. package/dist/tools/suggest-improvements.d.ts +34 -3
  124. package/dist/tools/suggest-improvements.js +34 -9
  125. package/dist/tools/trace-output-flow.js +3 -2
  126. package/dist/tools/transform-code-batch.d.ts +9 -9
  127. package/dist/tools/transform-code.d.ts +161 -12
  128. package/dist/tools/transform-code.js +715 -206
  129. package/dist/tools/validate-before-transform.js +2 -1
  130. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  131. package/dist/tools/validate-project-compatibility.js +33 -225
  132. package/dist/tools/validate-transformation.d.ts +40 -26
  133. package/dist/tools/validate-transformation.js +115 -294
  134. package/dist/tools/verify-citations.js +8 -2
  135. package/dist/types.d.ts +9 -9
  136. package/dist/utils/format-tool-response.d.ts +3 -1
  137. package/dist/utils/format-tool-response.js +8 -3
  138. package/package.json +14 -13
@@ -1,7 +1,9 @@
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, ARCHITECTURE_CACHE_VERSION, templateDependencies, } from './helpers/scan-cache.js';
6
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
5
7
  import { loadSourceFiles } from './helpers/load-source-files.js';
6
8
  import { filterFilesByScopePaths } from './helpers/scope-paths.js';
7
9
  import { toParallelOptions } from '../types.js';
@@ -10,7 +12,7 @@ import { ArchitecturePlugin } from '@angular-modernizer/plugin-architecture';
10
12
  import { createPublicApi } from '@angular-modernizer/api';
11
13
  import { getWorkerScriptPath } from '@angular-modernizer/worker';
12
14
  import { glob } from 'glob';
13
- import { resolve, extname } from 'node:path';
15
+ import { resolve, extname, relative } from 'node:path';
14
16
  import { readFileSync, existsSync, statSync } from 'node:fs';
15
17
  import { randomUUID } from 'node:crypto';
16
18
  import { ProgressStore } from '../streaming/progress-store.js';
@@ -41,15 +43,15 @@ function paginateViolations(violations, params) {
41
43
  */
42
44
  function withScanSummary(result) {
43
45
  const notes = result.execution?.note === undefined ? [] : [result.execution.note];
44
- return {
46
+ return withLibraryImportWarning({
45
47
  ...result,
46
48
  summary: describeScan(result.counts, result.violations, result.pagination, notes),
47
- };
49
+ }, result.unresolvedLibraryImports);
48
50
  }
49
51
  /**
50
52
  * MCP tool `scan-architecture`: scans for architectural issues. Runs only the
51
- * ArchitecturePlugin (17 rules: import cycles, layer violations, god objects
52
- * and others).
53
+ * rules of the ArchitecturePlugin (import cycles, layer violations, god
54
+ * objects and others).
53
55
  */
54
56
  export class ScanArchitectureTool {
55
57
  name = 'scan-architecture';
@@ -60,7 +62,7 @@ export class ScanArchitectureTool {
60
62
  idempotentHint: true,
61
63
  openWorldHint: false,
62
64
  };
63
- description = 'Scan Angular codebases for architectural issues with the 17 architecture rules: import cycles ' +
65
+ description = 'Scan Angular codebases for architectural issues with the architecture rules: import cycles ' +
64
66
  '(solid:circular-dependency, NG0919 risk), import direction, god objects, layer boundaries, content ' +
65
67
  'placement, service bags and more. Returns the violations directly; streaming: true (deprecated) runs in the background instead (poll get-operation-progress); ' +
66
68
  'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
@@ -111,7 +113,7 @@ export class ScanArchitectureTool {
111
113
  description: 'Specific rules to run (optional, runs all if not specified). ' +
112
114
  'Must be exact rule.id values — short names like "circular-dependency" will NOT match. ' +
113
115
  'Valid IDs: solid:circular-dependency, solid:import-direction-violation, solid:god-object-violation, ' +
114
- 'architecture:component-complexity, architecture:service-architecture, architecture:content-placement, ' +
116
+ 'architecture:component-complexity, architecture:service-architecture (deprecated, reports nothing), architecture:content-placement, ' +
115
117
  'architecture:advanced-content-placement, architecture:model-separation, architecture:rxjs-memory-leak, ' +
116
118
  'architecture:error-handling-pattern, architecture:inheritance-analysis, architecture:performance-pattern, ' +
117
119
  'architecture:cross-file-architecture, architecture:service-bag, architecture:static-in-stateful-class, ' +
@@ -138,14 +140,18 @@ export class ScanArchitectureTool {
138
140
  '**/*.test.ts',
139
141
  ],
140
142
  },
143
+ cache: {
144
+ ...SCAN_CACHE_MODE_SCHEMA,
145
+ 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",
146
+ },
141
147
  includeAutoFixes: {
142
148
  type: 'boolean',
143
- description: 'Whether to include auto-fix suggestions',
144
- default: true,
149
+ description: 'Deprecated, no effect: scan-architecture always returns the suggested fixes',
150
+ deprecated: true,
145
151
  },
146
152
  maxFiles: {
147
153
  type: 'number',
148
- description: 'Maximum number of files to analyze (default: 100 to prevent memory issues)',
154
+ 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
155
  default: 100,
150
156
  },
151
157
  maxResults: {
@@ -160,7 +166,7 @@ export class ScanArchitectureTool {
160
166
  },
161
167
  orchestration: {
162
168
  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.',
169
+ 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
170
  properties: {
165
171
  parallel: {
166
172
  type: 'boolean',
@@ -228,7 +234,7 @@ export class ScanArchitectureTool {
228
234
  },
229
235
  streaming: {
230
236
  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.',
237
+ 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
238
  default: false,
233
239
  },
234
240
  apiStyle: {
@@ -259,6 +265,7 @@ export class ScanArchitectureTool {
259
265
  incomplete: { type: 'boolean' },
260
266
  stopReason: { type: 'string' },
261
267
  skippedFiles: { type: 'integer' },
268
+ scopeFiles: { type: 'integer' },
262
269
  ruleTimings: { type: 'array', items: { type: 'object' } },
263
270
  note: { type: 'string' },
264
271
  },
@@ -270,7 +277,13 @@ export class ScanArchitectureTool {
270
277
  intermediateResults: { type: 'object' },
271
278
  });
272
279
  async execute(args, ctx = {}) {
273
- const params = args;
280
+ const callParams = args;
281
+ // tools['scan-architecture'] of .angular-modernizer.json, overridden by
282
+ // the arguments of the call; all three paths read the merged parameters
283
+ const params = {
284
+ ...this.loadConfig(typeof callParams.rootPath === 'string' ? callParams.rootPath : undefined),
285
+ ...callParams,
286
+ };
274
287
  // Check if streaming mode is enabled
275
288
  const streaming = params.streaming ?? false;
276
289
  if (streaming) {
@@ -280,15 +293,14 @@ export class ScanArchitectureTool {
280
293
  // Check if fluent API should be used
281
294
  const apiStyle = params.apiStyle ?? 'fluent';
282
295
  if (apiStyle === 'fluent') {
296
+ // The fluent path has no orchestration; it used to ignore the argument
297
+ // without a word (incremental and parallel ran as a plain scan)
298
+ if (callParams.orchestration !== undefined) {
299
+ throw new Error("orchestration is read only with apiStyle 'imperative' (deprecated WorkerPool path); leave it unset for the default scan");
300
+ }
283
301
  return this.executeWithFluentApi(params, ctx);
284
302
  }
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
- };
303
+ const mergedParams = params;
292
304
  // Use orchestration object directly
293
305
  const orchestration = mergedParams.orchestration ?? {};
294
306
  // Validate input
@@ -353,6 +365,7 @@ export class ScanArchitectureTool {
353
365
  // own analysis workers); the sequential path runs in a scan worker.
354
366
  let parallelKernel;
355
367
  let rulesExecuted = [];
368
+ let unresolvedLibraryImports;
356
369
  let lastProgress;
357
370
  if (orchestration.parallel || orchestration.incremental) {
358
371
  // Initialize kernel with ArchitecturePlugin only + caching
@@ -444,6 +457,8 @@ export class ScanArchitectureTool {
444
457
  '@angular-modernizer/plugin-architecture',
445
458
  ],
446
459
  rules: params.rules,
460
+ // rules['<id>'] options and suppressionComments for every rule
461
+ rulesConfig: (loadConfig(params.rootPath).rules ?? {}),
447
462
  timeout: orchestration.timeout ?? 120000, // 2 minutes for complex architecture rules
448
463
  };
449
464
  // Process each batch; cancellation is checked between batches
@@ -559,115 +574,108 @@ export class ScanArchitectureTool {
559
574
  else {
560
575
  // Sequential analysis mode (existing logic)
561
576
  console.info('Using sequential analysis mode...');
562
- let filesToAnalyze = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, maxFiles);
563
- // Apply scope filtering for sequential mode
577
+ // Scope first, then the cap: capping first left a scope outside the
578
+ // first maxFiles sorted project files with nothing to analyze
579
+ const filesToAnalyze = scopeFilteredFiles.slice(0, maxFiles);
564
580
  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})`);
581
+ console.info(`Scope filter: ${scopeFilteredFiles.length} files (from ${preDiscoveryFiles.length})`);
568
582
  }
569
583
  // Update resolved scope with matched files count
570
584
  resolvedScope.matchedFiles = filesToAnalyze.length;
571
585
  // ============================================================================
572
- // CACHE READ SYSTEM (Sequential Mode Only)
586
+ // CACHE (sequential mode only)
573
587
  // ============================================================================
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.
588
+ // One entry per analyzed file, also without findings, holding the
589
+ // findings of the rules with file scope. Rules with scope 'project'
590
+ // (library-extraction-opportunity, inheritance-analysis,
591
+ // model-separation) are never cached: they run over the whole scope on
592
+ // every call. Cached per file, a project-wide finding reported at a
593
+ // representative file was served again while a warm run reported it
594
+ // once more at another file (70 -> 74 -> 78 findings on a large app).
595
+ // The cache version carries the rule configuration (scanCacheVersion).
592
596
  // ============================================================================
593
- const cache = await openToolCache(mergedParams.rootPath, 'architecture');
594
- const cachedViolations = []; // eslint-disable-line @typescript-eslint/no-explicit-any
597
+ // Library resolution state before the cache read: it is part of the
598
+ // cache version, so entries of another node_modules state are not served
599
+ const libraryCheck = await (await import('./helpers/library-imports.js')).checkScanScope(tsConfigPath, filesToAnalyze);
600
+ unresolvedLibraryImports =
601
+ libraryCheck.unresolved.imports > 0 ? libraryCheck.unresolved : undefined;
602
+ const cache = await openToolCache(mergedParams.rootPath, 'architecture', scanCacheVersion(ARCHITECTURE_CACHE_VERSION, mergedParams.rootPath, undefined, {
603
+ unresolvedPackages: libraryCheck.packages,
604
+ }));
605
+ // A run limited by rules holds only those rules' findings per file:
606
+ // it neither reads the cache nor writes entries a full run would
607
+ // take for complete
608
+ const useCache = params.rules === undefined;
609
+ // refresh analyzes every file and overwrites the entries; only the
610
+ // call's own argument counts, not the tools section
611
+ const cacheMode = scanCacheMode(args);
612
+ const findingsByFile = new Map();
595
613
  const filesToProcess = [];
596
614
  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);
615
+ const cached = useCache && cacheMode === 'use' ? await readCachedFindings(filePath, cache) : null;
616
+ if (cached !== null) {
617
+ findingsByFile.set(filePath, cached);
601
618
  }
602
619
  else {
603
- // File not cached or has changed
604
620
  filesToProcess.push(filePath);
605
621
  }
606
622
  }
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({
623
+ const cacheHits = filesToAnalyze.length - filesToProcess.length;
624
+ console.info(`Cache: ${cacheHits} files from cache, ${filesToProcess.length} files to analyze (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
625
+ const ruleFilter = params.rules === undefined ? {} : { ruleIds: params.rules };
626
+ const newEntries = new Map();
627
+ const fileRun = await this.runRules({
612
628
  tool: this.name,
613
629
  plugins: 'architecture',
614
630
  tsConfigPath,
615
631
  rootPath: mergedParams.rootPath,
616
632
  files: filesToProcess,
617
633
  mode: 'runner',
618
- ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
634
+ ...ruleFilter,
635
+ ruleScope: 'file',
619
636
  maxDurationMs,
620
637
  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);
638
+ }, [], ctx, newEntries);
639
+ const projectFindings = new Map();
640
+ const projectRun = fileRun.run.stopReason === 'cancelled'
641
+ ? undefined
642
+ : await this.runRules({
643
+ tool: this.name,
644
+ plugins: 'architecture',
645
+ tsConfigPath,
646
+ rootPath: mergedParams.rootPath,
647
+ files: filesToAnalyze,
648
+ mode: 'runner',
649
+ ...ruleFilter,
650
+ ruleScope: 'project',
651
+ maxDurationMs,
652
+ startTime,
653
+ }, [], ctx, projectFindings);
654
+ rulesExecuted = [...fileRun.ruleIds, ...(projectRun?.ruleIds ?? [])];
655
+ const run = combineRuns(fileRun.run, projectRun?.run);
656
+ execution = withFileCap(toExecution(run, maxDurationMs), scopeFilteredFiles.length, filesToAnalyze.length, maxFiles);
657
+ filesAnalyzed = cacheHits + fileRun.run.filesAnalyzed;
658
+ for (const [filePath, entry] of newEntries) {
659
+ findingsByFile.set(filePath, entry);
660
+ }
661
+ for (const [filePath, entry] of projectFindings) {
662
+ findingsByFile.set(filePath, [...(findingsByFile.get(filePath) ?? []), ...entry]);
658
663
  }
659
- // Write each file's results to cache
660
- for (const [filePath, fileResults] of resultsByFile.entries()) {
661
- await cache.setAnalysisResult(filePath, fileResults);
664
+ violations.push(...findingsInFileOrder(findingsByFile));
665
+ // A cancelled run writes nothing; entries of files the file pass
666
+ // analyzed are complete otherwise (file-scope findings only)
667
+ const writeCache = useCache && fileRun.run.stopReason !== 'cancelled';
668
+ if (writeCache) {
669
+ for (const [filePath, entry] of newEntries) {
670
+ await cache.setAnalysisResult(filePath, entry, cacheDependencies(filePath, entry));
671
+ }
662
672
  }
663
- // Log cache effectiveness
664
- const stats = cache.getStats();
665
- console.info(`Cache: Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
673
+ console.info(`Cache: Cached ${writeCache ? newEntries.size : 0} files (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
666
674
  }
667
675
  // Calculate summary (before pagination)
668
676
  const summary = this.calculateSummary(violations);
669
677
  const duration = Date.now() - startTime;
670
- const page = paginateViolations(violations, params);
678
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
671
679
  // Gather orchestration stats using full Phase 6d/7b options
672
680
  let orchestrationMetrics;
673
681
  if (parallelKernel !== undefined) {
@@ -703,6 +711,7 @@ export class ScanArchitectureTool {
703
711
  ...summary,
704
712
  analyzedFiles: filesAnalyzed,
705
713
  },
714
+ ...(unresolvedLibraryImports === undefined ? {} : { unresolvedLibraryImports }),
706
715
  metadata: {
707
716
  rulesExecuted,
708
717
  duration,
@@ -724,7 +733,7 @@ export class ScanArchitectureTool {
724
733
  * and appends each file's findings to `violations`. A worker terminated by
725
734
  * a cancel leaves no run summary; it is rebuilt from the files received.
726
735
  */
727
- async runRules(spec, violations, ctx) {
736
+ async runRules(spec, violations, ctx, perFile) {
728
737
  const total = spec.files.length;
729
738
  let analyzed = 0;
730
739
  let found = 0;
@@ -735,11 +744,16 @@ export class ScanArchitectureTool {
735
744
  file: (event) => {
736
745
  // The runner mode sets the violation id
737
746
  violations.push(...event.findings);
747
+ perFile?.set(event.filePath, event.findings);
738
748
  analyzed++;
739
749
  found += event.findings.length;
740
750
  ctx.progress?.(analyzed, total, fileProgressMessage(analyzed, total, found));
741
751
  },
742
752
  }, { signal: ctx.signal });
753
+ if (!engine.cancelled) {
754
+ // the loop sent 0 first, then each analyzed count
755
+ finalFileProgress(ctx.progress, total, analyzed, found, total > 0 ? analyzed : undefined);
756
+ }
743
757
  const run = engine.run ?? {
744
758
  filesAnalyzed: analyzed,
745
759
  incomplete: true,
@@ -748,7 +762,14 @@ export class ScanArchitectureTool {
748
762
  ruleTimings: [],
749
763
  durationMs: Date.now() - (spec.startTime ?? Date.now()),
750
764
  };
751
- return { run, ruleIds: engine.ruleIds };
765
+ return {
766
+ run,
767
+ ruleIds: engine.ruleIds,
768
+ // Only when some do not resolve, like the other scans
769
+ ...((engine.unresolvedLibraryImports?.imports ?? 0) > 0
770
+ ? { unresolvedLibraryImports: engine.unresolvedLibraryImports }
771
+ : {}),
772
+ };
752
773
  }
753
774
  /**
754
775
  * Execute analysis using fluent API.
@@ -802,28 +823,30 @@ export class ScanArchitectureTool {
802
823
  // rules such as layer-boundary-violation returned 0 violations, Bug 1/3),
803
824
  // in a scan worker when enabled.
804
825
  const violations = [];
805
- const { run, ruleIds } = await this.runRules({
826
+ const { run, ruleIds, unresolvedLibraryImports } = await this.runRules({
806
827
  tool: this.name,
807
828
  plugins: 'architecture',
808
829
  tsConfigPath,
809
830
  rootPath: params.rootPath,
810
831
  files: filesToAnalyze,
811
832
  mode: 'runner',
833
+ libraryImports: true,
812
834
  ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
813
835
  maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
814
836
  startTime,
815
837
  }, violations, ctx);
816
838
  const filesAnalyzed = run.filesAnalyzed;
817
- const execution = toExecution(run, parseMaxDurationMs(params.maxDurationMs));
839
+ const execution = withFileCap(toExecution(run, parseMaxDurationMs(params.maxDurationMs)), scopeFiltered.length, filesToAnalyze.length, maxFiles);
818
840
  const duration = Date.now() - startTime;
819
841
  const summary = this.calculateSummary(violations);
820
- const page = paginateViolations(violations, params);
842
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
821
843
  return withScanSummary({
822
844
  violations: page.violations,
823
845
  counts: {
824
846
  ...summary,
825
847
  analyzedFiles: filesAnalyzed,
826
848
  },
849
+ ...(unresolvedLibraryImports === undefined ? {} : { unresolvedLibraryImports }),
827
850
  metadata: {
828
851
  rulesExecuted: ruleIds,
829
852
  duration,
@@ -864,8 +887,11 @@ export class ScanArchitectureTool {
864
887
  });
865
888
  // Start analysis in background (don't await)
866
889
  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));
890
+ // Mark operation as failed if error occurs; the TTL sweep may have
891
+ // removed it already, and a throw here would end the server
892
+ if (store.hasOperation(operationId)) {
893
+ store.markFailed(operationId, error instanceof Error ? error.message : String(error));
894
+ }
869
895
  });
870
896
  // Return operationId immediately
871
897
  return {
@@ -899,12 +925,8 @@ export class ScanArchitectureTool {
899
925
  percentage: 0,
900
926
  timestamp: Date.now(),
901
927
  });
902
- // Load configuration
903
- const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
904
- const mergedParams = {
905
- ...config,
906
- ...params,
907
- };
928
+ // params already carry the tools['scan-architecture'] config (execute)
929
+ const mergedParams = params;
908
930
  const orchestration = mergedParams.orchestration ?? {};
909
931
  // Find tsconfig
910
932
  const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(params.rootPath);
@@ -1003,7 +1025,7 @@ export class ScanArchitectureTool {
1003
1025
  });
1004
1026
  violations.push(...run.violations);
1005
1027
  const filesProcessed = run.filesAnalyzed;
1006
- const execution = toExecution(run, maxDurationMs);
1028
+ const execution = withFileCap(toExecution(run, maxDurationMs), streamingScopeFiltered.length, filesToAnalyze.length, maxFiles);
1007
1029
  if (execution.note) {
1008
1030
  store.addEvent(operationId, {
1009
1031
  phase: 'analyzing',
@@ -1021,7 +1043,7 @@ export class ScanArchitectureTool {
1021
1043
  });
1022
1044
  // Store full result so get-operation-progress can return violations
1023
1045
  const summary = this.calculateSummary(violations);
1024
- const page = paginateViolations(violations, params);
1046
+ const page = paginateViolations(relativeToRoot(violations, params.rootPath), params);
1025
1047
  store.setResult(operationId, withScanSummary({
1026
1048
  violations: page.violations,
1027
1049
  pagination: page.pagination,
@@ -1094,40 +1116,42 @@ export class ScanArchitectureTool {
1094
1116
  };
1095
1117
  }
1096
1118
  /**
1097
- * Load configuration from .angular-modernizer.json file.
1098
- * Only loads from the provided root path to avoid cache directory issues.
1119
+ * The `tools['scan-architecture']` section of `.angular-modernizer.json`.
1120
+ * Only loads from the provided root path, never from the server's cwd.
1099
1121
  */
1100
1122
  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
1123
  if (!providedRootPath) {
1104
1124
  return {};
1105
1125
  }
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);
1126
+ try {
1127
+ const toolConfig = loadConfig(providedRootPath).tools?.['scan-architecture'];
1128
+ if (toolConfig && typeof toolConfig === 'object') {
1129
+ return toolConfig;
1122
1130
  }
1123
1131
  }
1132
+ catch (error) {
1133
+ console.warn(`Error loading config:`, error);
1134
+ }
1124
1135
  return {};
1125
1136
  }
1126
1137
  /**
1127
- * Resolve scope configuration to actual file paths.
1128
- * Reads angular.json to find project paths.
1138
+ * Resolve scope configuration to actual file paths. A scope other than
1139
+ * `all` that resolves to no path is an error: the file filter treats an
1140
+ * empty path list as "everything", so such a scope used to scan the whole
1141
+ * project (its first `maxFiles` files) instead of nothing.
1129
1142
  */
1130
1143
  resolveScope(rootPath, scope) {
1144
+ const resolved = this.resolveScopePaths(rootPath, scope);
1145
+ if (resolved.type !== 'all' && resolved.resolvedPaths.length === 0) {
1146
+ const requested = [...(scope?.paths ?? []), ...(scope?.names ?? [])];
1147
+ throw new Error(`Scope '${resolved.type}'${requested.length > 0 ? ` (${requested.join(', ')})` : ''} matches no folder below ${rootPath}`);
1148
+ }
1149
+ return resolved;
1150
+ }
1151
+ /**
1152
+ * Paths a scope stands for. Reads angular.json to find project paths.
1153
+ */
1154
+ resolveScopePaths(rootPath, scope) {
1131
1155
  // Default to scanning all
1132
1156
  if (!scope || scope.type === 'all') {
1133
1157
  return {
@@ -1325,4 +1349,61 @@ function toExecution(run, maxDurationMs) {
1325
1349
  ...(note ? { note } : {}),
1326
1350
  };
1327
1351
  }
1352
+ /**
1353
+ * Marks a scan whose `maxFiles` cap left files of the scope out as
1354
+ * incomplete; it used to report `incomplete: false` and `skippedFiles: 0`, so
1355
+ * a whole-project audit over 100 of 3392 files read as complete.
1356
+ */
1357
+ function withFileCap(execution, scopeFiles, selectedFiles, maxFiles) {
1358
+ const cut = scopeFiles - selectedFiles;
1359
+ if (cut <= 0) {
1360
+ return execution;
1361
+ }
1362
+ const capNote = `maxFiles ${maxFiles}: ${selectedFiles} of ${scopeFiles} files in scope selected, ${cut} not analyzed. ` +
1363
+ `Raise maxFiles (argument or tools['scan-architecture'].maxFiles) or narrow the scope.`;
1364
+ return {
1365
+ ...execution,
1366
+ incomplete: true,
1367
+ stopReason: execution.stopReason ?? 'max-files',
1368
+ skippedFiles: execution.skippedFiles + cut,
1369
+ scopeFiles,
1370
+ note: execution.note === undefined ? capNote : `${execution.note} ${capNote}`,
1371
+ };
1372
+ }
1373
+ /**
1374
+ * Violations with `filePath` relative to the scanned root, as the other scans
1375
+ * return them; the rules and the cache work with absolute paths.
1376
+ */
1377
+ function relativeToRoot(violations, rootPath) {
1378
+ return violations.map((v) => ({ ...v, filePath: relative(rootPath, v.filePath) }));
1379
+ }
1380
+ /** Files a cache entry depends on besides the analyzed file itself. */
1381
+ function cacheDependencies(filePath, findings) {
1382
+ let text = '';
1383
+ try {
1384
+ text = readFileSync(filePath, 'utf-8');
1385
+ }
1386
+ catch {
1387
+ // An unreadable file has no template dependencies
1388
+ }
1389
+ return templateDependencies(filePath, text, findings.map((f) => f.filePath), existsSync);
1390
+ }
1391
+ /**
1392
+ * The file pass and the project pass of the imperative path as one run: it
1393
+ * is incomplete when either pass stopped early.
1394
+ */
1395
+ function combineRuns(fileRun, projectRun) {
1396
+ if (projectRun === undefined) {
1397
+ return fileRun;
1398
+ }
1399
+ const stopReason = fileRun.stopReason ?? projectRun.stopReason;
1400
+ return {
1401
+ filesAnalyzed: fileRun.filesAnalyzed,
1402
+ incomplete: fileRun.incomplete || projectRun.incomplete,
1403
+ ...(stopReason === undefined ? {} : { stopReason }),
1404
+ skippedFiles: Math.max(fileRun.skippedFiles, projectRun.skippedFiles),
1405
+ ruleTimings: [...fileRun.ruleTimings, ...projectRun.ruleTimings].sort((a, b) => b.ms - a.ms),
1406
+ durationMs: fileRun.durationMs + projectRun.durationMs,
1407
+ };
1408
+ }
1328
1409
  //# sourceMappingURL=scan-architecture.js.map