@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
@@ -2,6 +2,25 @@ import { FeedbackStorage, ParserFeedbackAnalyzer, loadConfig, } from '@angular-m
2
2
  import { countList } from './helpers/analysis-output.js';
3
3
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
4
4
  import { feedbackSessionDirs, feedbackStorageConfig, resolveFeedbackRoots, } from './helpers/platform-root-resolver.js';
5
+ import { INCLUDE_OUTDATED_SCHEMA, SKIPPED_RECORDS_OUTPUT_SCHEMA, describeSkipped, skipMarkedRecords, } from './helpers/feedback-sidecar.js';
6
+ /** Storage that serves sessions loaded before, with the records the feedback sidecar marks left out. */
7
+ class LoadedSessions extends FeedbackStorage {
8
+ sessions;
9
+ constructor(config, sessions) {
10
+ super(config);
11
+ this.sessions = sessions;
12
+ }
13
+ loadSession(sessionId) {
14
+ const session = this.sessions.get(sessionId);
15
+ return session === undefined
16
+ ? Promise.reject(new Error(`Session ${sessionId} not found`))
17
+ : Promise.resolve(session);
18
+ }
19
+ }
20
+ /** Deprecation notice of every answer. */
21
+ const DEPRECATION_MESSAGE = 'analyze-parser-performance is deprecated, removal planned for 3.0: no MCP tool records the parser metadata it reads ' +
22
+ '(collect-feedback and transform-code do not write it; only feedback stored by the core TransformExecutionEngine carries it), ' +
23
+ 'so feedback collected through MCP gives 0 sessions analyzed. Use review-feedback for transformation feedback.';
5
24
  const NUMBER_RECORD = { type: 'object', additionalProperties: { type: 'number' } };
6
25
  /** Suggestions spelled out in the summary; the rest is in `suggestions`. */
7
26
  const SUMMARY_SUGGESTIONS = 5;
@@ -10,6 +29,7 @@ function describeParserPerformance(output) {
10
29
  const m = output.aggregatedMetrics;
11
30
  const strategies = countList(m.strategyDistribution, SUMMARY_SUGGESTIONS);
12
31
  const lines = [
32
+ DEPRECATION_MESSAGE,
13
33
  `${output.sessionsAnalyzed} session(s), ${output.totalTransformations} transformation(s); parse time ` +
14
34
  `avg ${m.avgParseTime.toFixed(1)} ms (min ${m.minParseTime}, max ${m.maxParseTime})` +
15
35
  (strategies === undefined ? '.' : `; strategies ${strategies}.`),
@@ -18,6 +38,7 @@ function describeParserPerformance(output) {
18
38
  for (const s of output.suggestions.slice(0, SUMMARY_SUGGESTIONS)) {
19
39
  lines.push(`- ${s.priority} ${s.category}: ${s.recommendation}`);
20
40
  }
41
+ lines.push(...describeSkipped(output.skippedRecords, output.sidecarWarnings ?? []));
21
42
  return lines.join('\n');
22
43
  }
23
44
  /**
@@ -33,17 +54,22 @@ function describeParserPerformance(output) {
33
54
  * Location Support:
34
55
  * - 'both' (default): the project, plus the platform store when ANGULAR_MODERNIZER_PLATFORM_ROOT is set
35
56
  * - Automatic session deduplication by sessionId
57
+ *
58
+ * @deprecated No MCP tool writes the parser metadata this tool reads; it stays
59
+ * registered and working in 2.x, removal planned for 3.0.
36
60
  */
37
61
  export class AnalyzeParserPerformanceTool {
38
62
  name = 'analyze-parser-performance';
39
- title = 'Analyze Parser Performance';
63
+ title = 'Analyze Parser Performance (deprecated)';
40
64
  annotations = {
41
65
  readOnlyHint: true,
42
66
  destructiveHint: false,
43
67
  idempotentHint: true,
44
68
  openWorldHint: false,
45
69
  };
46
- description = 'Analyze parser performance metrics from transformation feedback sessions. ' +
70
+ description = 'Deprecated, removal in 3.0: no MCP tool records parser metadata (collect-feedback and transform-code do not write it), ' +
71
+ 'so feedback collected through MCP gives 0 sessions analyzed; use review-feedback for transformation feedback. ' +
72
+ 'Analyze parser performance metrics from transformation feedback sessions. ' +
47
73
  'Generates actionable improvement recommendations based on parser behavior. ' +
48
74
  'Reads <projectRoot>/.claude-feedback, plus the platform store when ANGULAR_MODERNIZER_PLATFORM_ROOT is set. ' +
49
75
  'Supports multi-session aggregation. summary is a short text of the metrics and the top suggestions.';
@@ -71,6 +97,7 @@ export class AnalyzeParserPerformanceTool {
71
97
  "plus the platform store when ANGULAR_MODERNIZER_PLATFORM_ROOT is set; " +
72
98
  "'platform' requires that variable.",
73
99
  },
100
+ ...INCLUDE_OUTDATED_SCHEMA,
74
101
  },
75
102
  required: [],
76
103
  };
@@ -84,6 +111,7 @@ export class AnalyzeParserPerformanceTool {
84
111
  sessionsAnalyzed: { type: 'integer' },
85
112
  totalTransformations: { type: 'integer' },
86
113
  sourcesRead: STRING_ARRAY,
114
+ ...SKIPPED_RECORDS_OUTPUT_SCHEMA,
87
115
  aggregatedMetrics: {
88
116
  type: 'object',
89
117
  properties: {
@@ -131,6 +159,8 @@ export class AnalyzeParserPerformanceTool {
131
159
  required: ['sessionId', 'transformations', 'avgParseTime', 'primaryStrategy', 'successRate'],
132
160
  },
133
161
  },
162
+ deprecated: { type: 'boolean' },
163
+ message: { type: 'string' },
134
164
  summary: { type: 'string' },
135
165
  },
136
166
  required: [
@@ -140,6 +170,8 @@ export class AnalyzeParserPerformanceTool {
140
170
  'aggregatedMetrics',
141
171
  'suggestions',
142
172
  'sessionMetrics',
173
+ 'deprecated',
174
+ 'message',
143
175
  'summary',
144
176
  ],
145
177
  };
@@ -212,13 +244,29 @@ export class AnalyzeParserPerformanceTool {
212
244
  const sessionIds = input.sessionIds ?? (await feedbackStorage.listSessions());
213
245
  // Track which locations we read from
214
246
  const sourcesRead = feedbackSessionDirs(roots);
247
+ // Records the sidecar marks (duplicates, outdated) stay out unless includeOutdated
248
+ const loaded = new Map();
249
+ for (const sessionId of sessionIds) {
250
+ try {
251
+ loaded.set(sessionId, await feedbackStorage.loadSession(sessionId));
252
+ }
253
+ catch {
254
+ // Not found: reported below like a session without parser metadata
255
+ }
256
+ }
257
+ const marked = skipMarkedRecords(projectRoot, loaded, input.includeOutdated === true);
258
+ const markedStorage = new LoadedSessions(feedbackStorageConfig(roots), marked.byId);
259
+ const markOutput = {
260
+ skippedRecords: marked.skipped,
261
+ ...(marked.warnings.length === 0 ? {} : { sidecarWarnings: marked.warnings }),
262
+ };
215
263
  // Analyze each session and collect metrics
216
264
  const sessionMetricsList = [];
217
265
  const sessionDetails = [];
218
266
  for (const sessionId of sessionIds) {
219
267
  try {
220
268
  // Analyze parser performance for this session
221
- const metrics = await analyzer.analyzeParserPerformance(sessionId, feedbackStorage);
269
+ const metrics = await analyzer.analyzeParserPerformance(sessionId, markedStorage);
222
270
  sessionMetricsList.push(metrics);
223
271
  // Extract primary strategy (most used)
224
272
  const primaryStrategy = Object.entries(metrics.strategyDistribution).sort((a, b) => b[1] - a[1])[0]?.[0] ?? 'unknown';
@@ -247,11 +295,18 @@ export class AnalyzeParserPerformanceTool {
247
295
  sessionsAnalyzed: 0,
248
296
  totalTransformations: 0,
249
297
  sourcesRead,
298
+ ...markOutput,
250
299
  aggregatedMetrics: this.getEmptyAggregatedMetrics(),
251
300
  suggestions: [],
252
301
  sessionMetrics: [],
253
- summary: `No feedback session with parser metadata in ${sourcesRead.join(', ')} ` +
254
- `(${sessionIds.length} session(s) checked).`,
302
+ deprecated: true,
303
+ message: DEPRECATION_MESSAGE,
304
+ summary: `${DEPRECATION_MESSAGE}\n` +
305
+ `No feedback session with parser metadata in ${sourcesRead.join(', ')} ` +
306
+ `(${sessionIds.length} session(s) checked).` +
307
+ describeSkipped(markOutput.skippedRecords, markOutput.sidecarWarnings ?? [])
308
+ .map((line) => `\n${line}`)
309
+ .join(''),
255
310
  };
256
311
  }
257
312
  // Aggregate metrics across all sessions
@@ -268,11 +323,17 @@ export class AnalyzeParserPerformanceTool {
268
323
  sessionsAnalyzed: sessionMetricsList.length,
269
324
  totalTransformations: sessionMetricsList.reduce((sum, m) => sum + m.totalTransformations, 0),
270
325
  sourcesRead,
326
+ ...markOutput,
271
327
  aggregatedMetrics,
272
328
  suggestions,
273
329
  sessionMetrics: sessionDetails,
274
330
  };
275
- return { ...output, summary: describeParserPerformance(output) };
331
+ return {
332
+ ...output,
333
+ deprecated: true,
334
+ message: DEPRECATION_MESSAGE,
335
+ summary: describeParserPerformance(output),
336
+ };
276
337
  }
277
338
  /**
278
339
  * Aggregate metrics from multiple sessions
@@ -110,10 +110,15 @@ export interface AnalyzeProjectResult {
110
110
  * Counts of the run.
111
111
  */
112
112
  counts: {
113
- /** Files in the project. */
113
+ /**
114
+ * TypeScript files eligible for analysis (`.ts` and `.tsx` outside
115
+ * `node_modules` and `dist`, without spec and test files).
116
+ */
114
117
  totalFiles: number;
115
118
  /** Files analyzed by the rules. */
116
119
  analyzedFiles: number;
120
+ /** `true` when the `maxFiles` cap left files out of the analysis. */
121
+ truncated: boolean;
117
122
  /** Number of analyzer rules run. */
118
123
  rulesExecuted: number;
119
124
  /** Duration of the run in milliseconds. */
@@ -199,6 +204,8 @@ export interface AnalyzeProjectResult {
199
204
  };
200
205
  /** Set when the client cancelled the analysis; counts cover the analyzed files. */
201
206
  execution?: CancelledExecution;
207
+ /** Program files that could not be read and were left out of the analysis. */
208
+ warnings?: string[];
202
209
  }
203
210
  /**
204
211
  * MCP tool `analyze-project`: detects the framework (Angular CLI, Nx),
@@ -236,6 +243,12 @@ export declare class AnalyzeProjectTool implements MCPTool {
236
243
  description: string;
237
244
  default: number;
238
245
  };
246
+ maxFiles: {
247
+ type: string;
248
+ minimum: number;
249
+ description: string;
250
+ default: number;
251
+ };
239
252
  maxResults: {
240
253
  type: string;
241
254
  description: string;
@@ -326,6 +339,16 @@ export declare class AnalyzeProjectTool implements MCPTool {
326
339
  readonly outputSchema: {
327
340
  type: string;
328
341
  properties: {
342
+ summary: {
343
+ type: string;
344
+ };
345
+ warnings: {
346
+ readonly type: "array";
347
+ readonly items: {
348
+ readonly type: "string";
349
+ };
350
+ readonly description: "Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.";
351
+ };
329
352
  framework: {
330
353
  type: string;
331
354
  properties: {
@@ -491,6 +514,9 @@ export declare class AnalyzeProjectTool implements MCPTool {
491
514
  analyzedFiles: {
492
515
  type: string;
493
516
  };
517
+ truncated: {
518
+ type: string;
519
+ };
494
520
  rulesExecuted: {
495
521
  type: string;
496
522
  };
@@ -554,6 +580,9 @@ export declare class AnalyzeProjectTool implements MCPTool {
554
580
  readonly skippedFiles: {
555
581
  readonly type: "integer";
556
582
  };
583
+ readonly scopeFiles: {
584
+ readonly type: "integer";
585
+ };
557
586
  readonly ruleTimings: {
558
587
  readonly type: "array";
559
588
  readonly items: {
@@ -569,9 +598,6 @@ export declare class AnalyzeProjectTool implements MCPTool {
569
598
  progress: {
570
599
  type: string;
571
600
  };
572
- summary: {
573
- type: string;
574
- };
575
601
  };
576
602
  required: string[];
577
603
  };
@@ -601,8 +627,11 @@ export declare class AnalyzeProjectTool implements MCPTool {
601
627
  */
602
628
  private analyzeTsconfigPaths;
603
629
  /**
604
- * Load configuration from .angular-modernizer.json file.
605
- * Only loads from the provided root path to avoid cache directory issues.
630
+ * Settings of `tools.analyze-project` from the project's
631
+ * `.angular-modernizer.json` (only from the given root, never from the
632
+ * server's working directory). Only {@link CONFIG_KEYS} are taken; the
633
+ * config used to be read from a top-level `analyze-project` key, which the
634
+ * schema does not allow, so no setting ever applied.
606
635
  */
607
636
  private loadConfig;
608
637
  }
@@ -1,6 +1,6 @@
1
1
  import { findTsConfig } from './helpers/find-ts-config.js';
2
2
  import { toParallelOptions } from '../types.js';
3
- import { Kernel } from '@angular-modernizer/core';
3
+ import { Kernel, loadConfig, unreadableFilesWarning } from '@angular-modernizer/core';
4
4
  import { AnalyzerPlugin } from '@angular-modernizer/plugin-analyzer';
5
5
  import { getWorkerScriptPath } from '@angular-modernizer/worker';
6
6
  import { getMCPWatcher } from '../mcp-watcher.js';
@@ -8,9 +8,10 @@ import { glob } from 'glob';
8
8
  import { resolve, extname } from 'node:path';
9
9
  import { readFileSync, existsSync } from 'node:fs';
10
10
  import { PAGINATION_SCHEMA, SCAN_EXECUTION_SCHEMA, nameList, pageNote, } from './helpers/analysis-output.js';
11
- import { cancelledExecution, fileProgressMessage, forwardKernelProgress, } from './helpers/tool-context.js';
11
+ import { cancelledExecution, fileProgressMessage, finalFileProgress, forwardKernelProgress, } from './helpers/tool-context.js';
12
12
  import { runScan } from '../scan-host/scan-host.js';
13
13
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
14
+ import { WARNINGS_OUTPUT_SCHEMA, withWarnings } from './helpers/output-contract.js';
14
15
  /** Application or library entry of `framework.projects`. */
15
16
  const NAMED_PROJECT_SCHEMA = {
16
17
  type: 'object',
@@ -21,12 +22,64 @@ const NAMED_PROJECT_SCHEMA = {
21
22
  },
22
23
  required: ['name', 'root'],
23
24
  };
25
+ /** Keys of `tools.analyze-project` taken from the config. */
26
+ const CONFIG_KEYS = [
27
+ 'includeDetails',
28
+ 'maxDepth',
29
+ 'excludePatterns',
30
+ 'maxFiles',
31
+ 'maxResults',
32
+ 'resultOffset',
33
+ ];
24
34
  /** Layers, projects and stack entries named in the summary. */
25
35
  const SUMMARY_NAMES = 10;
26
36
  /**
27
37
  * Text summary of an analysis: framework, architecture, projects, stack,
28
38
  * counts and the returned page of rule findings.
29
39
  */
40
+ /** Files the sequential analysis takes when `maxFiles` is not set. */
41
+ const DEFAULT_MAX_FILES = 50;
42
+ /**
43
+ * `maxFiles` of the call or the config. The call argument is checked by the
44
+ * input schema; a config value is read as plain JSON, so it is checked here.
45
+ */
46
+ function parseMaxFiles(value) {
47
+ if (value === undefined) {
48
+ return DEFAULT_MAX_FILES;
49
+ }
50
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
51
+ throw new Error(`maxFiles must be an integer of at least 1, got ${JSON.stringify(value)}`);
52
+ }
53
+ return value;
54
+ }
55
+ /** Category of the analyzer rules whose findings describe the whole project. */
56
+ const PROJECT_FACT_CATEGORY = 'project-analysis';
57
+ /** Ids of the analyzer rules that report a fact about the project. */
58
+ function projectFactRuleIds() {
59
+ return new Set(new AnalyzerPlugin()
60
+ .getAnalysisRules()
61
+ .filter((rule) => rule.category === PROJECT_FACT_CATEGORY)
62
+ .map((rule) => rule.id));
63
+ }
64
+ /**
65
+ * Keeps the first finding of each project fact. The rules run per file and
66
+ * report the same fact (rule, message, metadata) for every analyzed file;
67
+ * findings of other rules stay as they are.
68
+ */
69
+ function collapseProjectFacts(results, factRuleIds) {
70
+ const seen = new Set();
71
+ return results.filter((result) => {
72
+ if (!factRuleIds.has(result.ruleId)) {
73
+ return true;
74
+ }
75
+ const key = JSON.stringify([result.ruleId, result.message, result.metadata ?? null]);
76
+ if (seen.has(key)) {
77
+ return false;
78
+ }
79
+ seen.add(key);
80
+ return true;
81
+ });
82
+ }
30
83
  function describeAnalysis(analysis, totalResults) {
31
84
  const { framework, architecture, technologyStack, counts } = analysis;
32
85
  const lines = [
@@ -51,6 +104,10 @@ function describeAnalysis(analysis, totalResults) {
51
104
  (analysis.pagination === undefined && totalResults > 0
52
105
  ? '; includeDetails returns them.'
53
106
  : '.'));
107
+ if (analysis.fileCap !== undefined) {
108
+ lines.push(`maxFiles ${analysis.fileCap.maxFiles} left ${analysis.fileCap.skippedFiles} file(s) out; ` +
109
+ 'raise maxFiles to analyze them.');
110
+ }
54
111
  const page = pageNote(analysis.pagination, 'findings');
55
112
  if (page !== undefined) {
56
113
  lines.push(page);
@@ -79,6 +136,8 @@ export class AnalyzeProjectTool {
79
136
  openWorldHint: false,
80
137
  };
81
138
  description = 'Analyze Angular projects to detect framework, architecture, layers, and technologies. ' +
139
+ `The rules analyze at most maxFiles TypeScript files in path order (default ${DEFAULT_MAX_FILES}); ` +
140
+ 'counts.truncated says whether files were left out. ' +
82
141
  'counts holds the file and rule numbers, summary a short text; includeDetails returns the rule findings ' +
83
142
  '(maxResults and resultOffset page them).';
84
143
  /**
@@ -103,6 +162,13 @@ export class AnalyzeProjectTool {
103
162
  description: 'Maximum depth for analysis',
104
163
  default: 3,
105
164
  },
165
+ maxFiles: {
166
+ type: 'integer',
167
+ minimum: 1,
168
+ description: `Maximum number of TypeScript files the rules analyze, taken in path order (default ${DEFAULT_MAX_FILES}). ` +
169
+ 'When files are left out, counts.truncated is true and the summary says how many.',
170
+ default: DEFAULT_MAX_FILES,
171
+ },
106
172
  maxResults: {
107
173
  type: 'number',
108
174
  description: 'Maximum number of results to return (pagination)',
@@ -115,11 +181,11 @@ export class AnalyzeProjectTool {
115
181
  },
116
182
  orchestration: {
117
183
  type: 'object',
118
- 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.',
184
+ description: 'Deprecated, kept in 2.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.',
119
185
  properties: {
120
186
  parallel: {
121
187
  type: 'boolean',
122
- description: 'Deprecated: runs the old WorkerPool path over the whole program instead of 50 files. Leave unset.',
188
+ description: 'Deprecated: runs the old WorkerPool path over the whole program instead of maxFiles files. Leave unset.',
123
189
  default: false,
124
190
  },
125
191
  incremental: {
@@ -265,10 +331,11 @@ export class AnalyzeProjectTool {
265
331
  properties: {
266
332
  totalFiles: { type: 'integer' },
267
333
  analyzedFiles: { type: 'integer' },
334
+ truncated: { type: 'boolean' },
268
335
  rulesExecuted: { type: 'integer' },
269
336
  duration: { type: 'number' },
270
337
  },
271
- required: ['totalFiles', 'analyzedFiles', 'rulesExecuted', 'duration'],
338
+ required: ['totalFiles', 'analyzedFiles', 'truncated', 'rulesExecuted', 'duration'],
272
339
  },
273
340
  metadata: {
274
341
  type: 'object',
@@ -284,6 +351,7 @@ export class AnalyzeProjectTool {
284
351
  orchestration: { type: 'object' },
285
352
  execution: SCAN_EXECUTION_SCHEMA,
286
353
  progress: { type: 'object' },
354
+ ...WARNINGS_OUTPUT_SCHEMA,
287
355
  summary: { type: 'string' },
288
356
  },
289
357
  required: [
@@ -335,13 +403,19 @@ export class AnalyzeProjectTool {
335
403
  }
336
404
  const projectStructure = await this.analyzeProjectStructure(mergedParams.rootPath, mergedParams.excludePatterns);
337
405
  const technologyStack = this.detectTechnologyStack(mergedParams.rootPath);
406
+ // TypeScript files eligible for analysis: totalFiles counts them, the
407
+ // sequential path takes the first maxFiles of them
408
+ const tsFiles = await this.findTypeScriptFiles(mergedParams.rootPath, mergedParams.maxDepth ?? 3);
338
409
  if (opId) {
339
- watcher?.updateOperation(opId, 'structure-complete', `Found ${projectStructure.totalFiles} files`);
410
+ watcher?.updateOperation(opId, 'structure-complete', `Found ${tsFiles.length} TypeScript files`);
340
411
  }
341
412
  // Run analysis using full Phase 6d/7b orchestration
342
413
  let results = [];
343
414
  let filesAnalyzed = 0;
344
415
  let execution;
416
+ const warnings = [];
417
+ let fileCap;
418
+ const maxFiles = parseMaxFiles(mergedParams.maxFiles);
345
419
  let lastProgress;
346
420
  // The parallel and incremental paths run the kernel here (it starts its
347
421
  // own analysis workers); the sequential path runs in a scan worker.
@@ -364,6 +438,10 @@ export class AnalyzeProjectTool {
364
438
  },
365
439
  });
366
440
  await kernel.initialize();
441
+ const kernelWarning = unreadableFilesWarning(kernel.getUnreadableFiles());
442
+ if (kernelWarning !== undefined) {
443
+ warnings.push(kernelWarning);
444
+ }
367
445
  if (opId) {
368
446
  watcher?.updateOperation(opId, 'kernel-ready', 'Kernel initialized successfully');
369
447
  }
@@ -400,6 +478,8 @@ export class AnalyzeProjectTool {
400
478
  'analyzer',
401
479
  '@angular-modernizer/plugin-analyzer',
402
480
  ],
481
+ // rules['<id>'] options and suppressionComments for every rule
482
+ rulesConfig: (loadConfig(mergedParams.rootPath).rules ?? {}),
403
483
  };
404
484
  if (orchestration.incremental) {
405
485
  const incrementalResult = await kernel.analyzeIncremental({
@@ -441,13 +521,15 @@ export class AnalyzeProjectTool {
441
521
  if (opId) {
442
522
  watcher?.updateOperation(opId, 'starting-sequential', 'Running sequential analysis');
443
523
  }
444
- const tsFiles = await this.findTypeScriptFiles(mergedParams.rootPath, mergedParams.maxDepth ?? 3);
445
524
  if (opId) {
446
525
  watcher?.updateOperation(opId, 'scanning-files', `Found ${tsFiles.length} files to analyze`);
447
526
  }
448
527
  // Kernel (the whole tsconfig program) and rules run in a scan worker,
449
528
  // so the server keeps reading stdin while the program is built
450
- const sequentialFiles = tsFiles.slice(0, 50);
529
+ const sequentialFiles = tsFiles.slice(0, maxFiles);
530
+ if (sequentialFiles.length < tsFiles.length) {
531
+ fileCap = { maxFiles, skippedFiles: tsFiles.length - sequentialFiles.length };
532
+ }
451
533
  let done = 0;
452
534
  ctx.progress?.(0, sequentialFiles.length, fileProgressMessage(0, sequentialFiles.length, 0));
453
535
  const engine = await runScan({
@@ -476,15 +558,25 @@ export class AnalyzeProjectTool {
476
558
  },
477
559
  }, { signal: ctx.signal });
478
560
  rulesExecuted = engine.ruleIds.length;
561
+ const unreadableWarning = unreadableFilesWarning(engine.unreadableFiles ?? []);
562
+ if (unreadableWarning !== undefined) {
563
+ warnings.push(unreadableWarning);
564
+ }
479
565
  if (engine.cancelled) {
480
566
  execution = cancelledExecution(done, sequentialFiles.length - done);
481
567
  }
482
- filesAnalyzed =
483
- sequentialFiles.length - (execution?.skippedFiles ?? 0);
568
+ else {
569
+ // the loop sent 0 first, then each analyzed count
570
+ finalFileProgress(ctx.progress, sequentialFiles.length, done, results.length, done);
571
+ }
572
+ // Files reported by the engine; one it could not load is not analyzed
573
+ filesAnalyzed = done;
484
574
  if (opId) {
485
575
  watcher?.updateOperation(opId, 'sequential-complete', `Analyzed ${filesAnalyzed} files sequentially`);
486
576
  }
487
577
  }
578
+ // The analyzer rules run per file; a project fact counts once
579
+ results = collapseProjectFacts(results, projectFactRuleIds());
488
580
  // Determine framework from results
489
581
  const framework = this.determineFramework(results, projectStructure);
490
582
  // Determine architecture pattern
@@ -518,11 +610,11 @@ export class AnalyzeProjectTool {
518
610
  }
519
611
  // Apply pagination to results if includeDetails is true
520
612
  const totalResults = results.length;
521
- const maxResults = params.maxResults ?? 1000;
522
- const resultOffset = params.resultOffset ?? 0;
613
+ const maxResults = mergedParams.maxResults ?? 1000;
614
+ const resultOffset = mergedParams.resultOffset ?? 0;
523
615
  let paginatedResults = results;
524
616
  let paginationMetadata;
525
- if (params.includeDetails) {
617
+ if (mergedParams.includeDetails) {
526
618
  // Slice results for pagination
527
619
  paginatedResults = results.slice(resultOffset, resultOffset + maxResults);
528
620
  // Add pagination metadata
@@ -537,10 +629,11 @@ export class AnalyzeProjectTool {
537
629
  framework,
538
630
  architecture,
539
631
  technologyStack,
540
- results: params.includeDetails ? paginatedResults : [],
632
+ results: mergedParams.includeDetails ? paginatedResults : [],
541
633
  counts: {
542
- totalFiles: projectStructure.totalFiles,
634
+ totalFiles: tsFiles.length,
543
635
  analyzedFiles: filesAnalyzed,
636
+ truncated: fileCap !== undefined,
544
637
  rulesExecuted,
545
638
  duration,
546
639
  },
@@ -555,10 +648,10 @@ export class AnalyzeProjectTool {
555
648
  progress: lastProgress,
556
649
  ...(execution === undefined ? {} : { execution }),
557
650
  };
558
- const result = {
651
+ const result = withWarnings({
559
652
  ...analysis,
560
- summary: describeAnalysis(analysis, totalResults),
561
- };
653
+ summary: describeAnalysis({ ...analysis, fileCap }, totalResults),
654
+ }, warnings);
562
655
  // Mark operation as completed successfully
563
656
  if (opId) {
564
657
  const message = paginationMetadata
@@ -717,7 +810,6 @@ export class AnalyzeProjectTool {
717
810
  }
718
811
  }
719
812
  return {
720
- totalFiles: allFiles.length,
721
813
  directories,
722
814
  packageJsonPath,
723
815
  angularJsonPath,
@@ -1101,31 +1193,44 @@ export class AnalyzeProjectTool {
1101
1193
  return layers;
1102
1194
  }
1103
1195
  /**
1104
- * Load configuration from .angular-modernizer.json file.
1105
- * Only loads from the provided root path to avoid cache directory issues.
1196
+ * Settings of `tools.analyze-project` from the project's
1197
+ * `.angular-modernizer.json` (only from the given root, never from the
1198
+ * server's working directory). Only {@link CONFIG_KEYS} are taken; the
1199
+ * config used to be read from a top-level `analyze-project` key, which the
1200
+ * schema does not allow, so no setting ever applied.
1106
1201
  */
1107
1202
  loadConfig(providedRootPath) {
1108
- // Only load config if rootPath is explicitly provided
1109
- // This prevents accidentally using process.cwd() which may point to the MCP server directory
1110
1203
  if (!providedRootPath) {
1111
1204
  return {};
1112
1205
  }
1113
1206
  const configPath = resolve(providedRootPath, '.angular-modernizer.json');
1114
- if (existsSync(configPath)) {
1115
- try {
1116
- // Disable no-unsafe-assignment: JSON.parse() returns 'any' but config structure is validated below
1117
- const config = JSON.parse(readFileSync(configPath, 'utf-8')); // eslint-disable-line @typescript-eslint/no-unsafe-assignment
1118
- // Disable no-unsafe-member-access and no-unsafe-assignment: config is parsed from JSON and may be any, but we validate it below (line 1315)
1119
- const analyzeProjectConfig = config['analyze-project']; // eslint-disable-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
1120
- if (analyzeProjectConfig && typeof analyzeProjectConfig === 'object') {
1121
- return analyzeProjectConfig;
1122
- }
1123
- }
1124
- catch (error) {
1125
- console.warn(`Error loading config from ${configPath}:`, error);
1207
+ if (!existsSync(configPath)) {
1208
+ return {};
1209
+ }
1210
+ try {
1211
+ const config = JSON.parse(readFileSync(configPath, 'utf-8'));
1212
+ const section = toolSection(config, 'analyze-project');
1213
+ if (section === undefined) {
1214
+ return {};
1126
1215
  }
1216
+ return Object.fromEntries(CONFIG_KEYS.filter((key) => section[key] !== undefined).map((key) => [
1217
+ key,
1218
+ section[key],
1219
+ ]));
1220
+ }
1221
+ catch (error) {
1222
+ console.warn(`Error loading config from ${configPath}:`, error);
1223
+ return {};
1127
1224
  }
1128
- return {};
1129
1225
  }
1130
1226
  }
1227
+ /** `tools.<name>` of a parsed config, when it is an object. */
1228
+ function toolSection(config, name) {
1229
+ const tools = isRecord(config) ? config['tools'] : undefined;
1230
+ const section = isRecord(tools) ? tools[name] : undefined;
1231
+ return isRecord(section) ? section : undefined;
1232
+ }
1233
+ function isRecord(value) {
1234
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1235
+ }
1131
1236
  //# sourceMappingURL=analyze-project.js.map