@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
@@ -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
@@ -1,5 +1,6 @@
1
1
  import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
2
2
  import { type CancelledExecution } from './helpers/tool-context.js';
3
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
3
4
  /**
4
5
  * Result from the analyze-project tool.
5
6
  */
@@ -110,10 +111,15 @@ export interface AnalyzeProjectResult {
110
111
  * Counts of the run.
111
112
  */
112
113
  counts: {
113
- /** Files in the project. */
114
+ /**
115
+ * TypeScript files eligible for analysis (`.ts` and `.tsx` outside
116
+ * `node_modules` and `dist`, without spec and test files).
117
+ */
114
118
  totalFiles: number;
115
119
  /** Files analyzed by the rules. */
116
120
  analyzedFiles: number;
121
+ /** `true` when the `maxFiles` cap left files out of the analysis. */
122
+ truncated: boolean;
117
123
  /** Number of analyzer rules run. */
118
124
  rulesExecuted: number;
119
125
  /** Duration of the run in milliseconds. */
@@ -199,6 +205,13 @@ export interface AnalyzeProjectResult {
199
205
  };
200
206
  /** Set when the client cancelled the analysis; counts cover the analyzed files. */
201
207
  execution?: CancelledExecution;
208
+ /**
209
+ * Program files that could not be read and were left out of the analysis,
210
+ * and library imports that do not resolve.
211
+ */
212
+ warnings?: string[];
213
+ /** Library imports of the analyzed files that do not resolve (sequential path); absent when all resolve. */
214
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
202
215
  }
203
216
  /**
204
217
  * MCP tool `analyze-project`: detects the framework (Angular CLI, Nx),
@@ -236,6 +249,12 @@ export declare class AnalyzeProjectTool implements MCPTool {
236
249
  description: string;
237
250
  default: number;
238
251
  };
252
+ maxFiles: {
253
+ type: string;
254
+ minimum: number;
255
+ description: string;
256
+ default: number;
257
+ };
239
258
  maxResults: {
240
259
  type: string;
241
260
  description: string;
@@ -326,6 +345,35 @@ export declare class AnalyzeProjectTool implements MCPTool {
326
345
  readonly outputSchema: {
327
346
  type: string;
328
347
  properties: {
348
+ summary: {
349
+ type: string;
350
+ };
351
+ unresolvedLibraryImports: {
352
+ readonly type: "object";
353
+ readonly description: "Library imports of the scanned files that do not resolve (node_modules missing or incomplete); rules that need library types can report less. Absent when all resolve.";
354
+ readonly properties: {
355
+ readonly imports: {
356
+ readonly type: "integer";
357
+ };
358
+ readonly packages: {
359
+ readonly type: "integer";
360
+ };
361
+ readonly examples: {
362
+ readonly type: "array";
363
+ readonly items: {
364
+ readonly type: "string";
365
+ };
366
+ };
367
+ };
368
+ readonly required: readonly ["imports", "packages", "examples"];
369
+ };
370
+ warnings: {
371
+ readonly type: "array";
372
+ readonly items: {
373
+ readonly type: "string";
374
+ };
375
+ readonly description: "Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.";
376
+ };
329
377
  framework: {
330
378
  type: string;
331
379
  properties: {
@@ -491,6 +539,9 @@ export declare class AnalyzeProjectTool implements MCPTool {
491
539
  analyzedFiles: {
492
540
  type: string;
493
541
  };
542
+ truncated: {
543
+ type: string;
544
+ };
494
545
  rulesExecuted: {
495
546
  type: string;
496
547
  };
@@ -554,6 +605,9 @@ export declare class AnalyzeProjectTool implements MCPTool {
554
605
  readonly skippedFiles: {
555
606
  readonly type: "integer";
556
607
  };
608
+ readonly scopeFiles: {
609
+ readonly type: "integer";
610
+ };
557
611
  readonly ruleTimings: {
558
612
  readonly type: "array";
559
613
  readonly items: {
@@ -569,9 +623,6 @@ export declare class AnalyzeProjectTool implements MCPTool {
569
623
  progress: {
570
624
  type: string;
571
625
  };
572
- summary: {
573
- type: string;
574
- };
575
626
  };
576
627
  required: string[];
577
628
  };
@@ -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,11 @@ 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 { UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA, WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
15
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
14
16
  /** Application or library entry of `framework.projects`. */
15
17
  const NAMED_PROJECT_SCHEMA = {
16
18
  type: 'object',
@@ -26,6 +28,7 @@ const CONFIG_KEYS = [
26
28
  'includeDetails',
27
29
  'maxDepth',
28
30
  'excludePatterns',
31
+ 'maxFiles',
29
32
  'maxResults',
30
33
  'resultOffset',
31
34
  ];
@@ -35,6 +38,49 @@ const SUMMARY_NAMES = 10;
35
38
  * Text summary of an analysis: framework, architecture, projects, stack,
36
39
  * counts and the returned page of rule findings.
37
40
  */
41
+ /** Files the sequential analysis takes when `maxFiles` is not set. */
42
+ const DEFAULT_MAX_FILES = 50;
43
+ /**
44
+ * `maxFiles` of the call or the config. The call argument is checked by the
45
+ * input schema; a config value is read as plain JSON, so it is checked here.
46
+ */
47
+ function parseMaxFiles(value) {
48
+ if (value === undefined) {
49
+ return DEFAULT_MAX_FILES;
50
+ }
51
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
52
+ throw new Error(`maxFiles must be an integer of at least 1, got ${JSON.stringify(value)}`);
53
+ }
54
+ return value;
55
+ }
56
+ /** Category of the analyzer rules whose findings describe the whole project. */
57
+ const PROJECT_FACT_CATEGORY = 'project-analysis';
58
+ /** Ids of the analyzer rules that report a fact about the project. */
59
+ function projectFactRuleIds() {
60
+ return new Set(new AnalyzerPlugin()
61
+ .getAnalysisRules()
62
+ .filter((rule) => rule.category === PROJECT_FACT_CATEGORY)
63
+ .map((rule) => rule.id));
64
+ }
65
+ /**
66
+ * Keeps the first finding of each project fact. The rules run per file and
67
+ * report the same fact (rule, message, metadata) for every analyzed file;
68
+ * findings of other rules stay as they are.
69
+ */
70
+ function collapseProjectFacts(results, factRuleIds) {
71
+ const seen = new Set();
72
+ return results.filter((result) => {
73
+ if (!factRuleIds.has(result.ruleId)) {
74
+ return true;
75
+ }
76
+ const key = JSON.stringify([result.ruleId, result.message, result.metadata ?? null]);
77
+ if (seen.has(key)) {
78
+ return false;
79
+ }
80
+ seen.add(key);
81
+ return true;
82
+ });
83
+ }
38
84
  function describeAnalysis(analysis, totalResults) {
39
85
  const { framework, architecture, technologyStack, counts } = analysis;
40
86
  const lines = [
@@ -59,6 +105,10 @@ function describeAnalysis(analysis, totalResults) {
59
105
  (analysis.pagination === undefined && totalResults > 0
60
106
  ? '; includeDetails returns them.'
61
107
  : '.'));
108
+ if (analysis.fileCap !== undefined) {
109
+ lines.push(`maxFiles ${analysis.fileCap.maxFiles} left ${analysis.fileCap.skippedFiles} file(s) out; ` +
110
+ 'raise maxFiles to analyze them.');
111
+ }
62
112
  const page = pageNote(analysis.pagination, 'findings');
63
113
  if (page !== undefined) {
64
114
  lines.push(page);
@@ -87,6 +137,8 @@ export class AnalyzeProjectTool {
87
137
  openWorldHint: false,
88
138
  };
89
139
  description = 'Analyze Angular projects to detect framework, architecture, layers, and technologies. ' +
140
+ `The rules analyze at most maxFiles TypeScript files in path order (default ${DEFAULT_MAX_FILES}); ` +
141
+ 'counts.truncated says whether files were left out. ' +
90
142
  'counts holds the file and rule numbers, summary a short text; includeDetails returns the rule findings ' +
91
143
  '(maxResults and resultOffset page them).';
92
144
  /**
@@ -111,6 +163,13 @@ export class AnalyzeProjectTool {
111
163
  description: 'Maximum depth for analysis',
112
164
  default: 3,
113
165
  },
166
+ maxFiles: {
167
+ type: 'integer',
168
+ minimum: 1,
169
+ description: `Maximum number of TypeScript files the rules analyze, taken in path order (default ${DEFAULT_MAX_FILES}). ` +
170
+ 'When files are left out, counts.truncated is true and the summary says how many.',
171
+ default: DEFAULT_MAX_FILES,
172
+ },
114
173
  maxResults: {
115
174
  type: 'number',
116
175
  description: 'Maximum number of results to return (pagination)',
@@ -123,11 +182,11 @@ export class AnalyzeProjectTool {
123
182
  },
124
183
  orchestration: {
125
184
  type: 'object',
126
- 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.',
185
+ 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.',
127
186
  properties: {
128
187
  parallel: {
129
188
  type: 'boolean',
130
- description: 'Deprecated: runs the old WorkerPool path over the whole program instead of 50 files. Leave unset.',
189
+ description: 'Deprecated: runs the old WorkerPool path over the whole program instead of maxFiles files. Leave unset.',
131
190
  default: false,
132
191
  },
133
192
  incremental: {
@@ -273,10 +332,11 @@ export class AnalyzeProjectTool {
273
332
  properties: {
274
333
  totalFiles: { type: 'integer' },
275
334
  analyzedFiles: { type: 'integer' },
335
+ truncated: { type: 'boolean' },
276
336
  rulesExecuted: { type: 'integer' },
277
337
  duration: { type: 'number' },
278
338
  },
279
- required: ['totalFiles', 'analyzedFiles', 'rulesExecuted', 'duration'],
339
+ required: ['totalFiles', 'analyzedFiles', 'truncated', 'rulesExecuted', 'duration'],
280
340
  },
281
341
  metadata: {
282
342
  type: 'object',
@@ -292,6 +352,8 @@ export class AnalyzeProjectTool {
292
352
  orchestration: { type: 'object' },
293
353
  execution: SCAN_EXECUTION_SCHEMA,
294
354
  progress: { type: 'object' },
355
+ ...WARNINGS_OUTPUT_SCHEMA,
356
+ ...UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA,
295
357
  summary: { type: 'string' },
296
358
  },
297
359
  required: [
@@ -343,13 +405,20 @@ export class AnalyzeProjectTool {
343
405
  }
344
406
  const projectStructure = await this.analyzeProjectStructure(mergedParams.rootPath, mergedParams.excludePatterns);
345
407
  const technologyStack = this.detectTechnologyStack(mergedParams.rootPath);
408
+ // TypeScript files eligible for analysis: totalFiles counts them, the
409
+ // sequential path takes the first maxFiles of them
410
+ const tsFiles = await this.findTypeScriptFiles(mergedParams.rootPath, mergedParams.maxDepth ?? 3);
346
411
  if (opId) {
347
- watcher?.updateOperation(opId, 'structure-complete', `Found ${projectStructure.totalFiles} files`);
412
+ watcher?.updateOperation(opId, 'structure-complete', `Found ${tsFiles.length} TypeScript files`);
348
413
  }
349
414
  // Run analysis using full Phase 6d/7b orchestration
350
415
  let results = [];
351
416
  let filesAnalyzed = 0;
352
417
  let execution;
418
+ const warnings = [];
419
+ let unresolvedLibraryImports;
420
+ let fileCap;
421
+ const maxFiles = parseMaxFiles(mergedParams.maxFiles);
353
422
  let lastProgress;
354
423
  // The parallel and incremental paths run the kernel here (it starts its
355
424
  // own analysis workers); the sequential path runs in a scan worker.
@@ -372,6 +441,10 @@ export class AnalyzeProjectTool {
372
441
  },
373
442
  });
374
443
  await kernel.initialize();
444
+ const kernelWarning = unreadableFilesWarning(kernel.getUnreadableFiles());
445
+ if (kernelWarning !== undefined) {
446
+ warnings.push(kernelWarning);
447
+ }
375
448
  if (opId) {
376
449
  watcher?.updateOperation(opId, 'kernel-ready', 'Kernel initialized successfully');
377
450
  }
@@ -408,6 +481,8 @@ export class AnalyzeProjectTool {
408
481
  'analyzer',
409
482
  '@angular-modernizer/plugin-analyzer',
410
483
  ],
484
+ // rules['<id>'] options and suppressionComments for every rule
485
+ rulesConfig: (loadConfig(mergedParams.rootPath).rules ?? {}),
411
486
  };
412
487
  if (orchestration.incremental) {
413
488
  const incrementalResult = await kernel.analyzeIncremental({
@@ -449,13 +524,15 @@ export class AnalyzeProjectTool {
449
524
  if (opId) {
450
525
  watcher?.updateOperation(opId, 'starting-sequential', 'Running sequential analysis');
451
526
  }
452
- const tsFiles = await this.findTypeScriptFiles(mergedParams.rootPath, mergedParams.maxDepth ?? 3);
453
527
  if (opId) {
454
528
  watcher?.updateOperation(opId, 'scanning-files', `Found ${tsFiles.length} files to analyze`);
455
529
  }
456
530
  // Kernel (the whole tsconfig program) and rules run in a scan worker,
457
531
  // so the server keeps reading stdin while the program is built
458
- const sequentialFiles = tsFiles.slice(0, 50);
532
+ const sequentialFiles = tsFiles.slice(0, maxFiles);
533
+ if (sequentialFiles.length < tsFiles.length) {
534
+ fileCap = { maxFiles, skippedFiles: tsFiles.length - sequentialFiles.length };
535
+ }
459
536
  let done = 0;
460
537
  ctx.progress?.(0, sequentialFiles.length, fileProgressMessage(0, sequentialFiles.length, 0));
461
538
  const engine = await runScan({
@@ -465,6 +542,7 @@ export class AnalyzeProjectTool {
465
542
  rootPath: mergedParams.rootPath,
466
543
  files: sequentialFiles,
467
544
  mode: 'sequential',
545
+ libraryImports: true,
468
546
  }, {
469
547
  file: (event) => {
470
548
  for (const finding of event.findings) {
@@ -484,15 +562,26 @@ export class AnalyzeProjectTool {
484
562
  },
485
563
  }, { signal: ctx.signal });
486
564
  rulesExecuted = engine.ruleIds.length;
565
+ const unreadableWarning = unreadableFilesWarning(engine.unreadableFiles ?? []);
566
+ if (unreadableWarning !== undefined) {
567
+ warnings.push(unreadableWarning);
568
+ }
569
+ unresolvedLibraryImports = engine.unresolvedLibraryImports;
487
570
  if (engine.cancelled) {
488
571
  execution = cancelledExecution(done, sequentialFiles.length - done);
489
572
  }
490
- filesAnalyzed =
491
- sequentialFiles.length - (execution?.skippedFiles ?? 0);
573
+ else {
574
+ // the loop sent 0 first, then each analyzed count
575
+ finalFileProgress(ctx.progress, sequentialFiles.length, done, results.length, done);
576
+ }
577
+ // Files reported by the engine; one it could not load is not analyzed
578
+ filesAnalyzed = done;
492
579
  if (opId) {
493
580
  watcher?.updateOperation(opId, 'sequential-complete', `Analyzed ${filesAnalyzed} files sequentially`);
494
581
  }
495
582
  }
583
+ // The analyzer rules run per file; a project fact counts once
584
+ results = collapseProjectFacts(results, projectFactRuleIds());
496
585
  // Determine framework from results
497
586
  const framework = this.determineFramework(results, projectStructure);
498
587
  // Determine architecture pattern
@@ -547,8 +636,9 @@ export class AnalyzeProjectTool {
547
636
  technologyStack,
548
637
  results: mergedParams.includeDetails ? paginatedResults : [],
549
638
  counts: {
550
- totalFiles: projectStructure.totalFiles,
639
+ totalFiles: tsFiles.length,
551
640
  analyzedFiles: filesAnalyzed,
641
+ truncated: fileCap !== undefined,
552
642
  rulesExecuted,
553
643
  duration,
554
644
  },
@@ -563,10 +653,10 @@ export class AnalyzeProjectTool {
563
653
  progress: lastProgress,
564
654
  ...(execution === undefined ? {} : { execution }),
565
655
  };
566
- const result = {
656
+ const result = withLibraryImportWarning(withWarnings({
567
657
  ...analysis,
568
- summary: describeAnalysis(analysis, totalResults),
569
- };
658
+ summary: describeAnalysis({ ...analysis, fileCap }, totalResults),
659
+ }, warnings), unresolvedLibraryImports);
570
660
  // Mark operation as completed successfully
571
661
  if (opId) {
572
662
  const message = paginationMetadata
@@ -725,7 +815,6 @@ export class AnalyzeProjectTool {
725
815
  }
726
816
  }
727
817
  return {
728
- totalFiles: allFiles.length,
729
818
  directories,
730
819
  packageJsonPath,
731
820
  angularJsonPath,