@angular-modernizer/adapter-mcp 0.3.0 → 1.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 (298) hide show
  1. package/README.md +181 -282
  2. package/dist/cli.js +21 -13
  3. package/dist/core/project-analyzer.d.ts +3 -12
  4. package/dist/core/project-analyzer.js +3 -12
  5. package/dist/index.d.ts +122 -6
  6. package/dist/index.js +49 -5
  7. package/dist/mcp-watcher.d.ts +32 -7
  8. package/dist/mcp-watcher.js +16 -15
  9. package/dist/scan-host/scan-host.d.ts +119 -0
  10. package/dist/scan-host/scan-host.js +376 -0
  11. package/dist/scan-host/scan-protocol.d.ts +35 -0
  12. package/dist/scan-host/scan-protocol.js +6 -0
  13. package/dist/scan-host/scan-worker.d.ts +14 -0
  14. package/dist/scan-host/scan-worker.js +48 -0
  15. package/dist/server/limited-stdio-transport.d.ts +75 -0
  16. package/dist/server/limited-stdio-transport.js +115 -0
  17. package/dist/server/mcp-server.d.ts +20 -18
  18. package/dist/server/mcp-server.js +42 -79
  19. package/dist/server/package-version.d.ts +16 -0
  20. package/dist/server/package-version.js +37 -0
  21. package/dist/server/sdk-server.d.ts +71 -0
  22. package/dist/server/sdk-server.js +113 -0
  23. package/dist/server/tool-registry.d.ts +6 -9
  24. package/dist/server/tool-registry.js +6 -12
  25. package/dist/streaming/progress-store.d.ts +22 -5
  26. package/dist/streaming/progress-store.js +9 -5
  27. package/dist/tools/analyze-build-impact.d.ts +276 -35
  28. package/dist/tools/analyze-build-impact.js +175 -28
  29. package/dist/tools/analyze-core-to-shared.d.ts +176 -16
  30. package/dist/tools/analyze-core-to-shared.js +124 -19
  31. package/dist/tools/analyze-parser-performance.d.ts +209 -15
  32. package/dist/tools/analyze-parser-performance.js +119 -56
  33. package/dist/tools/analyze-project.d.ts +349 -17
  34. package/dist/tools/analyze-project.js +282 -97
  35. package/dist/tools/check-incremental-compatibility.d.ts +74 -12
  36. package/dist/tools/check-incremental-compatibility.js +69 -10
  37. package/dist/tools/collect-feedback.d.ts +225 -21
  38. package/dist/tools/collect-feedback.js +199 -118
  39. package/dist/tools/compare-health.d.ts +413 -0
  40. package/dist/tools/compare-health.js +479 -0
  41. package/dist/tools/extract-libraries.d.ts +200 -24
  42. package/dist/tools/extract-libraries.js +131 -27
  43. package/dist/tools/find-angular-symbol.d.ts +92 -24
  44. package/dist/tools/find-angular-symbol.js +70 -20
  45. package/dist/tools/find-component-hosts.d.ts +603 -27
  46. package/dist/tools/find-component-hosts.js +223 -19
  47. package/dist/tools/find-usages.d.ts +102 -22
  48. package/dist/tools/find-usages.js +81 -21
  49. package/dist/tools/get-bootstrap-execution.d.ts +183 -25
  50. package/dist/tools/get-bootstrap-execution.js +109 -25
  51. package/dist/tools/get-call-graph.d.ts +127 -12
  52. package/dist/tools/get-call-graph.js +84 -19
  53. package/dist/tools/get-operation-progress-tool.d.ts +126 -8
  54. package/dist/tools/get-operation-progress-tool.js +124 -12
  55. package/dist/tools/get-operation-progress.d.ts +27 -1
  56. package/dist/tools/get-operation-progress.js +5 -5
  57. package/dist/tools/helpers/analysis-output.d.ts +182 -0
  58. package/dist/tools/helpers/analysis-output.js +165 -0
  59. package/dist/tools/helpers/batch-kernel.d.ts +14 -0
  60. package/dist/tools/helpers/batch-kernel.js +12 -0
  61. package/dist/tools/helpers/build-schemas.d.ts +36 -0
  62. package/dist/tools/helpers/build-schemas.js +23 -0
  63. package/dist/tools/helpers/citation-file-source.d.ts +10 -0
  64. package/dist/tools/helpers/citation-file-source.js +82 -0
  65. package/dist/tools/helpers/compact-output.d.ts +2 -1
  66. package/dist/tools/helpers/compact-output.js +2 -1
  67. package/dist/tools/helpers/finding-window.d.ts +43 -0
  68. package/dist/tools/helpers/finding-window.js +64 -0
  69. package/dist/tools/helpers/health-delta.d.ts +99 -0
  70. package/dist/tools/helpers/health-delta.js +236 -0
  71. package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
  72. package/dist/tools/helpers/investigation-schemas.js +48 -0
  73. package/dist/tools/helpers/library-imports.d.ts +57 -0
  74. package/dist/tools/helpers/library-imports.js +151 -0
  75. package/dist/tools/helpers/load-source-files.d.ts +30 -0
  76. package/dist/tools/helpers/load-source-files.js +34 -0
  77. package/dist/tools/helpers/output-contract.d.ts +32 -0
  78. package/dist/tools/helpers/output-contract.js +32 -0
  79. package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
  80. package/dist/tools/helpers/platform-root-resolver.js +75 -48
  81. package/dist/tools/helpers/process-output.d.ts +19 -0
  82. package/dist/tools/helpers/process-output.js +31 -0
  83. package/dist/tools/helpers/project-cache.d.ts +60 -37
  84. package/dist/tools/helpers/project-cache.js +54 -37
  85. package/dist/tools/helpers/project-decorators.d.ts +14 -0
  86. package/dist/tools/helpers/project-decorators.js +22 -0
  87. package/dist/tools/helpers/rule-matcher.js +5 -0
  88. package/dist/tools/helpers/rule-runner.d.ts +25 -13
  89. package/dist/tools/helpers/rule-runner.js +45 -24
  90. package/dist/tools/helpers/scan-cache.d.ts +22 -0
  91. package/dist/tools/helpers/scan-cache.js +34 -0
  92. package/dist/tools/helpers/scan-engine.d.ts +107 -0
  93. package/dist/tools/helpers/scan-engine.js +197 -0
  94. package/dist/tools/helpers/scan-plan.d.ts +5 -2
  95. package/dist/tools/helpers/scan-plan.js +18 -3
  96. package/dist/tools/helpers/scope-paths.d.ts +17 -0
  97. package/dist/tools/helpers/scope-paths.js +32 -0
  98. package/dist/tools/helpers/suggestion-generator.d.ts +9 -13
  99. package/dist/tools/helpers/suggestion-generator.js +0 -12
  100. package/dist/tools/helpers/tool-cache.d.ts +11 -0
  101. package/dist/tools/helpers/tool-cache.js +15 -0
  102. package/dist/tools/helpers/tool-context.d.ts +63 -0
  103. package/dist/tools/helpers/tool-context.js +79 -0
  104. package/dist/tools/helpers/transform-safety.d.ts +40 -0
  105. package/dist/tools/helpers/transform-safety.js +87 -0
  106. package/dist/tools/helpers/validation-output.d.ts +53 -0
  107. package/dist/tools/helpers/validation-output.js +48 -0
  108. package/dist/tools/inspect-form-group.d.ts +262 -24
  109. package/dist/tools/inspect-form-group.js +134 -13
  110. package/dist/tools/inspect-i18n.d.ts +410 -23
  111. package/dist/tools/inspect-i18n.js +213 -13
  112. package/dist/tools/inspect-template.d.ts +260 -22
  113. package/dist/tools/inspect-template.js +174 -13
  114. package/dist/tools/learn-patterns.d.ts +210 -13
  115. package/dist/tools/learn-patterns.js +113 -12
  116. package/dist/tools/list-imports.d.ts +152 -34
  117. package/dist/tools/list-imports.js +124 -18
  118. package/dist/tools/orchestrate-migration.d.ts +159 -14
  119. package/dist/tools/orchestrate-migration.js +147 -20
  120. package/dist/tools/parse-stack-trace.d.ts +78 -21
  121. package/dist/tools/parse-stack-trace.js +44 -7
  122. package/dist/tools/plan-migration.d.ts +395 -26
  123. package/dist/tools/plan-migration.js +173 -22
  124. package/dist/tools/resolve-type.d.ts +57 -9
  125. package/dist/tools/resolve-type.js +49 -12
  126. package/dist/tools/review-feedback.d.ts +214 -16
  127. package/dist/tools/review-feedback.js +142 -57
  128. package/dist/tools/rollback-changes.d.ts +88 -7
  129. package/dist/tools/rollback-changes.js +74 -19
  130. package/dist/tools/run-angular-cli.d.ts +57 -12
  131. package/dist/tools/run-angular-cli.js +76 -13
  132. package/dist/tools/run-build.d.ts +127 -13
  133. package/dist/tools/run-build.js +128 -16
  134. package/dist/tools/run-schematic.d.ts +82 -12
  135. package/dist/tools/run-schematic.js +115 -18
  136. package/dist/tools/scan-all.d.ts +88 -23
  137. package/dist/tools/scan-all.js +161 -220
  138. package/dist/tools/scan-angular.d.ts +60 -19
  139. package/dist/tools/scan-angular.js +100 -141
  140. package/dist/tools/scan-architecture.d.ts +92 -24
  141. package/dist/tools/scan-architecture.js +268 -211
  142. package/dist/tools/scan-solid.d.ts +59 -19
  143. package/dist/tools/scan-solid.js +98 -139
  144. package/dist/tools/search-codebase.d.ts +110 -23
  145. package/dist/tools/search-codebase.js +67 -11
  146. package/dist/tools/server-status.d.ts +392 -26
  147. package/dist/tools/server-status.js +260 -27
  148. package/dist/tools/suggest-improvements.d.ts +105 -10
  149. package/dist/tools/suggest-improvements.js +91 -51
  150. package/dist/tools/trace-output-flow.d.ts +713 -26
  151. package/dist/tools/trace-output-flow.js +396 -33
  152. package/dist/tools/transform-code-batch.d.ts +3 -0
  153. package/dist/tools/transform-code-batch.js +10 -5
  154. package/dist/tools/transform-code.d.ts +402 -18
  155. package/dist/tools/transform-code.js +708 -649
  156. package/dist/tools/validate-before-transform.d.ts +136 -7
  157. package/dist/tools/validate-before-transform.js +65 -9
  158. package/dist/tools/validate-project-compatibility.d.ts +82 -15
  159. package/dist/tools/validate-project-compatibility.js +84 -15
  160. package/dist/tools/validate-transformation.d.ts +243 -8
  161. package/dist/tools/validate-transformation.js +127 -23
  162. package/dist/tools/verify-citations.d.ts +202 -0
  163. package/dist/tools/verify-citations.js +221 -0
  164. package/dist/types.d.ts +78 -11
  165. package/dist/types.js +0 -5
  166. package/dist/utils/format-tool-response.d.ts +22 -59
  167. package/dist/utils/format-tool-response.js +25 -134
  168. package/package.json +31 -20
  169. package/dist/cli.d.ts.map +0 -1
  170. package/dist/cli.js.map +0 -1
  171. package/dist/core/project-analyzer.d.ts.map +0 -1
  172. package/dist/core/project-analyzer.js.map +0 -1
  173. package/dist/index.d.ts.map +0 -1
  174. package/dist/index.js.map +0 -1
  175. package/dist/mcp-watcher.d.ts.map +0 -1
  176. package/dist/mcp-watcher.js.map +0 -1
  177. package/dist/server/json-rpc-handler.d.ts +0 -98
  178. package/dist/server/json-rpc-handler.d.ts.map +0 -1
  179. package/dist/server/json-rpc-handler.js +0 -301
  180. package/dist/server/json-rpc-handler.js.map +0 -1
  181. package/dist/server/mcp-server.d.ts.map +0 -1
  182. package/dist/server/mcp-server.js.map +0 -1
  183. package/dist/server/stdio-guard.d.ts.map +0 -1
  184. package/dist/server/stdio-guard.js.map +0 -1
  185. package/dist/server/tool-registry.d.ts.map +0 -1
  186. package/dist/server/tool-registry.js.map +0 -1
  187. package/dist/streaming/progress-store.d.ts.map +0 -1
  188. package/dist/streaming/progress-store.js.map +0 -1
  189. package/dist/tools/analyze-build-impact.d.ts.map +0 -1
  190. package/dist/tools/analyze-build-impact.js.map +0 -1
  191. package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
  192. package/dist/tools/analyze-core-to-shared.js.map +0 -1
  193. package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
  194. package/dist/tools/analyze-parser-performance.js.map +0 -1
  195. package/dist/tools/analyze-project.d.ts.map +0 -1
  196. package/dist/tools/analyze-project.js.map +0 -1
  197. package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
  198. package/dist/tools/check-incremental-compatibility.js.map +0 -1
  199. package/dist/tools/collect-feedback.d.ts.map +0 -1
  200. package/dist/tools/collect-feedback.js.map +0 -1
  201. package/dist/tools/extract-libraries.d.ts.map +0 -1
  202. package/dist/tools/extract-libraries.js.map +0 -1
  203. package/dist/tools/find-angular-symbol.d.ts.map +0 -1
  204. package/dist/tools/find-angular-symbol.js.map +0 -1
  205. package/dist/tools/find-component-hosts.d.ts.map +0 -1
  206. package/dist/tools/find-component-hosts.js.map +0 -1
  207. package/dist/tools/find-usages.d.ts.map +0 -1
  208. package/dist/tools/find-usages.js.map +0 -1
  209. package/dist/tools/get-bootstrap-execution.d.ts.map +0 -1
  210. package/dist/tools/get-bootstrap-execution.js.map +0 -1
  211. package/dist/tools/get-call-graph.d.ts.map +0 -1
  212. package/dist/tools/get-call-graph.js.map +0 -1
  213. package/dist/tools/get-operation-progress-tool.d.ts.map +0 -1
  214. package/dist/tools/get-operation-progress-tool.js.map +0 -1
  215. package/dist/tools/get-operation-progress.d.ts.map +0 -1
  216. package/dist/tools/get-operation-progress.js.map +0 -1
  217. package/dist/tools/helpers/compact-output.d.ts.map +0 -1
  218. package/dist/tools/helpers/compact-output.js.map +0 -1
  219. package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
  220. package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
  221. package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
  222. package/dist/tools/helpers/find-ts-config.js.map +0 -1
  223. package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
  224. package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
  225. package/dist/tools/helpers/project-cache.d.ts.map +0 -1
  226. package/dist/tools/helpers/project-cache.js.map +0 -1
  227. package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
  228. package/dist/tools/helpers/rule-matcher.js.map +0 -1
  229. package/dist/tools/helpers/rule-runner.d.ts.map +0 -1
  230. package/dist/tools/helpers/rule-runner.js.map +0 -1
  231. package/dist/tools/helpers/scan-plan.d.ts.map +0 -1
  232. package/dist/tools/helpers/scan-plan.js.map +0 -1
  233. package/dist/tools/helpers/stack-frame-file-index.d.ts.map +0 -1
  234. package/dist/tools/helpers/stack-frame-file-index.js.map +0 -1
  235. package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
  236. package/dist/tools/helpers/suggestion-generator.js.map +0 -1
  237. package/dist/tools/inspect-form-group.d.ts.map +0 -1
  238. package/dist/tools/inspect-form-group.js.map +0 -1
  239. package/dist/tools/inspect-i18n.d.ts.map +0 -1
  240. package/dist/tools/inspect-i18n.js.map +0 -1
  241. package/dist/tools/inspect-template.d.ts.map +0 -1
  242. package/dist/tools/inspect-template.js.map +0 -1
  243. package/dist/tools/learn-patterns.d.ts.map +0 -1
  244. package/dist/tools/learn-patterns.js.map +0 -1
  245. package/dist/tools/list-imports.d.ts.map +0 -1
  246. package/dist/tools/list-imports.js.map +0 -1
  247. package/dist/tools/orchestrate-migration.d.ts.map +0 -1
  248. package/dist/tools/orchestrate-migration.js.map +0 -1
  249. package/dist/tools/parse-stack-trace.d.ts.map +0 -1
  250. package/dist/tools/parse-stack-trace.js.map +0 -1
  251. package/dist/tools/plan-migration.d.ts.map +0 -1
  252. package/dist/tools/plan-migration.js.map +0 -1
  253. package/dist/tools/resolve-type.d.ts.map +0 -1
  254. package/dist/tools/resolve-type.js.map +0 -1
  255. package/dist/tools/review-feedback.d.ts.map +0 -1
  256. package/dist/tools/review-feedback.js.map +0 -1
  257. package/dist/tools/rollback-changes.d.ts.map +0 -1
  258. package/dist/tools/rollback-changes.js.map +0 -1
  259. package/dist/tools/run-angular-cli.d.ts.map +0 -1
  260. package/dist/tools/run-angular-cli.js.map +0 -1
  261. package/dist/tools/run-build.d.ts.map +0 -1
  262. package/dist/tools/run-build.js.map +0 -1
  263. package/dist/tools/run-schematic.d.ts.map +0 -1
  264. package/dist/tools/run-schematic.js.map +0 -1
  265. package/dist/tools/scan-all.d.ts.map +0 -1
  266. package/dist/tools/scan-all.js.map +0 -1
  267. package/dist/tools/scan-angular.d.ts.map +0 -1
  268. package/dist/tools/scan-angular.js.map +0 -1
  269. package/dist/tools/scan-architecture.d.ts.map +0 -1
  270. package/dist/tools/scan-architecture.js.map +0 -1
  271. package/dist/tools/scan-solid.d.ts.map +0 -1
  272. package/dist/tools/scan-solid.js.map +0 -1
  273. package/dist/tools/search-codebase.d.ts.map +0 -1
  274. package/dist/tools/search-codebase.js.map +0 -1
  275. package/dist/tools/server-status.d.ts.map +0 -1
  276. package/dist/tools/server-status.js.map +0 -1
  277. package/dist/tools/shared/scan-types.d.ts +0 -200
  278. package/dist/tools/shared/scan-types.d.ts.map +0 -1
  279. package/dist/tools/shared/scan-types.js +0 -7
  280. package/dist/tools/shared/scan-types.js.map +0 -1
  281. package/dist/tools/suggest-improvements.d.ts.map +0 -1
  282. package/dist/tools/suggest-improvements.js.map +0 -1
  283. package/dist/tools/trace-output-flow.d.ts.map +0 -1
  284. package/dist/tools/trace-output-flow.js.map +0 -1
  285. package/dist/tools/transform-code-batch.d.ts.map +0 -1
  286. package/dist/tools/transform-code-batch.js.map +0 -1
  287. package/dist/tools/transform-code.d.ts.map +0 -1
  288. package/dist/tools/transform-code.js.map +0 -1
  289. package/dist/tools/validate-before-transform.d.ts.map +0 -1
  290. package/dist/tools/validate-before-transform.js.map +0 -1
  291. package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
  292. package/dist/tools/validate-project-compatibility.js.map +0 -1
  293. package/dist/tools/validate-transformation.d.ts.map +0 -1
  294. package/dist/tools/validate-transformation.js.map +0 -1
  295. package/dist/types.d.ts.map +0 -1
  296. package/dist/types.js.map +0 -1
  297. package/dist/utils/format-tool-response.d.ts.map +0 -1
  298. package/dist/utils/format-tool-response.js.map +0 -1
@@ -1,11 +1,7 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Transform Code Tool
3
- *
4
- * MCP tool for performing surgical code transformations to fix
5
- * architectural issues, including standalone component migration.
6
- */
1
+ import { yieldIfCancellable } from './helpers/tool-context.js';
7
2
  import { findTsConfig } from './helpers/find-ts-config.js';
8
- import { Kernel, FluentKernel, BackupManager, RollbackManager, PreTransformValidator, PostTransformValidator, StreamingKernelWrapper, loadConfig, } from '@angular-modernizer/core';
3
+ import { createBatchKernel } from './helpers/batch-kernel.js';
4
+ import { Kernel, FluentKernel, PreTransformValidator, PostTransformValidator, ValidationSeverity, ValidationType, loadConfig, } from '@angular-modernizer/core';
9
5
  import { AngularPlugin } from '@angular-modernizer/plugin-angular';
10
6
  import { readFileSync } from 'node:fs';
11
7
  import { resolve } from 'node:path';
@@ -13,15 +9,203 @@ import { randomUUID } from 'node:crypto';
13
9
  import { executeBatchTransformation, } from './transform-code-batch.js';
14
10
  import { ProgressStore } from '../streaming/progress-store.js';
15
11
  import { getAvailableRules, findSimilarRules } from './helpers/rule-matcher.js';
12
+ import { createProjectRollbackManager, fileTypeErrors, introducedTypeErrors, } from './helpers/transform-safety.js';
16
13
  import { cpus } from 'node:os';
14
+ import { STRING_ARRAY } from './helpers/investigation-schemas.js';
15
+ /** Transformations applied by plugin-angular (its rules check `transformationType`). */
16
+ const PLUGIN_ANGULAR_TRANSFORMATIONS = new Set([
17
+ 'constructor-to-inject',
18
+ 'interface-extraction',
19
+ 'dependency-injection-migration',
20
+ 'facade-pattern',
21
+ 'form-modernization',
22
+ 'constructor-injection-transform',
23
+ 'component-inputs-interface-extraction',
24
+ 'service-injection-cleanup',
25
+ 'container-presentational',
26
+ 'core-shared-modules',
27
+ 'inheritance-to-composition',
28
+ 'promise-service-to-observable',
29
+ 'promise-component-to-reactive',
30
+ 'promise-cleanup',
31
+ 'sequential-await-to-forkjoin',
32
+ 'missing-output-transform',
33
+ 'subscription-transform',
34
+ 'library-extraction',
35
+ 'service-bag-transform',
36
+ 'any-to-interface',
37
+ 'dto-object-literal',
38
+ 'interface-duplication',
39
+ 'static-class-to-functions',
40
+ 'extract-static-from-stateful',
41
+ 'type-safety',
42
+ ]);
43
+ /**
44
+ * Plugin config of a transformation: the plugins read `transformationType`
45
+ * and the transformation options under their own package name.
46
+ */
47
+ export function pluginConfigFor(transformation, options) {
48
+ return {
49
+ '@angular-modernizer/plugin-standalone': {
50
+ transformationType: transformation === 'standalone-migration' ? transformation : undefined,
51
+ ...options,
52
+ },
53
+ '@angular-modernizer/plugin-angular': {
54
+ transformationType: transformation !== undefined &&
55
+ PLUGIN_ANGULAR_TRANSFORMATIONS.has(transformation)
56
+ ? transformation
57
+ : undefined,
58
+ ...options,
59
+ },
60
+ };
61
+ }
62
+ /** Warnings and failed batch files spelled out in the summary. */
63
+ const SUMMARY_WARNINGS = 5;
64
+ const SUMMARY_FAILED_FILES = 10;
65
+ /** Backup and rollback part of the summary. */
66
+ function describeSafety(result) {
67
+ const lines = [];
68
+ if (result.backup?.created === true) {
69
+ lines.push(`Backup: ${result.backup.backupPath ?? result.backup.strategy}` +
70
+ (result.backup.gitSnapshot === undefined
71
+ ? ''
72
+ : ` (git snapshot ${result.backup.gitSnapshot})`) +
73
+ '.');
74
+ }
75
+ if (result.rollback?.performed === true) {
76
+ lines.push(`Rolled back${result.rollback.success === false ? ' (rollback failed)' : ''}: ` +
77
+ `${result.rollback.reason ?? 'no reason given'}.`);
78
+ }
79
+ return lines;
80
+ }
81
+ /** Text summary of a single-file, batch or background transformation. */
82
+ function describeTransformation(result) {
83
+ if (result.operationId !== undefined) {
84
+ return (`${result.transformation} started in the background as operation ${result.operationId}; ` +
85
+ 'get-operation-progress (deprecated) returns the result once it is completed.');
86
+ }
87
+ const outcome = result.success ? 'succeeded' : 'failed';
88
+ const lines = [];
89
+ if (result.files !== undefined) {
90
+ const failed = result.files.filter((f) => !f.success);
91
+ const duration = result.orchestration?.duration;
92
+ lines.push(`${result.transformation} ${outcome} on ${result.files.length} file(s): ` +
93
+ `${result.files.length - failed.length} succeeded, ${failed.length} failed` +
94
+ (duration === undefined ? '.' : ` in ${duration} ms.`));
95
+ lines.push(...describeSafety(result));
96
+ lines.push(...failed
97
+ .slice(0, SUMMARY_FAILED_FILES)
98
+ .map((f) => `- ${f.path}${f.error === undefined ? '' : `: ${f.error}`}`));
99
+ return lines.join('\n');
100
+ }
101
+ const c = result.changes;
102
+ const introduced = result.validation.introducedTypeErrors ?? [];
103
+ lines.push(`${result.transformation} ${outcome} on ${result.filePath ?? 'unknown file'}: ` +
104
+ `${c.linesChanged} line(s) changed (+${c.additions}/-${c.deletions}); ` +
105
+ `type check ${result.validation.typeCheckPassed ? 'passed' : 'failed'}` +
106
+ (introduced.length > 0
107
+ ? ` (${introduced.length} introduced type error(s))`
108
+ : '') +
109
+ (result.buildValidation === undefined
110
+ ? ''
111
+ : `; build ${result.buildValidation.passed ? 'passed' : 'failed'}`) +
112
+ '.');
113
+ lines.push(...describeSafety(result));
114
+ lines.push(...introduced.slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`));
115
+ const warnings = result.warnings ?? [];
116
+ if (warnings.length > 0) {
117
+ lines.push(`${warnings.length} warning(s):`);
118
+ lines.push(...warnings.slice(0, SUMMARY_WARNINGS).map((w) => `- ${w}`));
119
+ }
120
+ return lines.join('\n');
121
+ }
17
122
  /**
18
123
  * MCP tool for code transformations.
19
124
  */
125
+ /** Loads the kernel a batch shares: the project's tsconfig program with the Angular plugin. */
126
+ async function loadBatchKernel(projectRoot) {
127
+ const tsConfigPath = findTsConfig(projectRoot);
128
+ if (!tsConfigPath) {
129
+ throw new Error('Could not find tsconfig.json');
130
+ }
131
+ const kernel = new Kernel({
132
+ tsConfigPath,
133
+ plugins: [new AngularPlugin()],
134
+ });
135
+ await kernel.initialize();
136
+ return kernel;
137
+ }
138
+ /** Transforms one batch file on the shared kernel and saves it. */
139
+ async function transformWithKernel(kernel, filePath, params) {
140
+ const project = kernel.getProject();
141
+ const sourceFile = project.getSourceFile(filePath) ?? project.addSourceFileAtPath(filePath);
142
+ const linesBefore = sourceFile.getFullText().split('\n').length;
143
+ const result = (await kernel.transformFile(sourceFile, {
144
+ dryRun: false,
145
+ autoSave: true,
146
+ pluginConfig: pluginConfigFor(params.transformation, params.options),
147
+ }));
148
+ await sourceFile.save();
149
+ const linesAfter = sourceFile.getFullText().split('\n').length;
150
+ return {
151
+ success: result.success,
152
+ changes: {
153
+ linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
154
+ additions: Math.max(0, linesAfter - linesBefore),
155
+ deletions: Math.max(0, linesBefore - linesAfter),
156
+ },
157
+ };
158
+ }
159
+ /**
160
+ * Files a batch restores after a failure: all-or-nothing every file,
161
+ * selective only the failed ones, none nothing.
162
+ */
163
+ function batchFilesToRestore(strategy, allFiles, failedFiles) {
164
+ switch (strategy) {
165
+ case 'all-or-nothing':
166
+ return allFiles;
167
+ case 'selective':
168
+ return failedFiles;
169
+ case 'none':
170
+ return [];
171
+ }
172
+ }
173
+ /** Thrown between the steps of a single-file run when the client cancelled. */
174
+ class TransformCancelledError extends Error {
175
+ constructor() {
176
+ super('Transformation cancelled by the client');
177
+ }
178
+ }
179
+ /**
180
+ * MCP tool `transform-code`: applies one of the transformation types to a
181
+ * file (or, with `files`, to a batch) to fix architectural issues, including
182
+ * standalone component migration.
183
+ *
184
+ * @remarks
185
+ * Runs inside a safety envelope: pre-validation, a backup in the project
186
+ * (file copy plus git snapshot inside a repository) that rollback-changes can
187
+ * restore, a type check of the transformed file that rolls back on newly
188
+ * introduced errors (`autoRollback`, default true), and an optional build or
189
+ * lint check. A cancelled call restores the backup.
190
+ */
20
191
  export class TransformCodeTool {
21
192
  name = 'transform-code';
22
- description = 'Apply surgical code transformations to fix architectural issues';
193
+ title = 'Transform Code';
194
+ annotations = {
195
+ readOnlyHint: false,
196
+ destructiveHint: true,
197
+ idempotentHint: false,
198
+ openWorldHint: false,
199
+ };
200
+ description = 'Apply surgical code transformations to fix architectural issues. ' +
201
+ 'summary is a short text with the outcome, the changes, the type check, backup and rollback.';
202
+ /**
203
+ * JSON Schema of the tool arguments.
204
+ * @hidden
205
+ */
23
206
  inputSchema = {
24
207
  type: 'object',
208
+ additionalProperties: false,
25
209
  properties: {
26
210
  filePath: {
27
211
  type: 'string',
@@ -55,11 +239,18 @@ export class TransformCodeTool {
55
239
  'missing-output-transform',
56
240
  'subscription-transform',
57
241
  'library-extraction',
242
+ 'service-bag-transform',
243
+ 'any-to-interface',
244
+ 'dto-object-literal',
245
+ 'interface-duplication',
246
+ 'static-class-to-functions',
247
+ 'extract-static-from-stateful',
248
+ 'type-safety',
58
249
  ],
59
250
  },
60
251
  options: {
61
252
  type: 'object',
62
- description: 'Transformation-specific options',
253
+ 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',
63
254
  },
64
255
  validateBeforeTransform: {
65
256
  type: 'boolean',
@@ -73,7 +264,7 @@ export class TransformCodeTool {
73
264
  },
74
265
  validateTransformation: {
75
266
  type: 'boolean',
76
- description: 'Whether to validate transformation results (default: true)',
267
+ description: 'Whether to validate transformation results (default: true): type check of the transformed file (new errors only), plus build and lint when enabled',
77
268
  default: true,
78
269
  },
79
270
  autoRollback: {
@@ -145,13 +336,13 @@ export class TransformCodeTool {
145
336
  },
146
337
  streaming: {
147
338
  type: 'boolean',
148
- description: 'Enable streaming mode - returns operationId immediately for polling progress. When true, transformation runs in background and progress can be queried via get-operation-progress tool.',
149
- default: true,
339
+ 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.',
340
+ default: false,
150
341
  },
151
342
  diffFormat: {
152
343
  type: 'string',
153
344
  enum: ['unified', 'structured', 'both'],
154
- description: 'Format for diff output in streaming mode. "structured" (default) provides AI-parseable diffs with semantic annotations including Angular file type detection, syntax type annotations, and transformation intent. "unified" provides traditional unified diffs. "both" includes both formats simultaneously.',
345
+ description: 'No effect: streaming runs the regular transformation in the background and emits no diff events. Kept so existing calls stay valid.',
155
346
  default: 'structured',
156
347
  },
157
348
  apiStyle: {
@@ -167,8 +358,13 @@ export class TransformCodeTool {
167
358
  },
168
359
  validateBuild: {
169
360
  type: 'boolean',
170
- description: 'Whether to validate the build after transformation (default: true). Runs the project build to ensure code compiles after transformation.',
171
- default: true,
361
+ description: 'Whether to run the project build after transformation (default: false). The transformed file is type-checked either way and rolled back on new type errors; the build runs build.command of .angular-modernizer.json (or the detected build system) and can take minutes on a large app.',
362
+ default: false,
363
+ },
364
+ validateLint: {
365
+ type: 'boolean',
366
+ 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.",
367
+ default: false,
172
368
  },
173
369
  rollbackOnBuildFailure: {
174
370
  type: 'boolean',
@@ -187,7 +383,157 @@ export class TransformCodeTool {
187
383
  },
188
384
  required: ['transformation'],
189
385
  };
190
- async execute(args) {
386
+ /**
387
+ * JSON Schema of the tool result (`structuredContent`).
388
+ * @hidden
389
+ */
390
+ outputSchema = {
391
+ type: 'object',
392
+ properties: {
393
+ operationId: { type: 'string' },
394
+ success: { type: 'boolean' },
395
+ filePath: { type: 'string' },
396
+ files: {
397
+ type: 'array',
398
+ items: {
399
+ type: 'object',
400
+ properties: {
401
+ path: { type: 'string' },
402
+ success: { type: 'boolean' },
403
+ error: { type: 'string' },
404
+ },
405
+ required: ['path', 'success'],
406
+ },
407
+ },
408
+ transformation: { type: 'string' },
409
+ changes: {
410
+ type: 'object',
411
+ properties: {
412
+ linesChanged: { type: 'integer' },
413
+ additions: { type: 'integer' },
414
+ deletions: { type: 'integer' },
415
+ },
416
+ required: ['linesChanged', 'additions', 'deletions'],
417
+ },
418
+ preValidation: {
419
+ type: 'object',
420
+ properties: {
421
+ valid: { type: 'boolean' },
422
+ issues: {
423
+ type: 'array',
424
+ items: {
425
+ type: 'object',
426
+ properties: {
427
+ type: { type: 'string' },
428
+ severity: { type: 'string' },
429
+ message: { type: 'string' },
430
+ filePath: { type: 'string' },
431
+ line: { type: 'integer' },
432
+ column: { type: 'integer' },
433
+ },
434
+ required: ['type', 'severity', 'message'],
435
+ },
436
+ },
437
+ },
438
+ required: ['valid', 'issues'],
439
+ },
440
+ validation: {
441
+ type: 'object',
442
+ properties: {
443
+ syntaxValid: { type: 'boolean' },
444
+ typeCheckPassed: { type: 'boolean' },
445
+ testsPass: { type: 'boolean' },
446
+ introducedTypeErrors: STRING_ARRAY,
447
+ },
448
+ required: ['syntaxValid', 'typeCheckPassed'],
449
+ },
450
+ backup: {
451
+ type: 'object',
452
+ properties: {
453
+ created: { type: 'boolean' },
454
+ backupPath: { type: 'string' },
455
+ strategy: { type: 'string', enum: ['git-stash', 'file-backup'] },
456
+ gitSnapshot: { type: 'string' },
457
+ },
458
+ required: ['created', 'strategy'],
459
+ },
460
+ rollback: {
461
+ type: 'object',
462
+ properties: {
463
+ performed: { type: 'boolean' },
464
+ reason: { type: 'string' },
465
+ success: { type: 'boolean' },
466
+ },
467
+ required: ['performed'],
468
+ },
469
+ warnings: {
470
+ type: 'array',
471
+ items: { type: 'string' },
472
+ description: 'Warnings of the transformation and its validation.',
473
+ },
474
+ orchestration: {
475
+ type: 'object',
476
+ properties: {
477
+ parallel: { type: 'boolean' },
478
+ batchMode: { type: 'boolean' },
479
+ filesProcessed: { type: 'integer' },
480
+ filesSucceeded: { type: 'integer' },
481
+ filesFailed: { type: 'integer' },
482
+ duration: { type: 'number' },
483
+ throughput: { type: 'number' },
484
+ },
485
+ },
486
+ progress: {
487
+ type: 'object',
488
+ properties: {
489
+ current: { type: 'number' },
490
+ total: { type: 'number' },
491
+ percentage: { type: 'number' },
492
+ eta: { type: 'number' },
493
+ phase: { type: 'string' },
494
+ },
495
+ },
496
+ pipeline: STRING_ARRAY,
497
+ intermediateResults: {
498
+ type: 'object',
499
+ additionalProperties: {
500
+ type: 'object',
501
+ properties: {
502
+ success: { type: 'boolean' },
503
+ violations: { type: 'number' },
504
+ filesProcessed: { type: 'number' },
505
+ message: { type: 'string' },
506
+ },
507
+ required: ['success'],
508
+ },
509
+ },
510
+ buildValidation: {
511
+ type: 'object',
512
+ properties: {
513
+ passed: { type: 'boolean' },
514
+ success: { type: 'boolean' },
515
+ exitCode: { type: 'integer' },
516
+ errors: STRING_ARRAY,
517
+ warnings: STRING_ARRAY,
518
+ duration: { type: 'number' },
519
+ buildCommand: { type: 'string' },
520
+ buildSystem: { type: 'string' },
521
+ timedOut: { type: 'boolean' },
522
+ },
523
+ required: ['passed', 'success'],
524
+ },
525
+ rolledBack: { type: 'boolean' },
526
+ backupId: { type: 'string' },
527
+ rollbackReason: { type: 'string' },
528
+ summary: { type: 'string' },
529
+ },
530
+ required: ['success', 'transformation', 'changes', 'validation', 'summary'],
531
+ };
532
+ async execute(args, ctx = {}) {
533
+ const result = await this.runTransform(args, ctx);
534
+ return { ...result, summary: describeTransformation(result) };
535
+ }
536
+ async runTransform(args, ctx) {
191
537
  const params = args;
192
538
  // Validate that either filePath or files is provided
193
539
  if (!params.filePath && (!params.files || params.files.length === 0)) {
@@ -196,8 +542,8 @@ export class TransformCodeTool {
196
542
  if (params.filePath && params.files && params.files.length > 0) {
197
543
  throw new Error('Cannot specify both filePath and files - choose either single file or batch mode');
198
544
  }
199
- // Check if streaming mode is enabled (default: true)
200
- const streaming = params.streaming ?? true;
545
+ // Streaming runs the same path in the background (default: false)
546
+ const streaming = params.streaming ?? false;
201
547
  if (streaming) {
202
548
  // Streaming mode - start operation in background and return operationId
203
549
  return this.executeStreaming(params);
@@ -222,9 +568,9 @@ export class TransformCodeTool {
222
568
  }
223
569
  if (isBatchMode) {
224
570
  // Batch mode - delegate to batch transformation handler
225
- return this.executeBatch(params, orchestration);
571
+ return this.executeBatch(params, orchestration, ctx);
226
572
  }
227
- // Original single-file mode logic
573
+ // Single-file mode
228
574
  const filePath = params.filePath;
229
575
  const transformation = params.transformation;
230
576
  if (!filePath || typeof filePath !== 'string') {
@@ -235,537 +581,344 @@ export class TransformCodeTool {
235
581
  const fullConfig = loadConfig(projectRoot);
236
582
  const config = fullConfig.tools?.['transform-code'] ?? {};
237
583
  const mergedParams = { ...config, ...params };
238
- const options = mergedParams.options ?? {};
239
- const validateBeforeTransform = mergedParams.validateBeforeTransform ?? true;
240
- const createBackup = mergedParams.createBackup ?? true;
241
- const validateTransformation = mergedParams.validateTransformation ?? true;
242
- const autoRollback = mergedParams.autoRollback ?? true;
243
- const backupDir = mergedParams.backupDir;
244
- const apiStyle = mergedParams.apiStyle ?? 'fluent';
245
- const buildCheck = mergedParams.buildCheck ?? false;
246
- const validateBuild = mergedParams.validateBuild ?? true;
247
- const rollbackOnBuildFailure = mergedParams.rollbackOnBuildFailure ?? true;
248
- const buildTimeout = mergedParams.buildTimeout ?? 300000;
249
584
  if (typeof transformation !== 'string') {
250
585
  throw new TypeError('transformation is required and must be a string');
251
586
  }
252
587
  // Validate that the transformation type exists in the schema
253
588
  this.validateTransformationType(transformation);
254
- // Use fluent API if requested
255
- if (apiStyle === 'fluent') {
256
- return this.executeWithFluentApi(filePath, transformation, options, {
257
- validateBeforeTransform,
258
- createBackup,
259
- validateTransformation,
260
- autoRollback,
261
- backupDir,
262
- buildCheck,
263
- validateBuild,
264
- rollbackOnBuildFailure,
265
- buildTimeout,
266
- projectRoot,
267
- });
268
- }
589
+ return this.executeSingleFile(filePath, transformation, mergedParams.options ?? {}, {
590
+ apiStyle: mergedParams.apiStyle ?? 'fluent',
591
+ validateBeforeTransform: mergedParams.validateBeforeTransform ?? true,
592
+ createBackup: mergedParams.createBackup ?? true,
593
+ validateTransformation: mergedParams.validateTransformation ?? true,
594
+ autoRollback: mergedParams.autoRollback ?? true,
595
+ backupDir: mergedParams.backupDir,
596
+ buildCheck: mergedParams.buildCheck ?? false,
597
+ validateBuild: mergedParams.validateBuild ?? false,
598
+ validateLint: mergedParams.validateLint ?? false,
599
+ buildTimeout: mergedParams.buildTimeout ?? 300000,
600
+ projectRoot,
601
+ signal: ctx.signal,
602
+ progress: ctx.progress,
603
+ });
604
+ }
605
+ /**
606
+ * Transform one file inside the safety envelope: one kernel load,
607
+ * pre-validation, backup (file plus git snapshot), transformation (fluent
608
+ * or imperative), type check of the file against its errors before the
609
+ * transformation, optional build and lint, rollback on failure.
610
+ */
611
+ async executeSingleFile(filePath, transformation, options, config) {
269
612
  let preValidationResult;
270
613
  let backupResult;
271
- let validationResult;
272
614
  let rollbackResult;
615
+ const rollbackManager = createProjectRollbackManager(config.projectRoot, {
616
+ backupDir: config.backupDir,
617
+ });
273
618
  try {
274
- // Step 0: Pre-validate if requested
275
- if (validateBeforeTransform) {
276
- const tsConfigPath = findTsConfig(projectRoot);
277
- if (!tsConfigPath) {
278
- throw new Error('Could not find tsconfig.json in the project root');
279
- }
280
- // Create a temporary kernel for pre-validation with caching
281
- const tempKernel = new Kernel({
282
- tsConfigPath,
283
- plugins: [new AngularPlugin()],
284
- cacheConfig: {
285
- enabled: true,
286
- cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
287
- maxSize: 100 * 1024 * 1024, // 100MB
288
- maxAge: 24 * 60 * 60 * 1000, // 24 hours
289
- compression: true,
290
- },
291
- });
292
- await tempKernel.initialize();
293
- const project = tempKernel.getProject();
294
- const sourceFile = project.addSourceFileAtPath(filePath);
295
- // Create pre-validator and config
296
- const preValidator = new PreTransformValidator();
297
- const preValidationConfig = {
298
- validateSyntax: true,
299
- validateDependencies: true,
300
- validateTypes: true,
301
- validateSchema: true,
302
- schema: this.getSchemaForTransformation(transformation),
303
- };
304
- const result = await preValidator.validate(sourceFile, project, preValidationConfig);
305
- preValidationResult = {
306
- valid: result.valid,
307
- issues: result.issues.map((issue) => ({
308
- type: issue.type,
309
- severity: issue.severity,
310
- message: issue.message,
311
- filePath: issue.filePath,
312
- line: issue.line,
313
- column: issue.column,
314
- })),
315
- };
316
- // If pre-validation fails, stop here (no backup needed)
317
- if (!result.valid) {
318
- throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
319
- `Cannot safely transform file. Please fix these issues first:\n` +
320
- result.issues
321
- .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
322
- .join('\n'));
323
- }
324
- }
325
- // Step 1: Create backup if requested
326
- if (createBackup) {
327
- const backupManager = new BackupManager(backupDir);
328
- backupResult = await backupManager.backup(filePath);
329
- if (!backupResult.success) {
330
- throw new Error('Failed to create backup before transformation');
331
- }
332
- }
333
- // Step 2: Perform transformation
334
- const tsConfigPath = findTsConfig(projectRoot);
619
+ const tsConfigPath = findTsConfig(config.projectRoot);
335
620
  if (!tsConfigPath) {
336
621
  throw new Error('Could not find tsconfig.json in the project root');
337
622
  }
338
- // Create transformation coordinator
339
- // Initialize kernel with transformation capabilities and caching
623
+ // One kernel for pre-validation and transformation: each load parses
624
+ // the whole program.
340
625
  const kernel = new Kernel({
341
626
  tsConfigPath,
342
627
  plugins: [new AngularPlugin()],
343
628
  cacheConfig: {
344
629
  enabled: true,
345
- cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
630
+ cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
346
631
  maxSize: 100 * 1024 * 1024, // 100MB
347
632
  maxAge: 24 * 60 * 60 * 1000, // 24 hours
348
633
  compression: true,
349
634
  },
350
635
  });
351
636
  await kernel.initialize();
352
- // Get the source file
353
637
  const project = kernel.getProject();
354
638
  const sourceFile = project.addSourceFileAtPath(filePath);
355
- // Capture line count before transformation
356
- const linesBefore = sourceFile.getFullText().split('\n').length;
357
- // Perform the transformation
358
- const transformConfig = {
359
- dryRun: false,
360
- autoSave: true,
361
- pluginConfig: {
362
- '@angular-modernizer/plugin-standalone': {
363
- transformationType: transformation === 'standalone-migration'
364
- ? transformation
365
- : undefined,
366
- ...options,
367
- },
368
- '@angular-modernizer/plugin-angular': {
369
- transformationType: [
370
- 'constructor-to-inject',
371
- 'interface-extraction',
372
- 'dependency-injection-migration',
373
- 'facade-pattern',
374
- 'form-modernization',
375
- 'constructor-injection-transform',
376
- 'component-inputs-interface-extraction',
377
- 'service-injection-cleanup',
378
- 'container-presentational',
379
- 'core-shared-modules',
380
- 'inheritance-to-composition',
381
- 'promise-service-to-observable',
382
- 'promise-component-to-reactive',
383
- 'promise-cleanup',
384
- 'sequential-await-to-forkjoin',
385
- 'missing-output-transform',
386
- 'subscription-transform',
387
- 'library-extraction',
388
- ].includes(transformation)
389
- ? transformation
390
- : undefined,
391
- ...options,
392
- },
393
- },
639
+ const checkCancelled = async () => {
640
+ await yieldIfCancellable(config.signal);
641
+ if (config.signal?.aborted === true) {
642
+ throw new TransformCancelledError();
643
+ }
394
644
  };
395
- const result = (await kernel.transformFile(sourceFile, transformConfig));
396
- // Save the file if autoSave is enabled
397
- if (!transformConfig.dryRun && transformConfig.autoSave) {
398
- await sourceFile.save();
645
+ await checkCancelled();
646
+ config.progress?.(1, 3, 'project loaded');
647
+ // Step 0: Pre-validate if requested (no backup needed when it fails)
648
+ if (config.validateBeforeTransform) {
649
+ preValidationResult = await this.preValidate(sourceFile, project, transformation);
399
650
  }
400
- // Capture line count after transformation
651
+ // Step 1: Backup in the project: file copy plus git snapshot
652
+ if (config.createBackup) {
653
+ const backup = await rollbackManager.createBackup([filePath], {
654
+ reason: `transform-code ${transformation}`,
655
+ });
656
+ if (!backup.success) {
657
+ throw new Error(`Failed to create backup before transformation: ${backup.error ?? 'unknown error'}`);
658
+ }
659
+ backupResult = {
660
+ created: true,
661
+ backupPath: backup.metadata?.backupPaths?.[0],
662
+ strategy: 'file-backup',
663
+ gitSnapshot: backup.metadata?.gitStashRef,
664
+ };
665
+ }
666
+ const typeErrorsBefore = config.validateTransformation
667
+ ? fileTypeErrors(sourceFile)
668
+ : [];
669
+ const linesBefore = sourceFile.getFullText().split('\n').length;
670
+ // Step 2: Transform
671
+ const transformed = config.apiStyle === 'fluent'
672
+ ? await this.transformFluent(kernel, filePath, transformation, options, config)
673
+ : await this.transformImperative(kernel, sourceFile, transformation, options);
674
+ await sourceFile.save();
675
+ await checkCancelled();
676
+ config.progress?.(2, 3, 'transformed, validating');
401
677
  const linesAfter = sourceFile.getFullText().split('\n').length;
402
- // Calculate changes
403
- const additions = Math.max(0, linesAfter - linesBefore);
404
- const deletions = Math.max(0, linesBefore - linesAfter);
405
- const linesChanged = result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0);
406
- // Step 3: Validate the transformation if requested
407
- let validation;
408
- if (validateTransformation) {
409
- const validator = new PostTransformValidator();
410
- const validationConfig = {
411
- validateBuild: validateBuild,
412
- validateTests: false, // Tests can be slow, skip by default
413
- validateLint: true,
414
- buildTimeout: buildTimeout,
415
- testTimeout: 600000,
416
- lintTimeout: 120000,
417
- cwd: projectRoot,
678
+ const changes = {
679
+ linesChanged: transformed.linesChanged,
680
+ additions: Math.max(0, linesAfter - linesBefore),
681
+ deletions: Math.max(0, linesBefore - linesAfter),
682
+ };
683
+ // Step 3: Validate
684
+ const checked = config.validateTransformation
685
+ ? await this.validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config)
686
+ : {
687
+ valid: true,
688
+ validation: await this.validateTransformation(filePath, transformation),
689
+ issues: [],
418
690
  };
419
- validationResult = await validator.validate(filePath, validationConfig);
420
- validation = {
421
- syntaxValid: validationResult.valid,
422
- typeCheckPassed: validationResult.valid,
423
- testsPass: validationResult.valid,
691
+ await checkCancelled();
692
+ config.progress?.(3, 3, 'validated');
693
+ const warnings = [...transformed.warnings];
694
+ // Step 4: Roll back when validation failed
695
+ if (!checked.valid && config.autoRollback && config.createBackup) {
696
+ const attempt = await rollbackManager.rollback([filePath]);
697
+ rollbackResult = {
698
+ performed: true,
699
+ reason: `Validation failed: ${checked.issues.length} issue(s) found`,
700
+ success: attempt.success,
424
701
  };
425
- // Step 4: Auto-rollback if validation failed and auto-rollback is enabled
426
- if (!validationResult.valid && autoRollback && createBackup) {
427
- const rollbackConfig = {
428
- backupDir: backupDir ?? undefined,
429
- gitRoot: projectRoot,
430
- };
431
- const rollbackManager = new RollbackManager(rollbackConfig);
432
- const rollbackAttempt = await rollbackManager.rollback([filePath]);
433
- rollbackResult = {
434
- performed: true,
435
- reason: `Validation failed: ${validationResult.issues.length} issue(s) found`,
436
- success: rollbackAttempt.success,
437
- };
438
- // If rollback succeeded, mark transformation as failed
439
- if (rollbackAttempt.success) {
440
- return {
441
- success: false,
442
- filePath,
443
- transformation,
444
- changes: {
445
- linesChanged,
446
- additions,
447
- deletions,
448
- },
449
- preValidation: preValidationResult,
450
- validation,
451
- backup: backupResult
452
- ? {
453
- created: backupResult.success,
454
- backupPath: backupResult.backupPath,
455
- strategy: 'file-backup',
456
- }
457
- : undefined,
458
- rollback: rollbackResult,
459
- warnings: [
460
- ...result.errors.map((e) => e.message),
461
- `Transformation rolled back due to validation failures`,
462
- ],
463
- };
464
- }
465
- }
466
- }
467
- else {
468
- // Use basic validation if full validation is disabled
469
- validation = (await this.validateTransformation(filePath, transformation));
702
+ warnings.push(attempt.success
703
+ ? 'Transformation rolled back due to validation failures'
704
+ : `Rollback failed: ${attempt.error ?? 'unknown error'}`);
470
705
  }
471
706
  return {
472
- success: result.success && (validationResult?.valid ?? true),
707
+ success: transformed.success && checked.valid,
473
708
  filePath,
474
709
  transformation,
475
- changes: {
476
- linesChanged,
477
- additions,
478
- deletions,
479
- },
710
+ changes,
480
711
  preValidation: preValidationResult,
481
- validation,
482
- backup: backupResult
483
- ? {
484
- created: backupResult.success,
485
- backupPath: backupResult.backupPath,
486
- strategy: 'file-backup',
487
- }
488
- : undefined,
712
+ validation: checked.validation,
713
+ backup: backupResult,
489
714
  rollback: rollbackResult,
490
- warnings: result.errors.map((e) => e.message),
715
+ pipeline: transformed.pipeline,
716
+ intermediateResults: transformed.intermediateResults,
717
+ buildValidation: checked.buildValidation,
718
+ warnings: [...warnings, ...checked.issues],
491
719
  };
492
720
  }
493
721
  catch (error) {
494
- // If an error occurs and we have a backup, attempt rollback
495
- if (createBackup && autoRollback && !rollbackResult) {
496
- try {
497
- const rollbackConfig = {
498
- backupDir: backupDir ?? undefined,
499
- gitRoot: projectRoot,
500
- };
501
- const rollbackManager = new RollbackManager(rollbackConfig);
502
- const rollbackAttempt = await rollbackManager.rollback([filePath]);
503
- rollbackResult = {
504
- performed: true,
505
- reason: `Transformation failed with error: ${error instanceof Error ? error.message : String(error)}`,
506
- success: rollbackAttempt.success,
507
- };
508
- }
509
- catch (rollbackError) {
510
- // Rollback failed, include this in the error
511
- throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}. ` +
512
- `Rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
722
+ if (error instanceof TransformCancelledError) {
723
+ return this.cancelledResult(filePath, transformation, backupResult, rollbackManager);
724
+ }
725
+ const message = error instanceof Error ? error.message : String(error);
726
+ // Restore the file when it may already have been changed
727
+ if (backupResult && config.autoRollback && !rollbackResult) {
728
+ const attempt = await rollbackManager.rollback([filePath]);
729
+ if (!attempt.success) {
730
+ throw new Error(`Code transformation failed: ${message}. ` +
731
+ `Rollback also failed: ${attempt.error ?? 'unknown error'}`);
513
732
  }
514
733
  }
515
- throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}`);
734
+ throw new Error(`Code transformation failed: ${message}`);
516
735
  }
517
736
  }
518
737
  /**
519
- * Execute transformation using fluent API.
738
+ * Result of a cancelled single-file run. A cancelled run always restores
739
+ * its backup (autoRollback or not): the client asked to stop, a half
740
+ * validated change must not stay. The SDK does not send this result; it
741
+ * is complete for direct callers.
520
742
  */
521
- async executeWithFluentApi(filePath, transformation, options, config) {
522
- let preValidationResult;
523
- let backupResult;
524
- let rollbackResult;
525
- try {
526
- // Step 0: Pre-validate if requested
527
- if (config.validateBeforeTransform) {
528
- const tsConfigPath = findTsConfig(config.projectRoot);
529
- if (!tsConfigPath) {
530
- throw new Error('Could not find tsconfig.json in the project root');
531
- }
532
- const tempKernel = new Kernel({
533
- tsConfigPath,
534
- plugins: [new AngularPlugin()],
535
- cacheConfig: {
536
- enabled: true,
537
- cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
538
- maxSize: 100 * 1024 * 1024,
539
- maxAge: 24 * 60 * 60 * 1000,
540
- compression: true,
541
- },
542
- });
543
- await tempKernel.initialize();
544
- const project = tempKernel.getProject();
545
- const sourceFile = project.addSourceFileAtPath(filePath);
546
- const preValidator = new PreTransformValidator();
547
- const preValidationConfig = {
548
- validateSyntax: true,
549
- validateDependencies: true,
550
- validateTypes: true,
551
- validateSchema: true,
552
- schema: this.getSchemaForTransformation(transformation),
553
- };
554
- const result = await preValidator.validate(sourceFile, project, preValidationConfig);
555
- preValidationResult = {
556
- valid: result.valid,
557
- issues: result.issues.map((issue) => ({
558
- type: issue.type,
559
- severity: issue.severity,
560
- message: issue.message,
561
- filePath: issue.filePath,
562
- line: issue.line,
563
- column: issue.column,
564
- })),
565
- };
566
- if (!result.valid) {
567
- throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
568
- `Cannot safely transform file. Please fix these issues first:\n` +
569
- result.issues
570
- .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
571
- .join('\n'));
572
- }
573
- }
574
- // Step 1: Create backup if requested
575
- if (config.createBackup) {
576
- const backupManager = new BackupManager(config.backupDir);
577
- backupResult = await backupManager.backup(filePath);
578
- if (!backupResult.success) {
579
- throw new Error('Failed to create backup before transformation');
580
- }
581
- }
582
- // Step 2: Create kernel and perform transformation using FluentKernel
583
- const tsConfigPath = findTsConfig(config.projectRoot);
584
- if (!tsConfigPath) {
585
- throw new Error('Could not find tsconfig.json in the project root');
586
- }
587
- const kernel = new Kernel({
588
- tsConfigPath,
589
- plugins: [new AngularPlugin()],
590
- cacheConfig: {
591
- enabled: true,
592
- cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
593
- maxSize: 100 * 1024 * 1024,
594
- maxAge: 24 * 60 * 60 * 1000,
595
- compression: true,
596
- },
597
- });
598
- await kernel.initialize();
599
- // Get the source file
600
- const project = kernel.getProject();
601
- const sourceFile = project.addSourceFileAtPath(filePath);
602
- const linesBefore = sourceFile.getFullText().split('\n').length;
603
- // Build fluent pipeline
604
- let fluent = FluentKernel.create(kernel)
605
- .transform(transformation, [filePath])
606
- .withMetadata({ transformation, filePath, options });
607
- // Add build check if requested
608
- if (config.buildCheck) {
609
- fluent = fluent.buildCheck(config.autoRollback);
610
- }
611
- // Execute pipeline
612
- const pipelineResult = await fluent.execute();
613
- // Save the file
614
- await sourceFile.save();
615
- // Capture line count after transformation
616
- const linesAfter = sourceFile.getFullText().split('\n').length;
617
- const additions = Math.max(0, linesAfter - linesBefore);
618
- const deletions = Math.max(0, linesBefore - linesAfter);
619
- // Extract pipeline info
620
- const pipeline = fluent.getStages().map((stage) => stage.name);
621
- const intermediateResults = {};
622
- for (const stage of fluent.getStages()) {
623
- intermediateResults[stage.name] = {
624
- success: true,
625
- message: `Stage ${stage.name} completed`,
626
- };
627
- }
628
- // Step 3: Validate if requested
629
- let validation;
630
- let buildValidation;
631
- if (config.validateTransformation) {
632
- const validator = new PostTransformValidator();
633
- const validationConfig = {
634
- validateBuild: config.validateBuild,
635
- validateTests: false,
636
- validateLint: true,
637
- buildTimeout: config.buildTimeout,
638
- testTimeout: 600000,
639
- lintTimeout: 120000,
640
- cwd: config.projectRoot,
641
- };
642
- const validationResult = await validator.validate(filePath, validationConfig);
643
- validation = {
644
- syntaxValid: validationResult.valid,
645
- typeCheckPassed: validationResult.valid,
646
- testsPass: validationResult.valid,
647
- };
648
- buildValidation = {
649
- passed: validationResult.valid,
650
- success: validationResult.valid,
651
- errors: validationResult.valid
652
- ? undefined
653
- : validationResult.issues.map((i) => i.message),
654
- };
655
- // Step 4: Auto-rollback if validation failed
656
- if (!validationResult.valid &&
657
- config.autoRollback &&
658
- config.createBackup) {
659
- const rollbackConfig = {
660
- backupDir: config.backupDir ?? undefined,
661
- gitRoot: config.projectRoot,
662
- };
663
- const rollbackManager = new RollbackManager(rollbackConfig);
664
- const rollbackAttempt = await rollbackManager.rollback([filePath]);
665
- rollbackResult = {
666
- performed: true,
667
- reason: `Validation failed: ${validationResult.issues.length} issue(s) found`,
668
- success: rollbackAttempt.success,
669
- };
670
- if (rollbackAttempt.success) {
671
- return {
672
- success: false,
673
- filePath,
674
- transformation,
675
- changes: {
676
- linesChanged: pipelineResult.transformations.length,
677
- additions,
678
- deletions,
679
- },
680
- preValidation: preValidationResult,
681
- validation,
682
- backup: backupResult
683
- ? {
684
- created: backupResult.success,
685
- backupPath: backupResult.backupPath,
686
- strategy: 'file-backup',
687
- }
688
- : undefined,
689
- rollback: rollbackResult,
690
- pipeline,
691
- intermediateResults,
692
- buildValidation,
693
- warnings: pipelineResult.errors.map((e) => e.message),
694
- };
695
- }
696
- }
697
- }
698
- else {
699
- validation = (await this.validateTransformation(filePath, transformation));
743
+ async cancelledResult(filePath, transformation, backup, rollbackManager) {
744
+ const warnings = [];
745
+ let rollback;
746
+ if (backup !== undefined) {
747
+ const attempt = await rollbackManager.rollback([filePath]);
748
+ rollback = { performed: true, reason: 'Cancelled by the client', success: attempt.success };
749
+ if (!attempt.success) {
750
+ warnings.push(`Rollback failed: ${attempt.error ?? 'unknown error'}`);
700
751
  }
701
- return {
702
- success: pipelineResult.success,
703
- filePath,
704
- transformation,
705
- changes: {
706
- linesChanged: pipelineResult.transformations.length,
707
- additions,
708
- deletions,
709
- },
710
- preValidation: preValidationResult,
711
- validation,
712
- backup: backupResult
713
- ? {
714
- created: backupResult.success,
715
- backupPath: backupResult.backupPath,
716
- strategy: 'file-backup',
717
- }
718
- : undefined,
719
- rollback: rollbackResult,
720
- pipeline,
721
- intermediateResults,
722
- buildValidation,
723
- warnings: pipelineResult.errors.map((e) => e.message),
752
+ }
753
+ else {
754
+ warnings.push('Cancelled by the client before a backup was taken; the file was not changed.');
755
+ }
756
+ return {
757
+ success: false,
758
+ filePath,
759
+ transformation,
760
+ changes: { linesChanged: 0, additions: 0, deletions: 0 },
761
+ validation: { syntaxValid: true, typeCheckPassed: true },
762
+ backup,
763
+ rollback,
764
+ warnings,
765
+ };
766
+ }
767
+ /**
768
+ * Pre-validate the file on the loaded project; throws when it is invalid.
769
+ */
770
+ async preValidate(sourceFile, project, transformation) {
771
+ const preValidator = new PreTransformValidator();
772
+ const preValidationConfig = {
773
+ validateSyntax: true,
774
+ validateDependencies: true,
775
+ validateTypes: true,
776
+ validateSchema: true,
777
+ schema: this.getSchemaForTransformation(transformation),
778
+ };
779
+ const result = await preValidator.validate(sourceFile, project, preValidationConfig);
780
+ if (!result.valid) {
781
+ throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
782
+ `Cannot safely transform file. Please fix these issues first:\n` +
783
+ result.issues
784
+ .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
785
+ .join('\n'));
786
+ }
787
+ return {
788
+ valid: result.valid,
789
+ issues: result.issues.map((issue) => ({
790
+ type: issue.type,
791
+ severity: issue.severity,
792
+ message: issue.message,
793
+ filePath: issue.filePath,
794
+ line: issue.line,
795
+ column: issue.column,
796
+ })),
797
+ };
798
+ }
799
+ /**
800
+ * Transform through the Kernel API.
801
+ */
802
+ async transformImperative(kernel, sourceFile, transformation, options) {
803
+ const result = (await kernel.transformFile(sourceFile, {
804
+ dryRun: false,
805
+ autoSave: true,
806
+ pluginConfig: pluginConfigFor(transformation, options),
807
+ }));
808
+ return {
809
+ success: result.success,
810
+ linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
811
+ warnings: result.errors.map((e) => e.message),
812
+ };
813
+ }
814
+ /**
815
+ * Transform through the FluentKernel pipeline (optional build check stage).
816
+ */
817
+ async transformFluent(kernel, filePath, transformation, options, config) {
818
+ let fluent = FluentKernel.create(kernel)
819
+ .transform(transformation, [filePath], pluginConfigFor(transformation, options))
820
+ .withMetadata({ transformation, filePath, options });
821
+ if (config.buildCheck) {
822
+ fluent = fluent.buildCheck(config.autoRollback);
823
+ }
824
+ const pipelineResult = await fluent.execute();
825
+ const intermediateResults = {};
826
+ for (const stage of fluent.getStages()) {
827
+ intermediateResults[stage.name] = {
828
+ success: true,
829
+ message: `Stage ${stage.name} completed`,
724
830
  };
725
831
  }
726
- catch (error) {
727
- // If an error occurs and we have a backup, attempt rollback
728
- if (config.createBackup && config.autoRollback && !rollbackResult) {
729
- try {
730
- const rollbackConfig = {
731
- backupDir: config.backupDir ?? undefined,
732
- gitRoot: config.projectRoot,
733
- };
734
- const rollbackManager = new RollbackManager(rollbackConfig);
735
- const rollbackAttempt = await rollbackManager.rollback([filePath]);
736
- rollbackResult = {
737
- performed: true,
738
- reason: `Transformation failed with error: ${error instanceof Error ? error.message : String(error)}`,
739
- success: rollbackAttempt.success,
740
- };
741
- }
742
- catch (rollbackError) {
743
- throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}. ` +
744
- `Rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
745
- }
832
+ return {
833
+ success: pipelineResult.success,
834
+ linesChanged: pipelineResult.transformations.length,
835
+ warnings: pipelineResult.errors.map((e) => e.message),
836
+ pipeline: fluent.getStages().map((stage) => stage.name),
837
+ intermediateResults,
838
+ };
839
+ }
840
+ /**
841
+ * Validate the transformed file: type errors the transformation introduced
842
+ * (from the loaded project, errors the file already had do not count), then
843
+ * build and lint only when requested. `buildValidation` is reported only
844
+ * when a build ran.
845
+ */
846
+ async validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config) {
847
+ const introduced = introducedTypeErrors(typeErrorsBefore, fileTypeErrors(sourceFile));
848
+ const issues = introduced.map((e) => `Type error introduced: ${e}`);
849
+ let postValid = true;
850
+ let buildValidation;
851
+ if (config.validateBuild || config.validateLint) {
852
+ const validator = new PostTransformValidator();
853
+ const validationConfig = {
854
+ validateBuild: config.validateBuild,
855
+ validateTests: false,
856
+ validateLint: config.validateLint,
857
+ buildTimeout: config.buildTimeout,
858
+ testTimeout: 600000,
859
+ lintTimeout: 120000,
860
+ cwd: config.projectRoot,
861
+ signal: config.signal,
862
+ };
863
+ const result = await validator.validate(filePath, validationConfig);
864
+ const errors = result.issues.filter((i) => i.severity === ValidationSeverity.ERROR);
865
+ postValid = result.valid;
866
+ issues.push(...errors.map((i) => i.message));
867
+ if (config.validateBuild) {
868
+ const buildErrors = errors
869
+ .filter((i) => i.type === ValidationType.BUILD)
870
+ .map((i) => i.message);
871
+ buildValidation = {
872
+ passed: buildErrors.length === 0,
873
+ success: buildErrors.length === 0,
874
+ errors: buildErrors.length > 0 ? buildErrors : undefined,
875
+ };
746
876
  }
747
- throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}`);
748
877
  }
878
+ return {
879
+ valid: introduced.length === 0 && postValid,
880
+ validation: {
881
+ syntaxValid: !introduced.some((e) => /^TS1\d{3}:/.test(e)),
882
+ typeCheckPassed: introduced.length === 0,
883
+ introducedTypeErrors: introduced.length > 0 ? introduced : undefined,
884
+ },
885
+ buildValidation,
886
+ issues,
887
+ };
749
888
  }
750
889
  /**
751
- * Execute streaming transformation - returns operationId immediately.
752
- * Transformation runs in background with progress stored in ProgressStore.
890
+ * Streaming mode: runs the synchronous path (same safety envelope, batch
891
+ * included) in the background and returns the operationId at once. The
892
+ * result is stored with setResult before markComplete, so
893
+ * get-operation-progress returns it.
753
894
  */
754
- async executeStreaming(params) {
895
+ executeStreaming(params) {
755
896
  const operationId = randomUUID();
756
897
  const store = ProgressStore.getInstance();
757
- // Create operation in store
758
898
  store.createOperation(operationId, {
759
899
  operationId,
760
900
  type: 'transformation',
761
901
  startTime: Date.now(),
762
902
  });
763
- // Start transformation in background (don't await)
764
- this.runStreamingTransformation(operationId, params).catch((error) => {
765
- // Mark operation as failed if error occurs
766
- store.markFailed(operationId, error instanceof Error ? error.message : String(error));
767
- });
768
- // Return operationId immediately
903
+ // Start in a later turn of the event loop: the run's synchronous part
904
+ // (project load, seconds on large projects) would otherwise delay the
905
+ // response with the operationId. Once the synchronous part runs, it also
906
+ // delays the next request, so the start waits 50 ms: a client that polls
907
+ // get-operation-progress right after the response is answered first
908
+ // (measured on a large project: setImmediate ~4 s for that poll, a 0 ms
909
+ // timer 0 or ~4 s, 50 ms always 0 to 1 ms).
910
+ setTimeout(() => {
911
+ void this.execute({ ...params, streaming: false }).then((result) => {
912
+ if (store.hasOperation(operationId)) {
913
+ store.setResult(operationId, result);
914
+ store.markComplete(operationId);
915
+ }
916
+ }, (error) => {
917
+ if (store.hasOperation(operationId)) {
918
+ store.markFailed(operationId, error instanceof Error ? error.message : String(error));
919
+ }
920
+ });
921
+ }, 50);
769
922
  return {
770
923
  success: true,
771
924
  operationId,
@@ -779,98 +932,15 @@ export class TransformCodeTool {
779
932
  syntaxValid: true,
780
933
  typeCheckPassed: true,
781
934
  },
935
+ warnings: [
936
+ 'Started in the background: the result is returned by get-operation-progress once the operation is completed.',
937
+ ],
782
938
  };
783
939
  }
784
940
  /**
785
- * Run streaming transformation in background using StreamingKernelWrapper.
941
+ * Execute batch transformation.
786
942
  */
787
- async runStreamingTransformation(operationId, params) {
788
- const store = ProgressStore.getInstance();
789
- const filePath = params.filePath;
790
- const transformation = params.transformation;
791
- if (!filePath || typeof filePath !== 'string') {
792
- throw new Error('filePath is required and must be a string');
793
- }
794
- if (!transformation) {
795
- throw new Error('transformation is required');
796
- }
797
- // Find project root
798
- const projectRoot = this.findProjectRoot(filePath);
799
- const tsConfigPath = findTsConfig(projectRoot);
800
- if (!tsConfigPath) {
801
- throw new Error('Could not find tsconfig.json in the project root');
802
- }
803
- // Create kernel
804
- const kernel = new Kernel({
805
- tsConfigPath,
806
- plugins: [new AngularPlugin()],
807
- cacheConfig: {
808
- enabled: true,
809
- cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
810
- maxSize: 100 * 1024 * 1024,
811
- maxAge: 24 * 60 * 60 * 1000,
812
- compression: true,
813
- },
814
- });
815
- await kernel.initialize();
816
- // Create StreamingKernelWrapper with diffFormat from params (default: 'structured')
817
- const wrapper = new StreamingKernelWrapper(kernel, {
818
- includeDiffs: true,
819
- diffFormat: params.diffFormat ?? 'structured',
820
- includeMemory: true,
821
- validateSyntax: true,
822
- diffContext: 3,
823
- });
824
- // Create transform config
825
- const transformConfig = {
826
- dryRun: false,
827
- autoSave: true,
828
- pluginConfig: {
829
- '@angular-modernizer/plugin-standalone': {
830
- transformationType: transformation === 'standalone-migration'
831
- ? transformation
832
- : undefined,
833
- ...params.options,
834
- },
835
- '@angular-modernizer/plugin-angular': {
836
- transformationType: [
837
- 'constructor-to-inject',
838
- 'interface-extraction',
839
- 'dependency-injection-migration',
840
- 'facade-pattern',
841
- 'form-modernization',
842
- 'constructor-injection-transform',
843
- 'component-inputs-interface-extraction',
844
- 'service-injection-cleanup',
845
- 'container-presentational',
846
- 'core-shared-modules',
847
- 'inheritance-to-composition',
848
- 'promise-service-to-observable',
849
- 'promise-component-to-reactive',
850
- 'promise-cleanup',
851
- 'sequential-await-to-forkjoin',
852
- 'missing-output-transform',
853
- 'subscription-transform',
854
- 'library-extraction',
855
- ].includes(transformation)
856
- ? transformation
857
- : undefined,
858
- ...params.options,
859
- },
860
- },
861
- };
862
- // Use streaming transformation
863
- for await (const event of wrapper.transformStreaming([], [filePath], transformConfig)) {
864
- // Add each streaming event to the store
865
- store.addEvent(operationId, event);
866
- }
867
- // Mark complete
868
- store.markComplete(operationId);
869
- }
870
- /**
871
- * Execute batch transformation (Phase 6a).
872
- */
873
- async executeBatch(params, orchestration) {
943
+ async executeBatch(params, orchestration, ctx) {
874
944
  if (!params.files || params.files.length === 0) {
875
945
  throw new Error('files array is required for batch mode');
876
946
  }
@@ -882,7 +952,7 @@ export class TransformCodeTool {
882
952
  if (!firstFile) {
883
953
  throw new Error('files array cannot be empty');
884
954
  }
885
- const projectRoot = this.findProjectRoot(firstFile);
955
+ const projectRoot = params.projectRoot ?? this.findProjectRoot(firstFile);
886
956
  const fullConfig = loadConfig(projectRoot);
887
957
  const config = fullConfig.tools?.['transform-code'] ?? {};
888
958
  const mergedParams = { ...config, ...params };
@@ -893,7 +963,12 @@ export class TransformCodeTool {
893
963
  options: mergedParams.options,
894
964
  parallel: orchestration.parallel ?? false,
895
965
  enableProgress: orchestration.enableProgress ?? false,
896
- signal: mergedParams.signal,
966
+ signal: ctx.signal,
967
+ onProgress: ctx.progress === undefined
968
+ ? undefined
969
+ : (done, total) => {
970
+ ctx.progress?.(done, total, `${done}/${total} files transformed`);
971
+ },
897
972
  resourceLimits: orchestration.resourceLimits
898
973
  ? {
899
974
  maxMemory: orchestration.resourceLimits.maxMemory,
@@ -909,12 +984,60 @@ export class TransformCodeTool {
909
984
  timeout: orchestration.timeout,
910
985
  pluginIds: orchestration.pluginIds,
911
986
  };
987
+ // Back up all files as one group before any of them changes
988
+ const rollbackManager = createProjectRollbackManager(projectRoot, {
989
+ backupDir: mergedParams.backupDir,
990
+ });
991
+ const createBackup = mergedParams.createBackup ?? true;
992
+ let backup;
993
+ if (createBackup) {
994
+ const backupResult = await rollbackManager.createBackup(batchOptions.files, {
995
+ reason: `transform-code ${batchOptions.transformation}`,
996
+ });
997
+ if (!backupResult.success) {
998
+ throw new Error(`Failed to create backup before transformation: ${backupResult.error ?? 'unknown error'}`);
999
+ }
1000
+ backup = {
1001
+ created: true,
1002
+ backupPath: backupResult.metadata?.backupPaths?.[0],
1003
+ strategy: 'file-backup',
1004
+ gitSnapshot: backupResult.metadata?.gitStashRef,
1005
+ };
1006
+ }
1007
+ const batchKernel = createBatchKernel(() => loadBatchKernel(projectRoot));
912
1008
  const result = await executeBatchTransformation(batchOptions, async (filePath) => {
913
- return this.transformSingleFile(filePath, params, projectRoot);
1009
+ return this.transformSingleFile(filePath, params, batchKernel);
914
1010
  });
1011
+ const failedFiles = result.files
1012
+ .filter((f) => !f.success)
1013
+ .map((f) => f.path);
1014
+ const cancelled = ctx.signal?.aborted === true;
1015
+ // A cancelled batch restores every file, whatever the strategy
1016
+ const filesToRestore = cancelled
1017
+ ? batchOptions.files
1018
+ : batchFilesToRestore(batchOptions.rollbackStrategy ?? 'all-or-nothing', batchOptions.files, failedFiles);
1019
+ let rollback;
1020
+ if (cancelled && createBackup) {
1021
+ const attempt = await rollbackManager.rollback(filesToRestore);
1022
+ rollback = {
1023
+ performed: true,
1024
+ reason: `Cancelled by the client after ${result.files.length} of ${batchOptions.files.length} file(s)`,
1025
+ success: attempt.success,
1026
+ };
1027
+ }
1028
+ else if (createBackup && failedFiles.length > 0 && filesToRestore.length > 0) {
1029
+ const attempt = await rollbackManager.rollback(filesToRestore);
1030
+ rollback = {
1031
+ performed: true,
1032
+ reason: `${failedFiles.length} file(s) failed (${batchOptions.rollbackStrategy})`,
1033
+ success: attempt.success,
1034
+ };
1035
+ }
915
1036
  // Convert batch result to TransformationResult format
916
1037
  return {
917
- success: result.success,
1038
+ success: result.success && !cancelled,
1039
+ backup,
1040
+ rollback,
918
1041
  files: result.files,
919
1042
  transformation: params.transformation,
920
1043
  changes: {
@@ -933,73 +1056,9 @@ export class TransformCodeTool {
933
1056
  /**
934
1057
  * Transform a single file (internal helper for batch mode).
935
1058
  */
936
- async transformSingleFile(filePath, params, projectRoot) {
1059
+ async transformSingleFile(filePath, params, batchKernel) {
937
1060
  try {
938
- const tsConfigPath = findTsConfig(projectRoot);
939
- if (!tsConfigPath) {
940
- return {
941
- success: false,
942
- error: 'Could not find tsconfig.json',
943
- changes: { linesChanged: 0, additions: 0, deletions: 0 },
944
- };
945
- }
946
- const kernel = new Kernel({
947
- tsConfigPath,
948
- plugins: [new AngularPlugin()],
949
- });
950
- await kernel.initialize();
951
- const project = kernel.getProject();
952
- const sourceFile = project.addSourceFileAtPath(filePath);
953
- const linesBefore = sourceFile.getFullText().split('\n').length;
954
- const transformConfig = {
955
- dryRun: false,
956
- autoSave: true,
957
- pluginConfig: {
958
- '@angular-modernizer/plugin-standalone': {
959
- transformationType: params.transformation === 'standalone-migration'
960
- ? params.transformation
961
- : undefined,
962
- ...params.options,
963
- },
964
- '@angular-modernizer/plugin-angular': {
965
- transformationType: [
966
- 'constructor-to-inject',
967
- 'interface-extraction',
968
- 'dependency-injection-migration',
969
- 'facade-pattern',
970
- 'form-modernization',
971
- 'constructor-injection-transform',
972
- 'component-inputs-interface-extraction',
973
- 'service-injection-cleanup',
974
- 'container-presentational',
975
- 'core-shared-modules',
976
- 'inheritance-to-composition',
977
- 'promise-service-to-observable',
978
- 'promise-component-to-reactive',
979
- 'promise-cleanup',
980
- 'sequential-await-to-forkjoin',
981
- 'missing-output-transform',
982
- 'subscription-transform',
983
- 'library-extraction',
984
- ].includes(params.transformation ?? '')
985
- ? params.transformation
986
- : undefined,
987
- ...params.options,
988
- },
989
- },
990
- };
991
- const result = (await kernel.transformFile(sourceFile, transformConfig));
992
- if (!transformConfig.dryRun && transformConfig.autoSave) {
993
- await sourceFile.save();
994
- }
995
- const linesAfter = sourceFile.getFullText().split('\n').length;
996
- const additions = Math.max(0, linesAfter - linesBefore);
997
- const deletions = Math.max(0, linesBefore - linesAfter);
998
- const linesChanged = result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0);
999
- return {
1000
- success: result.success,
1001
- changes: { linesChanged, additions, deletions },
1002
- };
1061
+ return await batchKernel.run((kernel) => transformWithKernel(kernel, filePath, params));
1003
1062
  }
1004
1063
  catch (error) {
1005
1064
  return {