@angular-modernizer/adapter-mcp 1.2.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 (130) hide show
  1. package/CHANGELOG.md +662 -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 +9 -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 +30 -4
  27. package/dist/tools/analyze-project.js +99 -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/extract-libraries.js +42 -27
  32. package/dist/tools/find-angular-symbol.js +3 -2
  33. package/dist/tools/find-component-hosts.js +3 -2
  34. package/dist/tools/find-usages.js +21 -12
  35. package/dist/tools/get-call-graph.js +15 -2
  36. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  37. package/dist/tools/get-operation-progress-tool.js +2 -2
  38. package/dist/tools/get-operation-progress.d.ts +4 -1
  39. package/dist/tools/get-operation-progress.js +6 -2
  40. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  41. package/dist/tools/helpers/analysis-output.js +22 -1
  42. package/dist/tools/helpers/build-cache.d.ts +27 -0
  43. package/dist/tools/helpers/build-cache.js +86 -0
  44. package/dist/tools/helpers/class-filter.d.ts +18 -0
  45. package/dist/tools/helpers/class-filter.js +30 -0
  46. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  47. package/dist/tools/helpers/cli-arguments.js +35 -0
  48. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  49. package/dist/tools/helpers/feedback-catalog.js +196 -0
  50. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  51. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  52. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  53. package/dist/tools/helpers/file-type-check.js +56 -0
  54. package/dist/tools/helpers/output-contract.d.ts +42 -0
  55. package/dist/tools/helpers/output-contract.js +54 -0
  56. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  57. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  58. package/dist/tools/helpers/project-cache.d.ts +5 -4
  59. package/dist/tools/helpers/project-cache.js +21 -16
  60. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  61. package/dist/tools/helpers/project-decorators.js +13 -6
  62. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  63. package/dist/tools/helpers/refresh-apply.js +460 -0
  64. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  65. package/dist/tools/helpers/refresh-inventory.js +610 -0
  66. package/dist/tools/helpers/rule-runner.js +3 -1
  67. package/dist/tools/helpers/scan-cache.d.ts +74 -5
  68. package/dist/tools/helpers/scan-cache.js +134 -6
  69. package/dist/tools/helpers/scan-engine.d.ts +30 -6
  70. package/dist/tools/helpers/scan-engine.js +131 -22
  71. package/dist/tools/helpers/scan-plan.js +16 -2
  72. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  73. package/dist/tools/helpers/source-map-loader.js +226 -0
  74. package/dist/tools/helpers/template-check.d.ts +76 -0
  75. package/dist/tools/helpers/template-check.js +158 -0
  76. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  77. package/dist/tools/helpers/tool-cache.js +9 -3
  78. package/dist/tools/helpers/tool-context.d.ts +18 -0
  79. package/dist/tools/helpers/tool-context.js +29 -0
  80. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  81. package/dist/tools/helpers/transform-safety.js +357 -4
  82. package/dist/tools/inspect-form-group.js +5 -0
  83. package/dist/tools/inspect-i18n.d.ts +1 -1
  84. package/dist/tools/inspect-template.js +8 -2
  85. package/dist/tools/learn-patterns.d.ts +43 -28
  86. package/dist/tools/learn-patterns.js +83 -161
  87. package/dist/tools/list-imports.d.ts +1 -1
  88. package/dist/tools/orchestrate-migration.d.ts +19 -1
  89. package/dist/tools/orchestrate-migration.js +52 -10
  90. package/dist/tools/parse-stack-trace.d.ts +48 -1
  91. package/dist/tools/parse-stack-trace.js +108 -9
  92. package/dist/tools/plan-migration.js +22 -10
  93. package/dist/tools/refresh-state.d.ts +378 -0
  94. package/dist/tools/refresh-state.js +370 -0
  95. package/dist/tools/resolve-type.js +10 -3
  96. package/dist/tools/review-feedback.d.ts +42 -7
  97. package/dist/tools/review-feedback.js +24 -17
  98. package/dist/tools/rollback-changes.d.ts +5 -0
  99. package/dist/tools/rollback-changes.js +7 -2
  100. package/dist/tools/run-angular-cli.js +36 -22
  101. package/dist/tools/run-build.d.ts +33 -28
  102. package/dist/tools/run-build.js +136 -438
  103. package/dist/tools/run-schematic.d.ts +8 -2
  104. package/dist/tools/run-schematic.js +80 -50
  105. package/dist/tools/scan-all.d.ts +31 -15
  106. package/dist/tools/scan-all.js +75 -109
  107. package/dist/tools/scan-angular.d.ts +27 -14
  108. package/dist/tools/scan-angular.js +70 -92
  109. package/dist/tools/scan-architecture.d.ts +29 -12
  110. package/dist/tools/scan-architecture.js +205 -135
  111. package/dist/tools/scan-solid.d.ts +27 -14
  112. package/dist/tools/scan-solid.js +73 -89
  113. package/dist/tools/search-codebase.d.ts +6 -1
  114. package/dist/tools/search-codebase.js +13 -7
  115. package/dist/tools/suggest-improvements.d.ts +34 -3
  116. package/dist/tools/suggest-improvements.js +34 -9
  117. package/dist/tools/trace-output-flow.js +3 -2
  118. package/dist/tools/transform-code-batch.d.ts +9 -9
  119. package/dist/tools/transform-code.d.ts +161 -12
  120. package/dist/tools/transform-code.js +715 -206
  121. package/dist/tools/validate-before-transform.js +2 -1
  122. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  123. package/dist/tools/validate-project-compatibility.js +33 -225
  124. package/dist/tools/validate-transformation.d.ts +40 -26
  125. package/dist/tools/validate-transformation.js +115 -294
  126. package/dist/tools/verify-citations.js +8 -2
  127. package/dist/types.d.ts +9 -9
  128. package/dist/utils/format-tool-response.d.ts +3 -1
  129. package/dist/utils/format-tool-response.js +8 -3
  130. package/package.json +14 -13
@@ -1,15 +1,18 @@
1
- import { yieldIfCancellable } from './helpers/tool-context.js';
1
+ import { readCancelAfterBlock, yieldIfCancellable } from './helpers/tool-context.js';
2
+ import { TRANSFORMATION_TYPES } from './helpers/feedback-catalog.js';
2
3
  import { findTsConfig } from './helpers/find-ts-config.js';
3
4
  import { createBatchKernel } from './helpers/batch-kernel.js';
4
- import { Kernel, FluentKernel, PreTransformValidator, PostTransformValidator, ValidationSeverity, ValidationType, loadConfig, } from '@angular-modernizer/core';
5
- import { AngularPlugin } from '@angular-modernizer/plugin-angular';
6
- import { readFileSync } from 'node:fs';
7
- import { resolve } from 'node:path';
5
+ import { Kernel, FluentKernel, PreTransformValidator, PostTransformValidator, countLineChanges, ValidationSeverity, ValidationType, loadConfig, } from '@angular-modernizer/core';
6
+ import { AngularPlugin, deprecationMessage } from '@angular-modernizer/plugin-angular';
7
+ import { StandalonePlugin } from '@angular-modernizer/plugin-standalone';
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
8
10
  import { randomUUID } from 'node:crypto';
9
11
  import { executeBatchTransformation, } from './transform-code-batch.js';
10
12
  import { ProgressStore } from '../streaming/progress-store.js';
11
13
  import { getAvailableRules, findSimilarRules } from './helpers/rule-matcher.js';
12
- import { createProjectRollbackManager, fileTypeErrors, introducedTypeErrors, } from './helpers/transform-safety.js';
14
+ import { createProjectRollbackManager, TransformBackups, changedSourceFiles, fileTypeErrors, importersAndErrorsBefore, isInsideProject, outsideProjectError, sourceTexts, testFileMatcher, typeErrorsBeforeChange, introducedTypeErrors, plainFileChanges, ruleFileChanges, saveChangedFiles, syntaxErrors, } from './helpers/transform-safety.js';
15
+ import { angularTemplateChecker, changedTemplateComponents, checkChangedTemplates, } from './helpers/template-check.js';
13
16
  import { cpus } from 'node:os';
14
17
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
15
18
  /** Transformations applied by plugin-angular (its rules check `transformationType`). */
@@ -59,6 +62,38 @@ export function pluginConfigFor(transformation, options) {
59
62
  },
60
63
  };
61
64
  }
65
+ /**
66
+ * Transformations whose analysis rule has options the transform reads too:
67
+ * the rule id in `rules` of .angular-modernizer.json and the option keys the
68
+ * transform reads (rule-only keys such as `scope` and `suppressionComments`
69
+ * stay with the rule).
70
+ */
71
+ const RULE_OPTION_DEFAULTS = {
72
+ 'interface-duplication': {
73
+ ruleId: 'angular:interface-duplication',
74
+ keys: ['minSimilarInstances', 'minCommonProperties', 'minSimilarityScore'],
75
+ },
76
+ };
77
+ /**
78
+ * The transformation options with the options of its analysis rule from the
79
+ * `rules` section as defaults: the rule and the transform then use the same
80
+ * thresholds. The call `options` win, key by key.
81
+ */
82
+ export function withRuleOptionDefaults(transformation, rules, options) {
83
+ const mapping = RULE_OPTION_DEFAULTS[transformation];
84
+ const ruleConfig = mapping === undefined ? undefined : rules?.[mapping.ruleId];
85
+ if (mapping === undefined || typeof ruleConfig !== 'object' || ruleConfig === null) {
86
+ return options;
87
+ }
88
+ const defaults = {};
89
+ for (const key of mapping.keys) {
90
+ const value = ruleConfig[key];
91
+ if (value !== undefined) {
92
+ defaults[key] = value;
93
+ }
94
+ }
95
+ return { ...defaults, ...options };
96
+ }
62
97
  /** Warnings and failed batch files spelled out in the summary. */
63
98
  const SUMMARY_WARNINGS = 5;
64
99
  const SUMMARY_FAILED_FILES = 10;
@@ -78,27 +113,85 @@ function describeSafety(result) {
78
113
  }
79
114
  return lines;
80
115
  }
116
+ /** Broken test files, spelled out in the summary of single files and batches. */
117
+ function describeTestErrors(result) {
118
+ const errors = result.validation.testTypeErrors ?? [];
119
+ if (errors.length === 0) {
120
+ return [];
121
+ }
122
+ const files = new Set(errors.map((e) => e.slice(0, e.indexOf(': TS'))));
123
+ return [
124
+ `${files.size} test file(s) no longer compile (failOnTestErrors makes this fail the transformation):`,
125
+ ...errors.slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`),
126
+ ];
127
+ }
128
+ /** Type check word of the summary (passed, failed or skipped), plus the template check when it ran. */
129
+ function describeTypeCheck(result) {
130
+ const typeCheck = result.validation.typeCheck ?? (result.validation.typeCheckPassed ? 'passed' : 'failed');
131
+ const templateCheck = result.validation.templateCheck;
132
+ const templateErrors = result.validation.introducedTemplateErrors ?? [];
133
+ return (typeCheck +
134
+ (templateCheck === undefined ? '' : `; template check ${templateCheck}`) +
135
+ (templateErrors.length > 0 ? ` (${templateErrors.length} introduced template error(s))` : ''));
136
+ }
137
+ /**
138
+ * Result of a deprecated transformation type (core-shared-modules,
139
+ * container-presentational): nothing changed, the rule's message says what to
140
+ * use instead; no project is loaded and no backup written.
141
+ */
142
+ function deprecatedResult(params, message) {
143
+ const noChanges = { linesChanged: 0, additions: 0, deletions: 0 };
144
+ return {
145
+ success: true,
146
+ modified: false,
147
+ transformation: params.transformation ?? '',
148
+ filePath: params.filePath,
149
+ files: params.files?.map((path) => ({ path, success: true, modified: false, changes: noChanges })),
150
+ changedFiles: [],
151
+ ruleMessages: [message],
152
+ changes: noChanges,
153
+ validation: { syntaxValid: true, typeCheckPassed: false, typeCheck: 'skipped' },
154
+ };
155
+ }
156
+ /** Outcome words of the summary: failed, made no changes, or succeeded. */
157
+ function describeOutcome(result) {
158
+ if (!result.success) {
159
+ return 'failed on';
160
+ }
161
+ return result.modified === false ? 'made no changes on' : 'succeeded on';
162
+ }
163
+ /** The first rule messages, e.g. why a run changed nothing. */
164
+ function describeRuleMessages(result) {
165
+ const messages = result.ruleMessages ?? [];
166
+ if (messages.length === 0) {
167
+ return [];
168
+ }
169
+ return ['Rule message(s):', ...messages.slice(0, SUMMARY_WARNINGS).map((m) => `- ${m}`)];
170
+ }
81
171
  /** Text summary of a single-file, batch or background transformation. */
82
172
  function describeTransformation(result) {
83
173
  if (result.operationId !== undefined) {
84
174
  return (`${result.transformation} started in the background as operation ${result.operationId}; ` +
85
175
  'get-operation-progress (deprecated) returns the result once it is completed.');
86
176
  }
87
- const outcome = result.success ? 'succeeded' : 'failed';
177
+ const outcome = describeOutcome(result);
88
178
  const lines = [];
89
179
  const introduced = result.validation.introducedTypeErrors ?? [];
90
180
  if (result.files !== undefined) {
91
181
  const failed = result.files.filter((f) => !f.success);
92
182
  const duration = result.orchestration?.duration;
93
- lines.push(`${result.transformation} ${outcome} on ${result.files.length} file(s): ` +
94
- `${result.files.length - failed.length} succeeded, ${failed.length} failed` +
183
+ lines.push(`${result.transformation} ${outcome} ${result.files.length} file(s): ` +
184
+ `${result.files.length - failed.length} succeeded, ${failed.length} failed, ` +
185
+ `${result.changes.linesChanged} line(s) changed (+${result.changes.additions}/-${result.changes.deletions})` +
95
186
  (duration === undefined ? '' : ` in ${duration} ms`) +
96
- `; type check ${result.validation.typeCheckPassed ? 'passed' : 'failed'}` +
187
+ `; type check ${describeTypeCheck(result)}` +
97
188
  (introduced.length > 0
98
189
  ? ` (${introduced.length} introduced type error(s))`
99
190
  : '') +
100
191
  '.');
101
192
  lines.push(...describeSafety(result));
193
+ lines.push(...describeTestErrors(result));
194
+ lines.push(...describeRuleMessages(result));
102
195
  lines.push(...(result.warnings ?? []).map((w) => `- ${w}`));
103
196
  lines.push(...failed
104
197
  .slice(0, SUMMARY_FAILED_FILES)
@@ -106,9 +199,11 @@ function describeTransformation(result) {
106
199
  return lines.join('\n');
107
200
  }
108
201
  const c = result.changes;
109
- lines.push(`${result.transformation} ${outcome} on ${result.filePath ?? 'unknown file'}: ` +
110
- `${c.linesChanged} line(s) changed (+${c.additions}/-${c.deletions}); ` +
111
- `type check ${result.validation.typeCheckPassed ? 'passed' : 'failed'}` +
202
+ lines.push(`${result.transformation} ${outcome} ${result.filePath ?? 'unknown file'}` +
203
+ (result.success && result.modified === false
204
+ ? '; '
205
+ : `: ${c.linesChanged} line(s) changed (+${c.additions}/-${c.deletions}); `) +
206
+ `type check ${describeTypeCheck(result)}` +
112
207
  (introduced.length > 0
113
208
  ? ` (${introduced.length} introduced type error(s))`
114
209
  : '') +
@@ -118,6 +213,9 @@ function describeTransformation(result) {
118
213
  '.');
119
214
  lines.push(...describeSafety(result));
120
215
  lines.push(...introduced.slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`));
216
+ lines.push(...(result.validation.introducedTemplateErrors ?? []).slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`));
217
+ lines.push(...describeTestErrors(result));
218
+ lines.push(...describeRuleMessages(result));
121
219
  const warnings = result.warnings ?? [];
122
220
  if (warnings.length > 0) {
123
221
  lines.push(`${warnings.length} warning(s):`);
@@ -128,40 +226,161 @@ function describeTransformation(result) {
128
226
  /**
129
227
  * MCP tool for code transformations.
130
228
  */
131
- /** Loads the kernel a batch shares: the project's tsconfig program with the Angular plugin. */
132
- async function loadBatchKernel(projectRoot) {
229
+ /** tsconfig of a batch's project; throws when there is none. */
230
+ function batchTsConfigPath(projectRoot) {
133
231
  const tsConfigPath = findTsConfig(projectRoot);
134
232
  if (!tsConfigPath) {
135
233
  throw new Error('Could not find tsconfig.json');
136
234
  }
235
+ return tsConfigPath;
236
+ }
237
+ /** Loads the kernel a batch shares: the project's tsconfig program with the Angular plugin. */
238
+ async function loadBatchKernel(tsConfigPath) {
137
239
  const kernel = new Kernel({
138
240
  tsConfigPath,
139
- plugins: [new AngularPlugin()],
241
+ plugins: [new AngularPlugin(), new StandalonePlugin()],
140
242
  });
141
243
  await kernel.initialize();
142
244
  return kernel;
143
245
  }
144
246
  /** Transforms one batch file on the shared kernel and saves it. */
145
- async function transformWithKernel(kernel, filePath, params) {
247
+ async function transformWithKernel(kernel, filePath, params, backups, extraErrorsBefore, projectRoot) {
248
+ if (!isInsideProject(projectRoot, filePath)) {
249
+ throw outsideProjectError(projectRoot, [filePath]);
250
+ }
146
251
  const project = kernel.getProject();
147
252
  const sourceFile = project.getSourceFile(filePath) ?? project.addSourceFileAtPath(filePath);
148
- const linesBefore = sourceFile.getFullText().split('\n').length;
253
+ const textBefore = sourceFile.getFullText();
254
+ const textsBefore = sourceTexts(project);
149
255
  const result = (await kernel.transformFile(sourceFile, {
150
256
  dryRun: false,
151
257
  autoSave: true,
152
258
  pluginConfig: pluginConfigFor(params.transformation, params.options),
153
259
  }));
154
- await sourceFile.save();
155
- const linesAfter = sourceFile.getFullText().split('\n').length;
260
+ // Every file the transformation changed, also other files than this one
261
+ // and files outside the ts-morph project (the rules' fileChanges): their
262
+ // errors at the old text (for the batch type check), a backup from the old
263
+ // text, then all of them saved
264
+ // A rule may remove the file from the project (library-extraction moves it)
265
+ const textAfter = project.getSourceFile(filePath)?.getFullText() ?? '';
266
+ const changed = [
267
+ ...changedSourceFiles(project, textsBefore, filePath),
268
+ ...plainFileChanges(project, ruleFileChanges([result])),
269
+ ];
270
+ const outside = changed.map((f) => f.filePath).filter((f) => !isInsideProject(projectRoot, f));
271
+ if (outside.length > 0) {
272
+ throw outsideProjectError(projectRoot, outside);
273
+ }
274
+ const extras = changed.filter((f) => f.filePath !== filePath);
275
+ if (extraErrorsBefore !== undefined && extras.some((f) => !extraErrorsBefore.has(f.filePath))) {
276
+ const before = typeErrorsBeforeChange(project, changed);
277
+ for (const extra of extras) {
278
+ if (!extraErrorsBefore.has(extra.filePath)) {
279
+ extraErrorsBefore.set(extra.filePath, before.get(extra.filePath) ?? []);
280
+ }
281
+ }
282
+ }
283
+ if (backups !== undefined) {
284
+ await backups.record(changed);
285
+ }
286
+ await saveChangedFiles(project, changed);
287
+ backups?.markSaved(changed.map((f) => f.filePath));
288
+ const changes = sumLineChanges(changed.map((f) => countLineChanges(f.before ?? '', f.after)));
156
289
  return {
290
+ extraFiles: extras.map((f) => f.filePath),
291
+ changedTexts: changed,
157
292
  success: result.success,
158
- changes: {
159
- linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
160
- additions: Math.max(0, linesAfter - linesBefore),
161
- deletions: Math.max(0, linesBefore - linesAfter),
162
- },
293
+ syntaxErrors: introducedTypeErrors(syntaxErrors(filePath, textBefore), syntaxErrors(filePath, textAfter)),
294
+ modified: changes.linesChanged > 0,
295
+ ruleMessages: requestedRuleMessages([result]),
296
+ changes,
163
297
  };
164
298
  }
299
+ /**
300
+ * Context file for a library-extraction whose `filePath` no longer exists
301
+ * (an earlier run moved it into the library): the first source file of the
302
+ * project, by path, in the workspace of that path (nearest folder above it
303
+ * with angular.json): a .ts or .tsx file, not a declaration file (ts-morph
304
+ * also keeps imported JSON files as source files). The rule only needs a file of
305
+ * the workspace and checks `options.artifacts`, so a second run with the
306
+ * same arguments reports what is already in the library. `undefined` in
307
+ * every other case, so the file load fails as before.
308
+ */
309
+ export function movedFileContext(project, filePath, transformation, options) {
310
+ const artifacts = options['artifacts'];
311
+ if (transformation !== 'library-extraction' || existsSync(filePath) || !Array.isArray(artifacts) || artifacts.length === 0) {
312
+ return undefined;
313
+ }
314
+ let dir = dirname(filePath);
315
+ while (!existsSync(join(dir, 'angular.json'))) {
316
+ const parent = dirname(dir);
317
+ if (parent === dir) {
318
+ return undefined;
319
+ }
320
+ dir = parent;
321
+ }
322
+ const workspace = `${dir}/`;
323
+ return project
324
+ .getSourceFiles()
325
+ .map((f) => f.getFilePath())
326
+ .filter((path) => path.startsWith(workspace) && /\.tsx?$/.test(path) && !path.endsWith('.d.ts') && !path.includes('/node_modules/'))
327
+ .sort()[0];
328
+ }
329
+ /**
330
+ * Message every transform rule returns when the call requested another
331
+ * transformation (plugin-angular, plugin-standalone and plugin-solid).
332
+ */
333
+ const NOT_APPLICABLE_MESSAGE = 'Transformation type not applicable';
334
+ /**
335
+ * Messages of the rules that handled the requested transformation, without
336
+ * duplicates: the coordinator runs every rule of every plugin, the others
337
+ * answer {@link NOT_APPLICABLE_MESSAGE}.
338
+ */
339
+ function requestedRuleMessages(results) {
340
+ const messages = new Set();
341
+ for (const result of results) {
342
+ for (const rule of result.ruleResults ?? []) {
343
+ if (rule.message !== undefined && rule.message !== '' && rule.message !== NOT_APPLICABLE_MESSAGE) {
344
+ messages.add(rule.message);
345
+ }
346
+ }
347
+ }
348
+ return [...messages];
349
+ }
350
+ /**
351
+ * Files a batch left changed on disk: the changed batch files and the other
352
+ * files their transformations changed, without restored ones.
353
+ */
354
+ function changedFilesOf(files, extrasOf, restored) {
355
+ const changed = new Set();
356
+ for (const file of files) {
357
+ if (file.modified === true) {
358
+ changed.add(file.path);
359
+ }
360
+ for (const extra of extrasOf.get(file.path) ?? []) {
361
+ if (!restored.has(extra)) {
362
+ changed.add(extra);
363
+ }
364
+ }
365
+ }
366
+ return changed.size > 0 ? [...changed] : undefined;
367
+ }
368
+ /** Line counts of a file the call left unchanged (or restored). */
369
+ const NO_CHANGES = {
370
+ linesChanged: 0,
371
+ additions: 0,
372
+ deletions: 0,
373
+ };
374
+ /** Sum of the line counts of batch files (files without counts add 0). */
375
+ function sumLineChanges(list) {
376
+ const sum = { linesChanged: 0, additions: 0, deletions: 0 };
377
+ for (const changes of list) {
378
+ sum.linesChanged += changes?.linesChanged ?? 0;
379
+ sum.additions += changes?.additions ?? 0;
380
+ sum.deletions += changes?.deletions ?? 0;
381
+ }
382
+ return sum;
383
+ }
165
384
  /**
166
385
  * Type errors of the batch files on the shared kernel, keyed by path. Files
167
386
  * that do not exist are left out (their transformation fails on its own).
@@ -193,6 +412,78 @@ function introducedBatchTypeErrors(kernel, files, before) {
193
412
  }
194
413
  return introduced;
195
414
  }
415
+ /**
416
+ * Type errors a batch introduced into files that import a changed file,
417
+ * keyed by the batch file whose transformation changed the imported file;
418
+ * each error reads `<importer>: <error>`. The importers are checked against
419
+ * their errors at the old texts of all changed files.
420
+ */
421
+ function introducedImporterErrors(kernel, files, isTest, testErrors) {
422
+ const project = kernel.getProject();
423
+ const { texts, ownersOf } = batchChangedTexts(files);
424
+ const changed = [...texts.values()];
425
+ const { importers, before } = importersAndErrorsBefore(project, changed);
426
+ const errors = new Map();
427
+ if (importers.length === 0) {
428
+ return errors;
429
+ }
430
+ for (const importer of importers) {
431
+ const sourceFile = project.getSourceFile(importer);
432
+ if (sourceFile === undefined) {
433
+ continue;
434
+ }
435
+ const added = introducedTypeErrors(before.get(importer) ?? [], fileTypeErrors(sourceFile));
436
+ if (added.length === 0) {
437
+ continue;
438
+ }
439
+ if (isTest(importer)) {
440
+ testErrors.push(...added.map((e) => `${importer}: ${e}`));
441
+ continue;
442
+ }
443
+ const imported = new Set(sourceFile
444
+ .getImportDeclarations()
445
+ .flatMap((d) => d.getModuleSpecifierSourceFile()?.getFilePath() ?? []));
446
+ for (const changedPath of texts.keys()) {
447
+ if (!imported.has(changedPath)) {
448
+ continue;
449
+ }
450
+ for (const owner of ownersOf.get(changedPath) ?? []) {
451
+ errors.set(owner, [...(errors.get(owner) ?? []), ...added.map((e) => `${importer}: ${e}`)]);
452
+ }
453
+ }
454
+ }
455
+ return errors;
456
+ }
457
+ /**
458
+ * The files a batch changed, each with its first text before and its last
459
+ * text after, and the batch files whose transformation changed it.
460
+ */
461
+ function batchChangedTexts(files) {
462
+ const texts = new Map();
463
+ const ownersOf = new Map();
464
+ for (const file of files) {
465
+ for (const changed of file.changedTexts ?? []) {
466
+ const known = texts.get(changed.filePath);
467
+ texts.set(changed.filePath, { ...changed, before: known === undefined ? changed.before : known.before });
468
+ ownersOf.set(changed.filePath, (ownersOf.get(changed.filePath) ?? new Set()).add(file.path));
469
+ }
470
+ }
471
+ return { texts, ownersOf };
472
+ }
473
+ /**
474
+ * New template errors of a batch per batch file whose transformation
475
+ * changed the file the error is attributed to.
476
+ */
477
+ function templateErrorsByBatchFile(templates, ownersOf) {
478
+ const errors = new Map();
479
+ for (const { error, changedFiles } of templates?.introduced ?? []) {
480
+ const owners = new Set(changedFiles.flatMap((file) => [...(ownersOf.get(file) ?? [])]));
481
+ for (const owner of owners) {
482
+ errors.set(owner, [...(errors.get(owner) ?? []), error]);
483
+ }
484
+ }
485
+ return errors;
486
+ }
196
487
  /**
197
488
  * Files a batch restores after a failure: all-or-nothing every file,
198
489
  * selective only the failed ones, none nothing.
@@ -207,6 +498,34 @@ function batchFilesToRestore(strategy, allFiles, failedFiles) {
207
498
  return [];
208
499
  }
209
500
  }
501
+ /**
502
+ * Fails the batch files that changed a file a failed batch file changed too
503
+ * (a spec that constructs both classes, or the failed file itself): a
504
+ * restore puts such a file back to its text before the call, which takes
505
+ * the change of every batch file that made one. Repeats until no succeeded
506
+ * file shares a file with a failed one.
507
+ */
508
+ function failSharingFiles(files, extrasOf) {
509
+ const touched = (f) => [f.path, ...(extrasOf.get(f.path) ?? [])];
510
+ const result = [...files];
511
+ let changed = true;
512
+ while (changed) {
513
+ changed = false;
514
+ const restoredFiles = new Set(result.filter((f) => !f.success).flatMap(touched));
515
+ for (const [index, f] of result.entries()) {
516
+ const shared = f.success ? touched(f).find((file) => restoredFiles.has(file)) : undefined;
517
+ if (shared !== undefined) {
518
+ result[index] = {
519
+ ...f,
520
+ success: false,
521
+ error: `Restored: shares ${shared} with a failed file`,
522
+ };
523
+ changed = true;
524
+ }
525
+ }
526
+ }
527
+ return result;
528
+ }
210
529
  /** Thrown between the steps of a single-file run when the client cancelled. */
211
530
  class TransformCancelledError extends Error {
212
531
  constructor() {
@@ -227,6 +546,15 @@ class TransformCancelledError extends Error {
227
546
  */
228
547
  export class TransformCodeTool {
229
548
  name = 'transform-code';
549
+ /** Compiles changed templates before and after a call. */
550
+ templateChecker;
551
+ /**
552
+ * @param options - `templateChecker` replaces the Angular compiler of the
553
+ * target project in the template check (tests).
554
+ */
555
+ constructor(options = {}) {
556
+ this.templateChecker = options.templateChecker ?? angularTemplateChecker;
557
+ }
230
558
  title = 'Transform Code';
231
559
  annotations = {
232
560
  readOnlyHint: false,
@@ -255,39 +583,12 @@ export class TransformCodeTool {
255
583
  },
256
584
  transformation: {
257
585
  type: 'string',
258
- description: 'Type of transformation to apply',
259
- enum: [
260
- 'constructor-to-inject',
261
- 'interface-extraction',
262
- 'standalone-migration',
263
- 'dependency-injection-migration',
264
- 'facade-pattern',
265
- 'form-modernization',
266
- 'constructor-injection-transform',
267
- 'component-inputs-interface-extraction',
268
- 'service-injection-cleanup',
269
- 'container-presentational',
270
- 'core-shared-modules',
271
- 'inheritance-to-composition',
272
- 'promise-service-to-observable',
273
- 'promise-component-to-reactive',
274
- 'promise-cleanup',
275
- 'sequential-await-to-forkjoin',
276
- 'missing-output-transform',
277
- 'subscription-transform',
278
- 'library-extraction',
279
- 'service-bag-transform',
280
- 'any-to-interface',
281
- 'dto-object-literal',
282
- 'interface-duplication',
283
- 'static-class-to-functions',
284
- 'extract-static-from-stateful',
285
- 'type-safety',
286
- ],
586
+ description: 'Type of transformation to apply (container-presentational is deprecated and changes nothing; use missing-output-transform)',
587
+ enum: [...TRANSFORMATION_TYPES],
287
588
  },
288
589
  options: {
289
590
  type: 'object',
290
- description: 'Transformation-specific options. service-bag-transform: assignments ({ methodName: groupKey }) moves methods into the named group (e.g. uncertain methods from the scan metadata); unassigned uncertain methods stay in the original service',
591
+ description: 'Transformation-specific options. service-bag-transform: assignments ({ methodName: groupKey }) moves methods into the group with that key in metadata.groups of architecture:service-bag, or into a new group; other methods follow the split plan',
291
592
  },
292
593
  validateBeforeTransform: {
293
594
  type: 'boolean',
@@ -301,7 +602,7 @@ export class TransformCodeTool {
301
602
  },
302
603
  validateTransformation: {
303
604
  type: 'boolean',
304
- description: 'Whether to validate transformation results (default: true): type check of the transformed file (new errors only; in a batch every batch file, a file with a new error fails and rollbackStrategy applies), plus build and lint when enabled',
605
+ description: 'Whether to validate transformation results (default: true): type check of every changed file and of the files that import one (new errors only; in a batch a file whose transformation added an error fails and rollbackStrategy applies), plus build and lint when enabled',
305
606
  default: true,
306
607
  },
307
608
  autoRollback: {
@@ -373,7 +674,7 @@ export class TransformCodeTool {
373
674
  },
374
675
  streaming: {
375
676
  type: 'boolean',
376
- description: 'Deprecated, kept in 1.x (default: false): returns operationId immediately, the transformation runs in the background with the same backup, validation and rollback, and get-operation-progress returns its result once completed. Synchronous calls report progress through MCP progress notifications and roll back when cancelled.',
677
+ description: 'Deprecated, kept in 2.x (default: false): returns operationId immediately with status "running" (success false: nothing has run yet), the transformation runs in the background with the same backup, validation and rollback, and get-operation-progress returns its result once completed. Synchronous calls report progress through MCP progress notifications and roll back when cancelled.',
377
678
  default: false,
378
679
  },
379
680
  diffFormat: {
@@ -403,6 +704,11 @@ export class TransformCodeTool {
403
704
  description: "Whether to run the project's lint script after transformation (default: false). Lints the whole project; the transformed file is type-checked either way and rolled back on new type errors.",
404
705
  default: false,
405
706
  },
707
+ failOnTestErrors: {
708
+ type: 'boolean',
709
+ description: 'Whether type errors the transformation causes in test files (tsconfig.spec.json, else *.spec.ts / *.test.ts) fail it like app errors (default: false: they are reported in validation.testTypeErrors and the summary, the transformation stays)',
710
+ default: false,
711
+ },
406
712
  rollbackOnBuildFailure: {
407
713
  type: 'boolean',
408
714
  description: 'Whether to automatically rollback on build failure (default: true). When enabled, restores backups if build validation fails.',
@@ -428,7 +734,15 @@ export class TransformCodeTool {
428
734
  type: 'object',
429
735
  properties: {
430
736
  operationId: { type: 'string' },
737
+ status: {
738
+ type: 'string',
739
+ enum: ['running'],
740
+ description: 'Only in the immediate answer of a streaming call: nothing has run yet, so success, modified, validation.syntaxValid and validation.typeCheckPassed are false and mean "not yet"; get-operation-progress returns the result. Not an error.',
741
+ },
431
742
  success: { type: 'boolean' },
743
+ modified: { type: 'boolean' },
744
+ ruleMessages: STRING_ARRAY,
745
+ changedFiles: STRING_ARRAY,
432
746
  filePath: { type: 'string' },
433
747
  files: {
434
748
  type: 'array',
@@ -438,6 +752,15 @@ export class TransformCodeTool {
438
752
  path: { type: 'string' },
439
753
  success: { type: 'boolean' },
440
754
  error: { type: 'string' },
755
+ modified: { type: 'boolean' },
756
+ changes: {
757
+ type: 'object',
758
+ properties: {
759
+ linesChanged: { type: 'integer' },
760
+ additions: { type: 'integer' },
761
+ deletions: { type: 'integer' },
762
+ },
763
+ },
441
764
  },
442
765
  required: ['path', 'success'],
443
766
  },
@@ -479,8 +802,12 @@ export class TransformCodeTool {
479
802
  properties: {
480
803
  syntaxValid: { type: 'boolean' },
481
804
  typeCheckPassed: { type: 'boolean' },
805
+ typeCheck: { type: 'string', enum: ['passed', 'failed', 'skipped'] },
482
806
  testsPass: { type: 'boolean' },
483
807
  introducedTypeErrors: STRING_ARRAY,
808
+ testTypeErrors: STRING_ARRAY,
809
+ templateCheck: { type: 'string', enum: ['passed', 'failed', 'skipped'] },
810
+ introducedTemplateErrors: STRING_ARRAY,
484
811
  },
485
812
  required: ['syntaxValid', 'typeCheckPassed'],
486
813
  },
@@ -500,6 +827,7 @@ export class TransformCodeTool {
500
827
  performed: { type: 'boolean' },
501
828
  reason: { type: 'string' },
502
829
  success: { type: 'boolean' },
830
+ files: STRING_ARRAY,
503
831
  },
504
832
  required: ['performed'],
505
833
  },
@@ -585,18 +913,27 @@ export class TransformCodeTool {
585
913
  // Streaming mode - start operation in background and return operationId
586
914
  return this.executeStreaming(params);
587
915
  }
588
- // Use orchestration object directly
589
- // Note: parallel defaults to false for transformations for safety
916
+ // Deprecated types change nothing: answered without loading the project
917
+ const deprecated = typeof params.transformation === 'string' ? deprecationMessage(params.transformation) : undefined;
918
+ if (deprecated !== undefined) {
919
+ return deprecatedResult(params, deprecated);
920
+ }
921
+ // Detect batch mode
922
+ const isBatchMode = Boolean(params.files && params.files.length > 0);
923
+ // Orchestration of tools['transform-code'] in .angular-modernizer.json,
924
+ // overridden by the call; parallel defaults to false for safety
925
+ const configured = isBatchMode && params.files?.[0] !== undefined
926
+ ? loadConfig(params.projectRoot ?? this.findProjectRoot(params.files[0])).tools?.['transform-code']?.orchestration
927
+ : undefined;
590
928
  const orchestration = {
591
- parallel: false, // Safety default for transformations
929
+ parallel: false,
930
+ ...configured,
592
931
  ...params.orchestration,
593
932
  };
594
- // Detect batch mode
595
- const isBatchMode = Boolean(params.files && params.files.length > 0);
596
933
  // Phase 4: Auto-enable parallel processing for >100 files (unless explicitly disabled)
597
934
  if (isBatchMode && params.files && params.files.length > 100) {
598
- // Only auto-enable if user hasn't explicitly set parallel flag
599
- if (params.orchestration?.parallel === undefined) {
935
+ // Only auto-enable if neither the call nor the config set the flag
936
+ if (params.orchestration?.parallel === undefined && configured?.parallel === undefined) {
600
937
  orchestration.parallel = true;
601
938
  orchestration.autoSelectMode = orchestration.autoSelectMode ?? true;
602
939
  orchestration.maxWorkers =
@@ -623,7 +960,10 @@ export class TransformCodeTool {
623
960
  }
624
961
  // Validate that the transformation type exists in the schema
625
962
  this.validateTransformationType(transformation);
626
- return this.executeSingleFile(filePath, transformation, mergedParams.options ?? {}, {
963
+ if (!isInsideProject(projectRoot, filePath)) {
964
+ throw outsideProjectError(projectRoot, [filePath]);
965
+ }
966
+ return this.executeSingleFile(filePath, transformation, withRuleOptionDefaults(transformation, fullConfig.rules, mergedParams.options) ?? {}, {
627
967
  apiStyle: mergedParams.apiStyle ?? 'fluent',
628
968
  validateBeforeTransform: mergedParams.validateBeforeTransform ?? true,
629
969
  createBackup: mergedParams.createBackup ?? true,
@@ -634,6 +974,8 @@ export class TransformCodeTool {
634
974
  validateBuild: mergedParams.validateBuild ?? false,
635
975
  validateLint: mergedParams.validateLint ?? false,
636
976
  buildTimeout: mergedParams.buildTimeout ?? 300000,
977
+ rollbackOnBuildFailure: mergedParams.rollbackOnBuildFailure ?? true,
978
+ failOnTestErrors: mergedParams.failOnTestErrors ?? false,
637
979
  projectRoot,
638
980
  signal: ctx.signal,
639
981
  progress: ctx.progress,
@@ -645,10 +987,14 @@ export class TransformCodeTool {
645
987
  * or imperative), type check of the file against its errors before the
646
988
  * transformation, optional build and lint, rollback on failure.
647
989
  */
648
- async executeSingleFile(filePath, transformation, options, config) {
990
+ async executeSingleFile(requestedPath, transformation, options, config) {
991
+ let filePath = requestedPath;
992
+ const notes = [];
649
993
  let preValidationResult;
650
994
  let backupResult;
651
995
  let rollbackResult;
996
+ let textBefore;
997
+ let changed = [];
652
998
  const rollbackManager = createProjectRollbackManager(config.projectRoot, {
653
999
  backupDir: config.backupDir,
654
1000
  });
@@ -661,7 +1007,7 @@ export class TransformCodeTool {
661
1007
  // the whole program.
662
1008
  const kernel = new Kernel({
663
1009
  tsConfigPath,
664
- plugins: [new AngularPlugin()],
1010
+ plugins: [new AngularPlugin(), new StandalonePlugin()],
665
1011
  cacheConfig: {
666
1012
  enabled: true,
667
1013
  cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
@@ -672,7 +1018,12 @@ export class TransformCodeTool {
672
1018
  });
673
1019
  await kernel.initialize();
674
1020
  const project = kernel.getProject();
675
- const sourceFile = project.addSourceFileAtPath(filePath);
1021
+ const context = movedFileContext(project, filePath, transformation, options);
1022
+ if (context !== undefined) {
1023
+ notes.push(`${filePath} does not exist (moved by an earlier library-extraction); ${context} served as context file`);
1024
+ filePath = context;
1025
+ }
1026
+ const sourceFile = project.getSourceFile(filePath) ?? project.addSourceFileAtPath(filePath);
676
1027
  const checkCancelled = async () => {
677
1028
  await yieldIfCancellable(config.signal);
678
1029
  if (config.signal?.aborted === true) {
@@ -685,63 +1036,94 @@ export class TransformCodeTool {
685
1036
  if (config.validateBeforeTransform) {
686
1037
  preValidationResult = await this.preValidate(sourceFile, project, transformation);
687
1038
  }
688
- // Step 1: Backup in the project: file copy plus git snapshot
689
- if (config.createBackup) {
690
- const backup = await rollbackManager.createBackup([filePath], {
1039
+ const typeErrorsBefore = config.validateTransformation
1040
+ ? fileTypeErrors(sourceFile)
1041
+ : [];
1042
+ textBefore = sourceFile.getFullText();
1043
+ // A rule may change other files too (callers, generated files)
1044
+ const textsBefore = sourceTexts(project);
1045
+ // Step 1: Transform (in memory)
1046
+ const transformed = config.apiStyle === 'fluent'
1047
+ ? await this.transformFluent(kernel, filePath, transformation, options, config)
1048
+ : await this.transformImperative(kernel, sourceFile, transformation, options, config.signal);
1049
+ // Step 2: Back up every file that changed (from its text before the
1050
+ // transformation; a file with no change gets no backup), then save
1051
+ // them all: a file changed only in memory would leave the project
1052
+ // inconsistent on disk
1053
+ // Files outside the ts-morph project come from the rules' fileChanges
1054
+ changed = [
1055
+ ...changedSourceFiles(project, textsBefore, filePath),
1056
+ ...plainFileChanges(project, transformed.fileChanges),
1057
+ ];
1058
+ const outside = changed
1059
+ .map((f) => f.filePath)
1060
+ .filter((f) => !isInsideProject(config.projectRoot, f));
1061
+ if (outside.length > 0) {
1062
+ changed = [];
1063
+ throw outsideProjectError(config.projectRoot, outside);
1064
+ }
1065
+ if (config.createBackup && changed.length > 0) {
1066
+ const backups = new TransformBackups(rollbackManager, {
1067
+ group: `op-${Date.now()}-${randomUUID().slice(0, 8)}`,
691
1068
  reason: `transform-code ${transformation}`,
692
1069
  });
693
- if (!backup.success) {
694
- throw new Error(`Failed to create backup before transformation: ${backup.error ?? 'unknown error'}`);
695
- }
696
- backupResult = {
1070
+ await backups.record(changed);
1071
+ const written = backups.written();
1072
+ backupResult = written && {
697
1073
  created: true,
698
- backupPath: backup.metadata?.backupPaths?.[0],
1074
+ backupPath: written.backupPaths[0],
699
1075
  strategy: 'file-backup',
700
- gitSnapshot: backup.metadata?.gitStashRef,
1076
+ gitSnapshot: written.gitSnapshot,
701
1077
  };
702
1078
  }
703
- const typeErrorsBefore = config.validateTransformation
704
- ? fileTypeErrors(sourceFile)
705
- : [];
706
- const linesBefore = sourceFile.getFullText().split('\n').length;
707
- // Step 2: Transform
708
- const transformed = config.apiStyle === 'fluent'
709
- ? await this.transformFluent(kernel, filePath, transformation, options, config)
710
- : await this.transformImperative(kernel, sourceFile, transformation, options);
711
- await sourceFile.save();
1079
+ await saveChangedFiles(project, changed);
712
1080
  await checkCancelled();
713
1081
  config.progress?.(2, 3, 'transformed, validating');
714
- const linesAfter = sourceFile.getFullText().split('\n').length;
715
- const changes = {
716
- linesChanged: transformed.linesChanged,
717
- additions: Math.max(0, linesAfter - linesBefore),
718
- deletions: Math.max(0, linesBefore - linesAfter),
719
- };
1082
+ let changes = sumLineChanges(changed.map((f) => countLineChanges(f.before ?? '', f.after)));
720
1083
  // Step 3: Validate
721
1084
  const checked = config.validateTransformation
722
- ? await this.validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config)
1085
+ ? await this.validateTransformedFile(project, filePath, changed, typeErrorsBefore, config, tsConfigPath)
723
1086
  : {
724
1087
  valid: true,
725
- validation: await this.validateTransformation(filePath, transformation),
1088
+ validation: {
1089
+ syntaxValid: introducedTypeErrors(syntaxErrors(filePath, textBefore), syntaxErrors(filePath, project.getSourceFile(filePath)?.getFullText() ?? '')).length === 0,
1090
+ typeCheckPassed: false,
1091
+ typeCheck: 'skipped',
1092
+ templateCheck: changedTemplateComponents(project, changed).size > 0 ? 'skipped' : undefined,
1093
+ },
726
1094
  issues: [],
727
1095
  };
728
1096
  await checkCancelled();
729
1097
  config.progress?.(3, 3, 'validated');
730
- const warnings = [...transformed.warnings];
1098
+ const warnings = [...transformed.warnings, ...(checked.warnings ?? [])];
731
1099
  // Step 4: Roll back when validation failed
732
- if (!checked.valid && config.autoRollback && config.createBackup) {
733
- const attempt = await rollbackManager.rollback([filePath]);
1100
+ const keepFailedBuild = checked.onlyBuildFailed === true && !config.rollbackOnBuildFailure;
1101
+ if (keepFailedBuild) {
1102
+ warnings.push('Build failed; the transformation was kept (rollbackOnBuildFailure: false)');
1103
+ }
1104
+ if (!checked.valid && config.autoRollback && !keepFailedBuild && backupResult !== undefined) {
1105
+ const attempt = await rollbackManager.rollback(changed.map((f) => f.filePath));
734
1106
  rollbackResult = {
735
1107
  performed: true,
736
1108
  reason: `Validation failed: ${checked.issues.length} issue(s) found`,
737
1109
  success: attempt.success,
1110
+ files: attempt.files,
738
1111
  };
1112
+ if (attempt.success) {
1113
+ changes = { ...NO_CHANGES };
1114
+ }
739
1115
  warnings.push(attempt.success
740
1116
  ? 'Transformation rolled back due to validation failures'
741
1117
  : `Rollback failed: ${attempt.error ?? 'unknown error'}`);
742
1118
  }
1119
+ // A file the rollback restored is no longer changed
1120
+ const restored = new Set(rollbackResult?.files ?? []);
1121
+ const leftChanged = changed.map((f) => f.filePath).filter((f) => !restored.has(f));
743
1122
  return {
744
1123
  success: transformed.success && checked.valid,
1124
+ modified: changes.linesChanged > 0,
1125
+ ruleMessages: transformed.ruleMessages,
1126
+ changedFiles: leftChanged.length > 0 ? leftChanged : undefined,
745
1127
  filePath,
746
1128
  transformation,
747
1129
  changes,
@@ -752,17 +1134,26 @@ export class TransformCodeTool {
752
1134
  pipeline: transformed.pipeline,
753
1135
  intermediateResults: transformed.intermediateResults,
754
1136
  buildValidation: checked.buildValidation,
755
- warnings: [...warnings, ...checked.issues],
1137
+ warnings: [...notes, ...warnings, ...checked.issues],
756
1138
  };
757
1139
  }
758
1140
  catch (error) {
759
1141
  if (error instanceof TransformCancelledError) {
760
- return this.cancelledResult(filePath, transformation, backupResult, rollbackManager);
1142
+ return this.cancelledResult(filePath, transformation, backupResult, rollbackManager, changed.map((f) => f.filePath));
761
1143
  }
762
1144
  const message = error instanceof Error ? error.message : String(error);
1145
+ // A rule that saved the file itself and then failed left it changed
1146
+ // before any backup: put the old text back
1147
+ if (!backupResult &&
1148
+ config.autoRollback &&
1149
+ textBefore !== undefined &&
1150
+ existsSync(filePath) &&
1151
+ readFileSync(filePath, 'utf-8') !== textBefore) {
1152
+ writeFileSync(filePath, textBefore, 'utf-8');
1153
+ }
763
1154
  // Restore the file when it may already have been changed
764
1155
  if (backupResult && config.autoRollback && !rollbackResult) {
765
- const attempt = await rollbackManager.rollback([filePath]);
1156
+ const attempt = await rollbackManager.rollback(changed.map((f) => f.filePath));
766
1157
  if (!attempt.success) {
767
1158
  throw new Error(`Code transformation failed: ${message}. ` +
768
1159
  `Rollback also failed: ${attempt.error ?? 'unknown error'}`);
@@ -777,12 +1168,17 @@ export class TransformCodeTool {
777
1168
  * validated change must not stay. The SDK does not send this result; it
778
1169
  * is complete for direct callers.
779
1170
  */
780
- async cancelledResult(filePath, transformation, backup, rollbackManager) {
1171
+ async cancelledResult(filePath, transformation, backup, rollbackManager, changedFiles) {
781
1172
  const warnings = [];
782
1173
  let rollback;
783
1174
  if (backup !== undefined) {
784
- const attempt = await rollbackManager.rollback([filePath]);
785
- rollback = { performed: true, reason: 'Cancelled by the client', success: attempt.success };
1175
+ const attempt = await rollbackManager.rollback(changedFiles);
1176
+ rollback = {
1177
+ performed: true,
1178
+ reason: 'Cancelled by the client',
1179
+ success: attempt.success,
1180
+ files: attempt.files,
1181
+ };
786
1182
  if (!attempt.success) {
787
1183
  warnings.push(`Rollback failed: ${attempt.error ?? 'unknown error'}`);
788
1184
  }
@@ -795,7 +1191,7 @@ export class TransformCodeTool {
795
1191
  filePath,
796
1192
  transformation,
797
1193
  changes: { linesChanged: 0, additions: 0, deletions: 0 },
798
- validation: { syntaxValid: true, typeCheckPassed: true },
1194
+ validation: { syntaxValid: true, typeCheckPassed: false, typeCheck: 'skipped' },
799
1195
  backup,
800
1196
  rollback,
801
1197
  warnings,
@@ -815,11 +1211,16 @@ export class TransformCodeTool {
815
1211
  };
816
1212
  const result = await preValidator.validate(sourceFile, project, preValidationConfig);
817
1213
  if (!result.valid) {
818
- throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
1214
+ // Only errors block (the validator's `valid`); warnings and info
1215
+ // findings are counted, not listed as issues to fix
1216
+ const blocking = result.issues.filter((i) => i.severity === ValidationSeverity.ERROR);
1217
+ const other = result.issues.length - blocking.length;
1218
+ throw new Error(`Pre-validation failed: ${blocking.length} error(s). ` +
819
1219
  `Cannot safely transform file. Please fix these issues first:\n` +
820
- result.issues
821
- .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
822
- .join('\n'));
1220
+ blocking
1221
+ .map((i) => ` - ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
1222
+ .join('\n') +
1223
+ (other > 0 ? `\n(${other} non-blocking finding(s): warnings or info)` : ''));
823
1224
  }
824
1225
  return {
825
1226
  valid: result.valid,
@@ -836,16 +1237,18 @@ export class TransformCodeTool {
836
1237
  /**
837
1238
  * Transform through the Kernel API.
838
1239
  */
839
- async transformImperative(kernel, sourceFile, transformation, options) {
1240
+ async transformImperative(kernel, sourceFile, transformation, options, signal) {
840
1241
  const result = (await kernel.transformFile(sourceFile, {
841
1242
  dryRun: false,
842
1243
  autoSave: true,
843
1244
  pluginConfig: pluginConfigFor(transformation, options),
1245
+ signal,
844
1246
  }));
845
1247
  return {
846
1248
  success: result.success,
847
- linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
848
1249
  warnings: result.errors.map((e) => e.message),
1250
+ ruleMessages: requestedRuleMessages([result]),
1251
+ fileChanges: ruleFileChanges([result]),
849
1252
  };
850
1253
  }
851
1254
  /**
@@ -853,10 +1256,10 @@ export class TransformCodeTool {
853
1256
  */
854
1257
  async transformFluent(kernel, filePath, transformation, options, config) {
855
1258
  let fluent = FluentKernel.create(kernel)
856
- .transform(transformation, [filePath], pluginConfigFor(transformation, options))
1259
+ .transform(transformation, [filePath], pluginConfigFor(transformation, options), { signal: config.signal })
857
1260
  .withMetadata({ transformation, filePath, options });
858
1261
  if (config.buildCheck) {
859
- fluent = fluent.buildCheck(config.autoRollback);
1262
+ fluent = fluent.buildCheck(config.autoRollback && config.rollbackOnBuildFailure);
860
1263
  }
861
1264
  const pipelineResult = await fluent.execute();
862
1265
  const intermediateResults = {};
@@ -868,8 +1271,9 @@ export class TransformCodeTool {
868
1271
  }
869
1272
  return {
870
1273
  success: pipelineResult.success,
871
- linesChanged: pipelineResult.transformations.length,
872
1274
  warnings: pipelineResult.errors.map((e) => e.message),
1275
+ ruleMessages: requestedRuleMessages(pipelineResult.transformations),
1276
+ fileChanges: ruleFileChanges(pipelineResult.transformations),
873
1277
  pipeline: fluent.getStages().map((stage) => stage.name),
874
1278
  intermediateResults,
875
1279
  };
@@ -880,10 +1284,39 @@ export class TransformCodeTool {
880
1284
  * build and lint only when requested. `buildValidation` is reported only
881
1285
  * when a build ran.
882
1286
  */
883
- async validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config) {
884
- const introduced = introducedTypeErrors(typeErrorsBefore, fileTypeErrors(sourceFile));
1287
+ async validateTransformedFile(project, filePath, changed, typeErrorsBefore, config, tsConfigPath) {
1288
+ // The requested file against its errors from before the transformation;
1289
+ // every other changed file and every file that imports a changed one
1290
+ // against its errors at the old texts
1291
+ // A moved file (library-extraction) is no longer in the project
1292
+ const sourceFile = project.getSourceFile(filePath);
1293
+ // All changed files go back to their old text for the errors before, so
1294
+ // they match the project before the transformation; deleted files come
1295
+ // back once for the importers and those errors
1296
+ const otherChanged = changed.filter((f) => f.filePath !== filePath && f.deleted !== true).map((f) => f.filePath);
1297
+ const { importers, before: othersBefore } = importersAndErrorsBefore(project, changed, (found) => otherChanged.length > 0 || found.length > 0);
1298
+ const others = [...otherChanged, ...importers];
1299
+ const isTest = testFileMatcher(config.projectRoot);
1300
+ const otherErrors = (paths) => paths.flatMap((path) => {
1301
+ const other = project.getSourceFile(path);
1302
+ return other === undefined
1303
+ ? []
1304
+ : introducedTypeErrors(othersBefore.get(path) ?? [], fileTypeErrors(other)).map((e) => `${path}: ${e}`);
1305
+ });
1306
+ // Errors in test files are reported apart; they fail only on request
1307
+ const testErrors = otherErrors(others.filter((path) => isTest(path)));
1308
+ const introduced = [
1309
+ ...introducedTypeErrors(typeErrorsBefore, sourceFile === undefined ? [] : fileTypeErrors(sourceFile)),
1310
+ ...otherErrors(others.filter((path) => !isTest(path))),
1311
+ ...(config.failOnTestErrors ? testErrors : []),
1312
+ ];
885
1313
  const issues = introduced.map((e) => `Type error introduced: ${e}`);
1314
+ // Changed templates: new Angular template errors fail like type errors
1315
+ const templates = await this.checkTemplates(project, changed, config.projectRoot, tsConfigPath);
1316
+ const templateErrors = templates?.introduced.map((i) => i.error) ?? [];
1317
+ issues.push(...templateErrors.map((e) => `Template error introduced: ${e}`));
886
1318
  let postValid = true;
1319
+ let otherPostErrors = 0;
887
1320
  let buildValidation;
888
1321
  if (config.validateBuild || config.validateLint) {
889
1322
  const validator = new PostTransformValidator();
@@ -900,6 +1333,7 @@ export class TransformCodeTool {
900
1333
  const result = await validator.validate(filePath, validationConfig);
901
1334
  const errors = result.issues.filter((i) => i.severity === ValidationSeverity.ERROR);
902
1335
  postValid = result.valid;
1336
+ otherPostErrors = errors.filter((i) => i.type !== ValidationType.BUILD).length;
903
1337
  issues.push(...errors.map((i) => i.message));
904
1338
  if (config.validateBuild) {
905
1339
  const buildErrors = errors
@@ -913,21 +1347,38 @@ export class TransformCodeTool {
913
1347
  }
914
1348
  }
915
1349
  return {
916
- valid: introduced.length === 0 && postValid,
1350
+ valid: introduced.length === 0 && templateErrors.length === 0 && postValid,
1351
+ onlyBuildFailed: introduced.length === 0 &&
1352
+ templateErrors.length === 0 &&
1353
+ buildValidation?.passed === false &&
1354
+ otherPostErrors === 0,
917
1355
  validation: {
918
- syntaxValid: !introduced.some((e) => /^TS1\d{3}:/.test(e)),
1356
+ syntaxValid: !introduced.some((e) => /(^|: )TS1\d{3}:/.test(e)),
919
1357
  typeCheckPassed: introduced.length === 0,
1358
+ typeCheck: introduced.length === 0 ? 'passed' : 'failed',
920
1359
  introducedTypeErrors: introduced.length > 0 ? introduced : undefined,
1360
+ testTypeErrors: testErrors.length > 0 ? testErrors : undefined,
1361
+ templateCheck: templates?.status,
1362
+ introducedTemplateErrors: templateErrors.length > 0 ? templateErrors : undefined,
921
1363
  },
922
1364
  buildValidation,
923
1365
  issues,
1366
+ warnings: templates?.warning === undefined ? undefined : [templates.warning],
924
1367
  };
925
1368
  }
1369
+ /**
1370
+ * Template check of the changed files with the tool's checker;
1371
+ * `undefined` when they changed no template.
1372
+ */
1373
+ checkTemplates(project, changed, projectRoot, tsConfigPath) {
1374
+ return checkChangedTemplates(project, changed, { projectRoot, tsConfigPath }, this.templateChecker);
1375
+ }
926
1376
  /**
927
1377
  * Streaming mode: runs the synchronous path (same safety envelope, batch
928
- * included) in the background and returns the operationId at once. The
929
- * result is stored with setResult before markComplete, so
930
- * get-operation-progress returns it.
1378
+ * included) in the background and returns the operationId at once with
1379
+ * `status: 'running'` and no success or passed check claimed. The result
1380
+ * is stored with setResult before markComplete, so get-operation-progress
1381
+ * returns it.
931
1382
  */
932
1383
  executeStreaming(params) {
933
1384
  const operationId = randomUUID();
@@ -956,8 +1407,11 @@ export class TransformCodeTool {
956
1407
  }
957
1408
  });
958
1409
  }, 50);
1410
+ // Nothing has run yet: claim no success and no passed check
959
1411
  return {
960
- success: true,
1412
+ status: 'running',
1413
+ success: false,
1414
+ modified: false,
961
1415
  operationId,
962
1416
  transformation: params.transformation ?? 'unknown',
963
1417
  changes: {
@@ -966,8 +1420,8 @@ export class TransformCodeTool {
966
1420
  deletions: 0,
967
1421
  },
968
1422
  validation: {
969
- syntaxValid: true,
970
- typeCheckPassed: true,
1423
+ syntaxValid: false,
1424
+ typeCheckPassed: false,
971
1425
  },
972
1426
  warnings: [
973
1427
  'Started in the background: the result is returned by get-operation-progress once the operation is completed.',
@@ -995,9 +1449,10 @@ export class TransformCodeTool {
995
1449
  const mergedParams = { ...config, ...params };
996
1450
  // Use orchestration options for batch transformation (parallel defaults to false for safety)
997
1451
  const batchOptions = {
998
- files: mergedParams.files,
1452
+ // Absolute and normalized, like the paths of backups and rollbacks
1453
+ files: mergedParams.files.map((file) => resolve(file)),
999
1454
  transformation: mergedParams.transformation,
1000
- options: mergedParams.options,
1455
+ options: withRuleOptionDefaults(mergedParams.transformation, fullConfig.rules, mergedParams.options),
1001
1456
  parallel: orchestration.parallel ?? false,
1002
1457
  enableProgress: orchestration.enableProgress ?? false,
1003
1458
  signal: ctx.signal,
@@ -1021,105 +1476,181 @@ export class TransformCodeTool {
1021
1476
  timeout: orchestration.timeout,
1022
1477
  pluginIds: orchestration.pluginIds,
1023
1478
  };
1024
- // Back up all files as one group before any of them changes
1479
+ // Each file that changes is backed up before it is saved, all in one
1480
+ // group; files without a change get no backup
1025
1481
  const rollbackManager = createProjectRollbackManager(projectRoot, {
1026
1482
  backupDir: mergedParams.backupDir,
1027
1483
  });
1028
1484
  const createBackup = mergedParams.createBackup ?? true;
1029
- let backup;
1030
- if (createBackup) {
1031
- const backupResult = await rollbackManager.createBackup(batchOptions.files, {
1485
+ const backups = createBackup
1486
+ ? new TransformBackups(rollbackManager, {
1487
+ group: `op-${Date.now()}-${randomUUID().slice(0, 8)}`,
1032
1488
  reason: `transform-code ${batchOptions.transformation}`,
1033
- });
1034
- if (!backupResult.success) {
1035
- throw new Error(`Failed to create backup before transformation: ${backupResult.error ?? 'unknown error'}`);
1036
- }
1037
- backup = {
1038
- created: true,
1039
- backupPath: backupResult.metadata?.backupPaths?.[0],
1040
- strategy: 'file-backup',
1041
- gitSnapshot: backupResult.metadata?.gitStashRef,
1042
- };
1043
- }
1489
+ })
1490
+ : undefined;
1044
1491
  // Type errors of every batch file before the first transformation, on
1045
1492
  // the kernel the batch shares
1046
1493
  const validateTransformation = mergedParams.validateTransformation ?? true;
1047
1494
  let typeErrorsBefore = new Map();
1495
+ // Errors of files outside the batch list that a transformation changed,
1496
+ // at their text before it
1497
+ const extraErrorsBefore = validateTransformation ? new Map() : undefined;
1498
+ // The tsconfig the kernel loaded, for the template check after the batch
1499
+ let tsConfigPath;
1048
1500
  const batchKernel = createBatchKernel(async () => {
1049
- const kernel = await loadBatchKernel(projectRoot);
1501
+ tsConfigPath = batchTsConfigPath(projectRoot);
1502
+ const kernel = await loadBatchKernel(tsConfigPath);
1050
1503
  if (validateTransformation) {
1051
1504
  typeErrorsBefore = batchTypeErrors(kernel, batchOptions.files);
1052
1505
  }
1053
1506
  return kernel;
1054
1507
  });
1055
1508
  const result = await executeBatchTransformation(batchOptions, async (filePath) => {
1056
- return this.transformSingleFile(filePath, params, batchKernel);
1509
+ return this.transformSingleFile(filePath, { ...params, options: batchOptions.options }, batchKernel, backups, extraErrorsBefore, projectRoot);
1057
1510
  });
1058
- // Files whose transformation introduced a type error fail like files
1059
- // whose transformation failed, and are restored by the same strategy
1060
- const transformedFiles = result.files
1061
- .filter((f) => f.success)
1062
- .map((f) => f.path);
1511
+ // Files whose transformation introduced a type error (in the file or in
1512
+ // another file it changed) fail like files whose transformation failed,
1513
+ // and are restored by the same strategy, with the other files they changed
1514
+ const extrasOf = new Map(result.files.map((f) => [f.path, f.extraFiles ?? []]));
1515
+ // Files outside the ts-morph project (templates) are not type-checked
1516
+ const plainFiles = new Set(result.files.flatMap((f) => (f.changedTexts ?? []).filter((t) => t.plain === true).map((t) => t.filePath)));
1517
+ const transformedFiles = [
1518
+ ...new Set(result.files.filter((f) => f.success).flatMap((f) => [f.path, ...(extrasOf.get(f.path) ?? [])])),
1519
+ ].filter((f) => !plainFiles.has(f));
1063
1520
  const typeChecked = validateTransformation &&
1064
1521
  ctx.signal?.aborted !== true &&
1065
1522
  transformedFiles.length > 0;
1066
1523
  const introduced = typeChecked
1067
- ? await batchKernel.run((kernel) => Promise.resolve(introducedBatchTypeErrors(kernel, transformedFiles, typeErrorsBefore)))
1524
+ ? await batchKernel.run((kernel) => Promise.resolve(introducedBatchTypeErrors(kernel, transformedFiles, new Map([...(extraErrorsBefore ?? []), ...typeErrorsBefore]))))
1525
+ : new Map();
1526
+ // Files that import a changed file and broke, attributed to the batch
1527
+ // files whose transformation changed what they import; errors in test
1528
+ // files are collected apart and fail only with failOnTestErrors
1529
+ const failOnTestErrors = mergedParams.failOnTestErrors ?? false;
1530
+ const testErrors = [];
1531
+ const importerErrors = typeChecked
1532
+ ? await batchKernel.run((kernel) => Promise.resolve(introducedImporterErrors(kernel, result.files.filter((f) => f.success), failOnTestErrors ? () => false : testFileMatcher(projectRoot), testErrors)))
1068
1533
  : new Map();
1534
+ // Changed templates, once for the whole batch: a new template error
1535
+ // fails the batch file whose transformation changed the template
1536
+ const succeeded = result.files.filter((f) => f.success);
1537
+ const { texts: batchTexts, ownersOf } = batchChangedTexts(succeeded);
1538
+ const checkedTsConfig = tsConfigPath;
1539
+ const templates = typeChecked && checkedTsConfig !== undefined
1540
+ ? await batchKernel.run((kernel) => this.checkTemplates(kernel.getProject(), [...batchTexts.values()], projectRoot, checkedTsConfig))
1541
+ : undefined;
1542
+ const templateErrors = templateErrorsByBatchFile(templates, ownersOf);
1069
1543
  const files = result.files.map((f) => {
1070
- const errors = introduced.get(f.path);
1071
- return errors === undefined
1544
+ const errors = [
1545
+ ...(introduced.get(f.path) ?? []),
1546
+ ...(extrasOf.get(f.path) ?? []).flatMap((extra) => (introduced.get(extra) ?? []).map((e) => `${extra}: ${e}`)),
1547
+ ...(importerErrors.get(f.path) ?? []),
1548
+ ];
1549
+ const fileTemplateErrors = templateErrors.get(f.path) ?? [];
1550
+ const all = [...errors, ...fileTemplateErrors];
1551
+ return all.length === 0
1072
1552
  ? f
1073
1553
  : {
1074
1554
  ...f,
1075
1555
  success: false,
1076
- error: `Type error introduced: ${errors[0]}` +
1077
- (errors.length > 1 ? ` (+${errors.length - 1} more)` : ''),
1556
+ error: `${errors.length > 0 ? 'Type' : 'Template'} error introduced: ${all[0]}` +
1557
+ (all.length > 1 ? ` (+${all.length - 1} more)` : ''),
1078
1558
  };
1079
1559
  });
1080
- const failedFiles = files.filter((f) => !f.success).map((f) => f.path);
1560
+ // The type and template checks above run synchronously: read a cancel
1561
+ // that arrived meanwhile before deciding, or it is seen only after the
1562
+ // answer and the batch stays changed
1563
+ await readCancelAfterBlock(ctx.signal);
1081
1564
  const cancelled = ctx.signal?.aborted === true;
1082
- // A cancelled batch restores every file, whatever the strategy
1083
- const filesToRestore = cancelled
1084
- ? batchOptions.files
1085
- : batchFilesToRestore(batchOptions.rollbackStrategy ?? 'all-or-nothing', batchOptions.files, failedFiles);
1565
+ // Restoring a failed file restores the files it changed to their text
1566
+ // before the call; a file that changed one of them too goes back with it
1567
+ const strategy = batchOptions.rollbackStrategy ?? 'all-or-nothing';
1568
+ const settled = strategy === 'selective' && !cancelled ? failSharingFiles(files, extrasOf) : files;
1569
+ const failedFiles = settled.filter((f) => !f.success).map((f) => f.path);
1570
+ // A cancelled batch restores every file, whatever the strategy; only
1571
+ // files that changed have a backup to restore
1572
+ const backedUp = new Set(backups?.files() ?? []);
1573
+ // Once per file: a file several batch files changed is restored once
1574
+ const filesToRestore = [
1575
+ ...new Set((cancelled ? batchOptions.files : batchFilesToRestore(strategy, batchOptions.files, failedFiles)).flatMap((f) => [f, ...(extrasOf.get(f) ?? [])])),
1576
+ ].filter((f) => backedUp.has(f));
1577
+ const written = backups?.written();
1578
+ const backup = written && {
1579
+ created: true,
1580
+ backupPath: written.backupPaths[0],
1581
+ strategy: 'file-backup',
1582
+ gitSnapshot: written.gitSnapshot,
1583
+ };
1086
1584
  let rollback;
1087
- if (cancelled && createBackup) {
1585
+ let restoredFiles = [];
1586
+ if (cancelled && filesToRestore.length > 0) {
1088
1587
  const attempt = await rollbackManager.rollback(filesToRestore);
1588
+ restoredFiles = attempt.files;
1089
1589
  rollback = {
1090
1590
  performed: true,
1091
1591
  reason: `Cancelled by the client after ${result.files.length} of ${batchOptions.files.length} file(s)`,
1092
1592
  success: attempt.success,
1593
+ files: attempt.files,
1093
1594
  };
1094
1595
  }
1095
- else if (createBackup && failedFiles.length > 0 && filesToRestore.length > 0) {
1596
+ else if (failedFiles.length > 0 && filesToRestore.length > 0) {
1096
1597
  const attempt = await rollbackManager.rollback(filesToRestore);
1598
+ restoredFiles = attempt.files;
1097
1599
  rollback = {
1098
1600
  performed: true,
1099
1601
  reason: `${failedFiles.length} file(s) failed (${batchOptions.rollbackStrategy})`,
1100
1602
  success: attempt.success,
1603
+ files: attempt.files,
1101
1604
  };
1102
1605
  }
1103
- const introducedErrors = [...introduced.values()].flat();
1104
- const introducedList = [...introduced].flatMap(([path, errors]) => errors.map((e) => `${path}: ${e}`));
1606
+ // A restored file has no changes left on disk; a file the rollback could
1607
+ // not restore is still changed
1608
+ const restored = new Set(restoredFiles);
1609
+ const reported = settled.map((f) => restored.has(f.path) ? { ...f, modified: false, changes: { ...NO_CHANGES } } : f);
1610
+ const ruleMessages = [
1611
+ ...new Set(result.files.flatMap((f) => f.ruleMessages ?? [])),
1612
+ ];
1613
+ const importerList = [...new Set([...importerErrors.values()].flat())];
1614
+ const introducedErrors = [...[...introduced.values()].flat(), ...importerList];
1615
+ const introducedList = [
1616
+ ...[...introduced].flatMap(([path, errors]) => errors.map((e) => `${path}: ${e}`)),
1617
+ ...importerList,
1618
+ ];
1619
+ const introducedTemplateList = (templates?.introduced ?? []).map((i) => i.error);
1620
+ // Without validation a changed template is reported as not checked
1621
+ const templateCheck = validateTransformation || batchTexts.size === 0
1622
+ ? templates?.status
1623
+ : await batchKernel.run((kernel) => Promise.resolve(changedTemplateComponents(kernel.getProject(), [...batchTexts.values()]).size > 0 ? 'skipped' : undefined));
1105
1624
  return {
1106
1625
  success: failedFiles.length === 0 && !cancelled,
1107
1626
  backup,
1108
1627
  rollback,
1109
- files,
1628
+ files: reported.map(({ ruleMessages: _messages, syntaxErrors: _syntax, extraFiles: _extra, changedTexts: _texts, ...f }) => f),
1629
+ changedFiles: changedFilesOf(reported, extrasOf, restored),
1630
+ modified: reported.some((f) => f.modified === true),
1631
+ ruleMessages: ruleMessages.length > 0 ? ruleMessages : undefined,
1110
1632
  transformation: params.transformation,
1111
- changes: {
1112
- linesChanged: 0, // Aggregated in batch handler
1113
- additions: 0,
1114
- deletions: 0,
1115
- },
1116
- validation: {
1117
- syntaxValid: !introducedErrors.some((e) => /^TS1\d{3}:/.test(e)),
1118
- typeCheckPassed: introducedErrors.length === 0,
1119
- introducedTypeErrors: introducedList.length > 0 ? introducedList : undefined,
1120
- },
1633
+ changes: sumLineChanges(reported.map((f) => f.changes)),
1634
+ validation: validateTransformation
1635
+ ? {
1636
+ syntaxValid: !introducedErrors.some((e) => /^TS1\d{3}:/.test(e)),
1637
+ typeCheckPassed: introducedErrors.length === 0,
1638
+ typeCheck: introducedErrors.length === 0 ? 'passed' : 'failed',
1639
+ introducedTypeErrors: introducedList.length > 0 ? introducedList : undefined,
1640
+ testTypeErrors: testErrors.length > 0 ? testErrors : undefined,
1641
+ templateCheck,
1642
+ introducedTemplateErrors: introducedTemplateList.length > 0 ? introducedTemplateList : undefined,
1643
+ }
1644
+ : {
1645
+ syntaxValid: result.files.every((f) => (f.syntaxErrors ?? []).length === 0),
1646
+ typeCheckPassed: false,
1647
+ typeCheck: 'skipped',
1648
+ templateCheck,
1649
+ },
1121
1650
  warnings: validateTransformation
1122
- ? undefined
1651
+ ? templates?.warning === undefined
1652
+ ? undefined
1653
+ : [templates.warning]
1123
1654
  : ['Type check skipped (validateTransformation: false).'],
1124
1655
  orchestration: {
1125
1656
  ...result.orchestration,
@@ -1132,9 +1663,9 @@ export class TransformCodeTool {
1132
1663
  /**
1133
1664
  * Transform a single file (internal helper for batch mode).
1134
1665
  */
1135
- async transformSingleFile(filePath, params, batchKernel) {
1666
+ async transformSingleFile(filePath, params, batchKernel, backups, extraErrorsBefore, projectRoot) {
1136
1667
  try {
1137
- return await batchKernel.run((kernel) => transformWithKernel(kernel, filePath, params));
1668
+ return await batchKernel.run((kernel) => transformWithKernel(kernel, filePath, params, backups, extraErrorsBefore, projectRoot));
1138
1669
  }
1139
1670
  catch (error) {
1140
1671
  return {
@@ -1172,31 +1703,6 @@ export class TransformCodeTool {
1172
1703
  // Fallback to current directory
1173
1704
  return '.';
1174
1705
  }
1175
- /**
1176
- * Validate the transformation.
1177
- */
1178
- async validateTransformation(filePath, _transformation) {
1179
- // Basic validation - check if file can be parsed
1180
- const fs = await import('node:fs/promises');
1181
- const content = await fs.readFile(filePath, 'utf-8');
1182
- let syntaxValid = true;
1183
- try {
1184
- // Try to parse as TypeScript
1185
- const ts = await import('typescript');
1186
- ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
1187
- // If we get here without errors, syntax is valid
1188
- }
1189
- catch {
1190
- syntaxValid = false;
1191
- }
1192
- // For now, assume type checking passes if syntax is valid
1193
- // In a real implementation, you'd run tsc or similar
1194
- const typeCheckPassed = syntaxValid;
1195
- return {
1196
- syntaxValid,
1197
- typeCheckPassed,
1198
- };
1199
- }
1200
1706
  /**
1201
1707
  * Get validation schema for a specific transformation type.
1202
1708
  */
@@ -1209,9 +1715,11 @@ export class TransformCodeTool {
1209
1715
  'interface-extraction': {
1210
1716
  description: 'Requires type literals or inline types',
1211
1717
  },
1718
+ // Components, directives, pipes and NgModule files: the rule names
1719
+ // what it found nothing to migrate in
1212
1720
  'standalone-migration': {
1213
- requiresDecorator: 'Component',
1214
- description: 'Requires @Component decorator',
1721
+ requiresClass: true,
1722
+ description: 'Requires a @Component, @Directive, @Pipe or @NgModule class',
1215
1723
  },
1216
1724
  'dependency-injection-migration': {
1217
1725
  requiresDecorator: 'Injectable',
@@ -1219,12 +1727,13 @@ export class TransformCodeTool {
1219
1727
  },
1220
1728
  'facade-pattern': {
1221
1729
  requiresClass: true,
1222
- requiresDecorator: 'Injectable',
1223
- description: 'Requires service class with @Injectable decorator',
1730
+ requiresDecorator: 'Component',
1731
+ description: 'Requires a @Component class with business methods',
1224
1732
  },
1733
+ // Reactive forms: the rule names the FormBuilder members it keeps
1225
1734
  'form-modernization': {
1226
- requiresImport: 'FormsModule',
1227
- description: 'Requires template-driven forms imports',
1735
+ requiresClass: true,
1736
+ description: 'Requires a class with a FormBuilder member',
1228
1737
  },
1229
1738
  'constructor-injection-transform': {
1230
1739
  requiresClass: true,