@angular-modernizer/adapter-mcp 0.1.1

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 (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +917 -0
  3. package/dist/cli.d.ts +8 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +129 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/core/project-analyzer.d.ts +59 -0
  8. package/dist/core/project-analyzer.d.ts.map +1 -0
  9. package/dist/core/project-analyzer.js +116 -0
  10. package/dist/core/project-analyzer.js.map +1 -0
  11. package/dist/index.d.ts +46 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +51 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mcp-watcher.d.ts +119 -0
  16. package/dist/mcp-watcher.d.ts.map +1 -0
  17. package/dist/mcp-watcher.js +380 -0
  18. package/dist/mcp-watcher.js.map +1 -0
  19. package/dist/server/json-rpc-handler.d.ts +57 -0
  20. package/dist/server/json-rpc-handler.d.ts.map +1 -0
  21. package/dist/server/json-rpc-handler.js +222 -0
  22. package/dist/server/json-rpc-handler.js.map +1 -0
  23. package/dist/server/mcp-server.d.ts +62 -0
  24. package/dist/server/mcp-server.d.ts.map +1 -0
  25. package/dist/server/mcp-server.js +184 -0
  26. package/dist/server/mcp-server.js.map +1 -0
  27. package/dist/server/tool-registry.d.ts +73 -0
  28. package/dist/server/tool-registry.d.ts.map +1 -0
  29. package/dist/server/tool-registry.js +102 -0
  30. package/dist/server/tool-registry.js.map +1 -0
  31. package/dist/streaming/progress-store.d.ts +120 -0
  32. package/dist/streaming/progress-store.d.ts.map +1 -0
  33. package/dist/streaming/progress-store.js +238 -0
  34. package/dist/streaming/progress-store.js.map +1 -0
  35. package/dist/tools/analyze-build-impact.d.ts +127 -0
  36. package/dist/tools/analyze-build-impact.d.ts.map +1 -0
  37. package/dist/tools/analyze-build-impact.js +194 -0
  38. package/dist/tools/analyze-build-impact.js.map +1 -0
  39. package/dist/tools/analyze-core-to-shared.d.ts +163 -0
  40. package/dist/tools/analyze-core-to-shared.d.ts.map +1 -0
  41. package/dist/tools/analyze-core-to-shared.js +436 -0
  42. package/dist/tools/analyze-core-to-shared.js.map +1 -0
  43. package/dist/tools/analyze-parser-performance.d.ts +105 -0
  44. package/dist/tools/analyze-parser-performance.d.ts.map +1 -0
  45. package/dist/tools/analyze-parser-performance.js +313 -0
  46. package/dist/tools/analyze-parser-performance.js.map +1 -0
  47. package/dist/tools/analyze-project.d.ts +277 -0
  48. package/dist/tools/analyze-project.d.ts.map +1 -0
  49. package/dist/tools/analyze-project.js +946 -0
  50. package/dist/tools/analyze-project.js.map +1 -0
  51. package/dist/tools/check-incremental-compatibility.d.ts +109 -0
  52. package/dist/tools/check-incremental-compatibility.d.ts.map +1 -0
  53. package/dist/tools/check-incremental-compatibility.js +302 -0
  54. package/dist/tools/check-incremental-compatibility.js.map +1 -0
  55. package/dist/tools/collect-feedback.d.ts +117 -0
  56. package/dist/tools/collect-feedback.d.ts.map +1 -0
  57. package/dist/tools/collect-feedback.js +773 -0
  58. package/dist/tools/collect-feedback.js.map +1 -0
  59. package/dist/tools/extract-libraries.d.ts +121 -0
  60. package/dist/tools/extract-libraries.d.ts.map +1 -0
  61. package/dist/tools/extract-libraries.js +223 -0
  62. package/dist/tools/extract-libraries.js.map +1 -0
  63. package/dist/tools/find-angular-symbol.d.ts +55 -0
  64. package/dist/tools/find-angular-symbol.d.ts.map +1 -0
  65. package/dist/tools/find-angular-symbol.js +104 -0
  66. package/dist/tools/find-angular-symbol.js.map +1 -0
  67. package/dist/tools/find-usages.d.ts +65 -0
  68. package/dist/tools/find-usages.d.ts.map +1 -0
  69. package/dist/tools/find-usages.js +108 -0
  70. package/dist/tools/find-usages.js.map +1 -0
  71. package/dist/tools/get-call-graph.d.ts +61 -0
  72. package/dist/tools/get-call-graph.d.ts.map +1 -0
  73. package/dist/tools/get-call-graph.js +119 -0
  74. package/dist/tools/get-call-graph.js.map +1 -0
  75. package/dist/tools/get-operation-progress-tool.d.ts +29 -0
  76. package/dist/tools/get-operation-progress-tool.d.ts.map +1 -0
  77. package/dist/tools/get-operation-progress-tool.js +36 -0
  78. package/dist/tools/get-operation-progress-tool.js.map +1 -0
  79. package/dist/tools/get-operation-progress.d.ts +51 -0
  80. package/dist/tools/get-operation-progress.d.ts.map +1 -0
  81. package/dist/tools/get-operation-progress.js +93 -0
  82. package/dist/tools/get-operation-progress.js.map +1 -0
  83. package/dist/tools/helpers/feedback-analyzer.d.ts +43 -0
  84. package/dist/tools/helpers/feedback-analyzer.d.ts.map +1 -0
  85. package/dist/tools/helpers/feedback-analyzer.js +196 -0
  86. package/dist/tools/helpers/feedback-analyzer.js.map +1 -0
  87. package/dist/tools/helpers/find-ts-config.d.ts +10 -0
  88. package/dist/tools/helpers/find-ts-config.d.ts.map +1 -0
  89. package/dist/tools/helpers/find-ts-config.js +32 -0
  90. package/dist/tools/helpers/find-ts-config.js.map +1 -0
  91. package/dist/tools/helpers/platform-root-resolver.d.ts +33 -0
  92. package/dist/tools/helpers/platform-root-resolver.d.ts.map +1 -0
  93. package/dist/tools/helpers/platform-root-resolver.js +60 -0
  94. package/dist/tools/helpers/platform-root-resolver.js.map +1 -0
  95. package/dist/tools/helpers/rule-matcher.d.ts +84 -0
  96. package/dist/tools/helpers/rule-matcher.d.ts.map +1 -0
  97. package/dist/tools/helpers/rule-matcher.js +212 -0
  98. package/dist/tools/helpers/rule-matcher.js.map +1 -0
  99. package/dist/tools/helpers/suggestion-generator.d.ts +66 -0
  100. package/dist/tools/helpers/suggestion-generator.d.ts.map +1 -0
  101. package/dist/tools/helpers/suggestion-generator.js +248 -0
  102. package/dist/tools/helpers/suggestion-generator.js.map +1 -0
  103. package/dist/tools/learn-patterns.d.ts +368 -0
  104. package/dist/tools/learn-patterns.d.ts.map +1 -0
  105. package/dist/tools/learn-patterns.js +1089 -0
  106. package/dist/tools/learn-patterns.js.map +1 -0
  107. package/dist/tools/orchestrate-migration.d.ts +187 -0
  108. package/dist/tools/orchestrate-migration.d.ts.map +1 -0
  109. package/dist/tools/orchestrate-migration.js +235 -0
  110. package/dist/tools/orchestrate-migration.js.map +1 -0
  111. package/dist/tools/parse-stack-trace.d.ts +63 -0
  112. package/dist/tools/parse-stack-trace.d.ts.map +1 -0
  113. package/dist/tools/parse-stack-trace.js +92 -0
  114. package/dist/tools/parse-stack-trace.js.map +1 -0
  115. package/dist/tools/plan-migration.d.ts +388 -0
  116. package/dist/tools/plan-migration.d.ts.map +1 -0
  117. package/dist/tools/plan-migration.js +826 -0
  118. package/dist/tools/plan-migration.js.map +1 -0
  119. package/dist/tools/resolve-type.d.ts +54 -0
  120. package/dist/tools/resolve-type.d.ts.map +1 -0
  121. package/dist/tools/resolve-type.js +101 -0
  122. package/dist/tools/resolve-type.js.map +1 -0
  123. package/dist/tools/review-feedback.d.ts +124 -0
  124. package/dist/tools/review-feedback.d.ts.map +1 -0
  125. package/dist/tools/review-feedback.js +276 -0
  126. package/dist/tools/review-feedback.js.map +1 -0
  127. package/dist/tools/rollback-changes.d.ts +42 -0
  128. package/dist/tools/rollback-changes.d.ts.map +1 -0
  129. package/dist/tools/rollback-changes.js +95 -0
  130. package/dist/tools/rollback-changes.js.map +1 -0
  131. package/dist/tools/run-angular-cli.d.ts +102 -0
  132. package/dist/tools/run-angular-cli.d.ts.map +1 -0
  133. package/dist/tools/run-angular-cli.js +152 -0
  134. package/dist/tools/run-angular-cli.js.map +1 -0
  135. package/dist/tools/run-build.d.ts +201 -0
  136. package/dist/tools/run-build.d.ts.map +1 -0
  137. package/dist/tools/run-build.js +554 -0
  138. package/dist/tools/run-build.js.map +1 -0
  139. package/dist/tools/run-schematic.d.ts +173 -0
  140. package/dist/tools/run-schematic.d.ts.map +1 -0
  141. package/dist/tools/run-schematic.js +410 -0
  142. package/dist/tools/run-schematic.js.map +1 -0
  143. package/dist/tools/scan-all.d.ts +160 -0
  144. package/dist/tools/scan-all.d.ts.map +1 -0
  145. package/dist/tools/scan-all.js +486 -0
  146. package/dist/tools/scan-all.js.map +1 -0
  147. package/dist/tools/scan-angular.d.ts +132 -0
  148. package/dist/tools/scan-angular.d.ts.map +1 -0
  149. package/dist/tools/scan-angular.js +411 -0
  150. package/dist/tools/scan-angular.js.map +1 -0
  151. package/dist/tools/scan-architecture.d.ts +351 -0
  152. package/dist/tools/scan-architecture.d.ts.map +1 -0
  153. package/dist/tools/scan-architecture.js +1290 -0
  154. package/dist/tools/scan-architecture.js.map +1 -0
  155. package/dist/tools/scan-solid.d.ts +132 -0
  156. package/dist/tools/scan-solid.d.ts.map +1 -0
  157. package/dist/tools/scan-solid.js +435 -0
  158. package/dist/tools/scan-solid.js.map +1 -0
  159. package/dist/tools/search-codebase.d.ts +64 -0
  160. package/dist/tools/search-codebase.d.ts.map +1 -0
  161. package/dist/tools/search-codebase.js +109 -0
  162. package/dist/tools/search-codebase.js.map +1 -0
  163. package/dist/tools/shared/scan-types.d.ts +200 -0
  164. package/dist/tools/shared/scan-types.d.ts.map +1 -0
  165. package/dist/tools/shared/scan-types.js +7 -0
  166. package/dist/tools/shared/scan-types.js.map +1 -0
  167. package/dist/tools/suggest-improvements.d.ts +96 -0
  168. package/dist/tools/suggest-improvements.d.ts.map +1 -0
  169. package/dist/tools/suggest-improvements.js +182 -0
  170. package/dist/tools/suggest-improvements.js.map +1 -0
  171. package/dist/tools/transform-code-batch.d.ts +57 -0
  172. package/dist/tools/transform-code-batch.d.ts.map +1 -0
  173. package/dist/tools/transform-code-batch.js +107 -0
  174. package/dist/tools/transform-code-batch.js.map +1 -0
  175. package/dist/tools/transform-code.d.ts +352 -0
  176. package/dist/tools/transform-code.d.ts.map +1 -0
  177. package/dist/tools/transform-code.js +1171 -0
  178. package/dist/tools/transform-code.js.map +1 -0
  179. package/dist/tools/validate-before-transform.d.ts +54 -0
  180. package/dist/tools/validate-before-transform.d.ts.map +1 -0
  181. package/dist/tools/validate-before-transform.js +141 -0
  182. package/dist/tools/validate-before-transform.js.map +1 -0
  183. package/dist/tools/validate-project-compatibility.d.ts +119 -0
  184. package/dist/tools/validate-project-compatibility.d.ts.map +1 -0
  185. package/dist/tools/validate-project-compatibility.js +243 -0
  186. package/dist/tools/validate-project-compatibility.js.map +1 -0
  187. package/dist/tools/validate-transformation.d.ts +105 -0
  188. package/dist/tools/validate-transformation.d.ts.map +1 -0
  189. package/dist/tools/validate-transformation.js +391 -0
  190. package/dist/tools/validate-transformation.js.map +1 -0
  191. package/dist/types.d.ts +153 -0
  192. package/dist/types.d.ts.map +1 -0
  193. package/dist/types.js +38 -0
  194. package/dist/types.js.map +1 -0
  195. package/dist/utils/format-tool-response.d.ts +72 -0
  196. package/dist/utils/format-tool-response.d.ts.map +1 -0
  197. package/dist/utils/format-tool-response.js +149 -0
  198. package/dist/utils/format-tool-response.js.map +1 -0
  199. package/package.json +70 -0
@@ -0,0 +1,773 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Collect Feedback Tool
3
+ *
4
+ * MCP tool for manually collecting transformation feedback for AI learning.
5
+ * Stores feedback in both user's project and platform root by default.
6
+ *
7
+ * Privacy-First:
8
+ * - All file paths anonymized with SHA-256 hashing
9
+ * - No code snippets stored, only metadata
10
+ * - Privacy audit enforced before storage
11
+ *
12
+ * Storage Strategy:
13
+ * - DEFAULT: Store in BOTH project and platform locations
14
+ * - Configurable: 'project', 'platform', or 'both'
15
+ * - Graceful partial failure handling
16
+ */
17
+ import { FeedbackCollector, PrivacyFilter, FeedbackValidator, FeedbackStorage, loadConfig, FEEDBACK_VERSION, FEEDBACK_FORMAT, ValidationType, ValidationSeverity, } from '@angular-modernizer/core';
18
+ import { randomUUID } from 'node:crypto';
19
+ import * as path from 'node:path';
20
+ import { promises as fs } from 'node:fs';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { resolvePlatformRoot } from './helpers/platform-root-resolver.js';
23
+ // ESM-compatible __dirname alternative
24
+ const __filename = fileURLToPath(import.meta.url);
25
+ const __dirname = path.dirname(__filename);
26
+ // Custom error types for better error handling
27
+ class SessionPersistenceError extends Error {
28
+ sessionId;
29
+ constructor(message, sessionId) {
30
+ super(message);
31
+ this.sessionId = sessionId;
32
+ this.name = 'SessionPersistenceError';
33
+ }
34
+ }
35
+ class ValidationError extends Error {
36
+ constructor(message) {
37
+ super(message);
38
+ this.name = 'ValidationError';
39
+ }
40
+ }
41
+ // Mutex to prevent race conditions during session initialization
42
+ const sessionInitLocks = new Map();
43
+ // Cache for platform root resolution (avoid repeated upward directory search)
44
+ let cachedPlatformRoot = null;
45
+ /**
46
+ * Ensures a feedback session exists, creating it if necessary.
47
+ * Thread-safe via Promise-based locking mechanism.
48
+ *
49
+ * @param sessionId - Unique session identifier (alphanumeric, underscore, hyphen only)
50
+ *
51
+ * @param feedbackStorage - Storage instance for session persistence
52
+ *
53
+ * @param projectRoot - Absolute path to project root
54
+ *
55
+ * @param platformRoot - Absolute path to platform root (tsanalyzer)
56
+ *
57
+ * @param privacyFilter - Privacy filter for anonymization
58
+ *
59
+ * @param salt - Salt for hashing
60
+ * @throws {ValidationError} If sessionId format is invalid or roots don't exist
61
+ * @throws {SessionPersistenceError} If session creation fails
62
+ */
63
+ async function ensureSessionExists(sessionId, feedbackStorage, projectRoot, platformRoot, privacyFilter, salt) {
64
+ const startTime = Date.now();
65
+ // 1. Validate session ID format (alphanumeric + underscore + hyphen)
66
+ if (!/^[a-zA-Z0-9_-]+$/.test(sessionId)) {
67
+ throw new ValidationError(`Invalid session ID: ${sessionId}. Must contain only alphanumeric characters, underscores, and hyphens.`);
68
+ }
69
+ // 2. Validate platform root exists (cached for performance)
70
+ if (!cachedPlatformRoot || cachedPlatformRoot !== platformRoot) {
71
+ try {
72
+ await fs.access(platformRoot);
73
+ cachedPlatformRoot = platformRoot; // Cache successful validation
74
+ }
75
+ catch {
76
+ throw new ValidationError(`Invalid platformRoot: ${platformRoot} does not exist or is not accessible.`);
77
+ }
78
+ }
79
+ // 3. Check if session already exists
80
+ const sessionExists = await feedbackStorage.sessionExists(sessionId);
81
+ if (sessionExists) {
82
+ return; // Already initialized
83
+ }
84
+ // 4. Check if initialization is already in progress (race condition protection)
85
+ const existingLock = sessionInitLocks.get(sessionId);
86
+ if (existingLock) {
87
+ await existingLock; // Wait for in-progress initialization
88
+ return;
89
+ }
90
+ // 5. Create new initialization lock with retry logic
91
+ const initPromise = (async () => {
92
+ const maxRetries = 3;
93
+ let lastError = null;
94
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
95
+ try {
96
+ // Double-check after acquiring lock (another call might have created it)
97
+ const stillNotExists = !(await feedbackStorage.sessionExists(sessionId));
98
+ if (!stillNotExists) {
99
+ return; // Another concurrent call created it
100
+ }
101
+ // Ensure directories exist (with retries for transient failures)
102
+ const projectSessionsDir = path.join(projectRoot, '.claude-feedback', 'sessions');
103
+ const platformSessionsDir = path.join(platformRoot, '.claude-feedback', 'sessions');
104
+ await fs.mkdir(projectSessionsDir, { recursive: true });
105
+ await fs.mkdir(platformSessionsDir, { recursive: true });
106
+ // Create minimal session for manual feedback
107
+ const minimalSession = {
108
+ format: FEEDBACK_FORMAT,
109
+ sessionId,
110
+ timestamp: new Date().toISOString(),
111
+ projectContext: {
112
+ // Use proper privacy filter with salt
113
+ projectId: privacyFilter.anonymizeProjectId(projectRoot, salt),
114
+ angularVersion: 'unknown',
115
+ projectSize: 'medium',
116
+ moduleStructure: 'ngmodule',
117
+ hasTests: false,
118
+ hasLinting: false,
119
+ },
120
+ transformations: [],
121
+ sessionOutcome: {
122
+ totalTransformations: 0,
123
+ successful: 0,
124
+ failed: 0,
125
+ rolledBack: 0,
126
+ duration: 0,
127
+ quality: 'unchanged',
128
+ aggregatedLearnings: [],
129
+ },
130
+ };
131
+ // Initialize session file before appending
132
+ await feedbackStorage.initSession(sessionId, minimalSession);
133
+ // Performance logging for slow operations
134
+ const duration = Date.now() - startTime;
135
+ if (duration > 1000) {
136
+ console.warn(`Session initialization took ${duration}ms (slow)`);
137
+ }
138
+ // Log success with duration
139
+ console.info(`Session ${sessionId} initialized successfully [${duration}ms]`);
140
+ return; // Success - exit retry loop
141
+ }
142
+ catch (error) {
143
+ lastError = error;
144
+ // Cast error to NodeJS.ErrnoException for proper error code checking
145
+ const fsError = error;
146
+ // Check if error is retryable (transient file system errors)
147
+ const isRetryable = fsError.code === 'EBUSY' || // File busy
148
+ fsError.code === 'EAGAIN' || // Resource temporarily unavailable
149
+ fsError.code === 'EMFILE' || // Too many open files
150
+ fsError.code === 'ENFILE'; // Too many open files (system)
151
+ if (isRetryable && attempt < maxRetries) {
152
+ const backoff = Math.min(100 * Math.pow(2, attempt), 1000);
153
+ console.warn(`Session initialization failed (attempt ${attempt}/${maxRetries}), ` +
154
+ `retrying in ${backoff}ms: ${fsError.message}`);
155
+ await new Promise((resolve) => setTimeout(resolve, backoff));
156
+ continue;
157
+ }
158
+ // Non-retryable error or max retries exceeded
159
+ break;
160
+ }
161
+ }
162
+ // All retries failed
163
+ throw new SessionPersistenceError(`Failed to initialize session after ${maxRetries} attempts: ${lastError?.message}`, sessionId);
164
+ })();
165
+ // Store promise and await completion
166
+ sessionInitLocks.set(sessionId, initPromise);
167
+ try {
168
+ await initPromise;
169
+ }
170
+ finally {
171
+ // Clean up lock after initialization (success or failure)
172
+ sessionInitLocks.delete(sessionId);
173
+ }
174
+ }
175
+ /**
176
+ * Helper function to safely extract a string value from an unknown type.
177
+ * Returns the value if it's a non-empty string, otherwise returns undefined.
178
+ */
179
+ function getStringValue(value) {
180
+ return typeof value === 'string' && value ? value : undefined;
181
+ }
182
+ /**
183
+ * Collect transformation feedback for AI learning
184
+ */
185
+ export class CollectFeedbackTool {
186
+ name = 'collect-feedback';
187
+ description = 'Manually collect transformation feedback for AI learning. ' +
188
+ 'Stores feedback in both user project and platform root (default). ' +
189
+ 'Validates feedback, anonymizes file paths, and extracts learnings automatically.';
190
+ // Cache platformRoot to avoid repeated path.join calculations
191
+ platformRoot = null;
192
+ inputSchema = {
193
+ type: 'object',
194
+ properties: {
195
+ projectRoot: {
196
+ type: 'string',
197
+ description: 'Project root path (defaults to process.cwd() if not provided)',
198
+ },
199
+ sessionId: {
200
+ type: 'string',
201
+ description: 'Optional session ID (existing session or create new)',
202
+ },
203
+ transformation: {
204
+ type: 'object',
205
+ required: [
206
+ 'ruleId',
207
+ 'targetFile',
208
+ 'approach',
209
+ 'reasoning',
210
+ 'confidence',
211
+ ],
212
+ properties: {
213
+ ruleId: {
214
+ type: 'string',
215
+ description: "Rule identifier (e.g., 'standalone-migration', 'constructor-to-inject')",
216
+ },
217
+ targetFile: {
218
+ type: 'string',
219
+ description: 'Target file path (will be anonymized)',
220
+ },
221
+ approach: {
222
+ type: 'string',
223
+ minLength: 10,
224
+ maxLength: 500,
225
+ description: 'Transformation approach description',
226
+ },
227
+ reasoning: {
228
+ type: 'string',
229
+ minLength: 10,
230
+ maxLength: 1000,
231
+ description: 'Reasoning for chosen approach',
232
+ },
233
+ confidence: {
234
+ type: 'number',
235
+ minimum: 0.0,
236
+ maximum: 1.0,
237
+ description: 'AI confidence in decision (0.0-1.0)',
238
+ },
239
+ },
240
+ },
241
+ execution: {
242
+ type: 'object',
243
+ required: ['succeeded', 'duration'],
244
+ properties: {
245
+ succeeded: {
246
+ type: 'boolean',
247
+ description: 'Whether transformation succeeded',
248
+ },
249
+ duration: {
250
+ type: 'number',
251
+ description: 'Execution duration in milliseconds',
252
+ },
253
+ diffJson: {
254
+ type: 'string',
255
+ description: 'Optional structured diff JSON string',
256
+ },
257
+ error: {
258
+ type: 'string',
259
+ description: 'Optional error message if execution failed',
260
+ },
261
+ },
262
+ },
263
+ validation: {
264
+ type: 'object',
265
+ properties: {
266
+ buildSuccess: {
267
+ type: 'boolean',
268
+ description: 'Whether build succeeded',
269
+ },
270
+ testsPass: {
271
+ type: 'boolean',
272
+ description: 'Whether tests passed',
273
+ },
274
+ lintSuccess: {
275
+ type: 'boolean',
276
+ description: 'Whether lint succeeded',
277
+ },
278
+ },
279
+ },
280
+ storageLocation: {
281
+ type: 'string',
282
+ enum: ['project', 'platform', 'both'],
283
+ description: "Storage location strategy (default: 'both')",
284
+ },
285
+ },
286
+ required: ['transformation', 'execution'],
287
+ };
288
+ async execute(args) {
289
+ // Determine initial project root for config loading (args > process.cwd)
290
+ const initialProjectRoot = args['projectRoot'] ?? process.cwd();
291
+ // Load config from .angular-modernizer.json and merge with args
292
+ const fullConfig = loadConfig(initialProjectRoot);
293
+ const config = fullConfig.tools?.['collect-feedback'] ?? {};
294
+ const mergedArgs = { ...config, ...args };
295
+ const input = mergedArgs;
296
+ // Final project root priority: args > global config > initial
297
+ const projectRoot = getStringValue(args['projectRoot']) ??
298
+ getStringValue(fullConfig.projectRoot) ??
299
+ initialProjectRoot;
300
+ // Resolve platform root intelligently (searches for monorepo root)
301
+ this.platformRoot ??= resolvePlatformRoot(__dirname, '../../../..');
302
+ const platformRoot = this.platformRoot;
303
+ const storageLocation = input.storageLocation ?? 'both';
304
+ // Initialize FeedbackCollector
305
+ const collectorConfig = {
306
+ projectRoot,
307
+ platformRoot,
308
+ storageLocation,
309
+ };
310
+ const feedbackCollector = new FeedbackCollector(collectorConfig);
311
+ const salt = PrivacyFilter.generateSalt();
312
+ const privacyFilter = new PrivacyFilter({ salt, strictMode: true });
313
+ const feedbackValidator = new FeedbackValidator();
314
+ // Generate or use existing session ID
315
+ const sessionId = input.sessionId ?? randomUUID();
316
+ const feedbackId = randomUUID();
317
+ // Parse rule ID to extract category and type
318
+ const { category, type } = parseRuleId(input.transformation.ruleId);
319
+ // Detect file type from file path
320
+ const fileType = detectFileType(input.transformation.targetFile);
321
+ // Calculate complexity metrics (basic estimation from file path)
322
+ const { linesOfCode, complexity } = await estimateComplexity(input.transformation.targetFile);
323
+ // Parse structured diff if provided
324
+ let structuredDiff;
325
+ if (input.execution.diffJson) {
326
+ try {
327
+ const parsed = JSON.parse(input.execution.diffJson);
328
+ // Type guard: validate that parsed data matches StructuredDiff interface
329
+ if (isStructuredDiff(parsed)) {
330
+ structuredDiff = parsed;
331
+ }
332
+ else {
333
+ console.warn('Parsed diffJson does not match StructuredDiff interface');
334
+ }
335
+ }
336
+ catch (error) {
337
+ console.warn('Failed to parse diffJson:', error instanceof Error ? error.message : String(error));
338
+ }
339
+ }
340
+ // Build TransformationFeedback record
341
+ const feedback = {
342
+ transformationId: feedbackId,
343
+ timestamp: new Date().toISOString(),
344
+ rule: {
345
+ ruleId: input.transformation.ruleId,
346
+ ruleName: input.transformation.ruleId,
347
+ ruleType: type,
348
+ category,
349
+ },
350
+ target: {
351
+ filePathHash: privacyFilter.anonymizeFilePath(input.transformation.targetFile, salt),
352
+ fileType,
353
+ linesOfCode,
354
+ complexity,
355
+ },
356
+ decision: {
357
+ approach: input.transformation.approach,
358
+ alternatives: [],
359
+ reasoning: input.transformation.reasoning,
360
+ confidence: input.transformation.confidence,
361
+ contextUsed: ['manual-input'],
362
+ timeToDecision: 0,
363
+ },
364
+ execution: {
365
+ succeeded: input.execution.succeeded,
366
+ duration: input.execution.duration,
367
+ diff: structuredDiff,
368
+ error: input.execution.error
369
+ ? {
370
+ type: 'runtime',
371
+ message: input.execution.error,
372
+ }
373
+ : undefined,
374
+ },
375
+ validation: buildValidationResult(input.validation),
376
+ outcome: {
377
+ status: determineStatus(input.execution.succeeded, input.validation),
378
+ quality: 'unchanged',
379
+ metrics: {},
380
+ },
381
+ learnings: [],
382
+ metadata: {
383
+ source: 'manual',
384
+ collectorVersion: FEEDBACK_VERSION,
385
+ reliability: 0.8, // Manual feedback has 0.8 reliability
386
+ completenessScore: 0,
387
+ validationResult: [],
388
+ },
389
+ };
390
+ // Extract learnings FIRST (before validation)
391
+ const learnings = feedbackCollector.extractLearnings(feedback);
392
+ feedback.learnings = learnings;
393
+ // THEN validate feedback (now sees learnings for +20 points)
394
+ const validationResult = feedbackValidator.validate(feedback);
395
+ // Update metadata with validation result (includes learnings bonus)
396
+ feedback.metadata.completenessScore = validationResult.score;
397
+ feedback.metadata.validationResult = validationResult.issues;
398
+ // Track storage locations
399
+ const storageLocations = [];
400
+ let stored = false;
401
+ // Store feedback if valid (validation errors don't block storage in manual mode)
402
+ try {
403
+ // Initialize FeedbackStorage
404
+ const feedbackStorage = new FeedbackStorage({
405
+ projectRoot,
406
+ platformRoot,
407
+ storageLocation,
408
+ });
409
+ // Ensure session exists (creates minimal session if needed, race-protected)
410
+ await ensureSessionExists(sessionId, feedbackStorage, projectRoot, platformRoot, privacyFilter, salt);
411
+ // Append transformation feedback to session
412
+ await feedbackStorage.appendTransformation(sessionId, feedback);
413
+ // Determine which locations were written to
414
+ const locations = getStorageLocations(storageLocation);
415
+ for (const location of locations) {
416
+ const root = location === 'project' ? projectRoot : platformRoot;
417
+ const sessionPath = path.join(root, '.claude-feedback/sessions', `${sessionId}.jsonl`);
418
+ storageLocations.push(sessionPath);
419
+ }
420
+ stored = true;
421
+ }
422
+ catch (error) {
423
+ console.error('Failed to store feedback:', error);
424
+ stored = false;
425
+ }
426
+ // Return output (map validation issues to the expected format)
427
+ const output = {
428
+ feedbackId,
429
+ sessionId,
430
+ stored,
431
+ storageLocations,
432
+ learnings,
433
+ validationResult: {
434
+ valid: validationResult.issues.filter((i) => i.severity === 'error')
435
+ .length === 0,
436
+ score: validationResult.score,
437
+ issues: validationResult.issues.map((issue) => ({
438
+ type: ValidationType.SCHEMA, // Use ValidationType enum for validation module
439
+ severity: issue.severity === 'error'
440
+ ? ValidationSeverity.ERROR
441
+ : issue.severity === 'warning'
442
+ ? ValidationSeverity.WARNING
443
+ : ValidationSeverity.INFO,
444
+ message: issue.message,
445
+ field: issue.field,
446
+ })),
447
+ },
448
+ };
449
+ return output;
450
+ }
451
+ }
452
+ /**
453
+ * Parse rule ID to extract category and type based on naming patterns.
454
+ *
455
+ * Analyzes the rule ID string to determine if it's a transformation or analysis rule,
456
+ * and extracts the primary category from the first segment of the rule ID.
457
+ *
458
+ * @param ruleId - The rule identifier (e.g., 'standalone-migration', 'solid-dependency-inversion')
459
+ *
460
+ * @returns An object containing:
461
+ * - category: The primary category extracted from the first segment of the rule ID
462
+ * - type: Either 'transform' (for migration/refactoring rules) or 'analysis' (for inspection rules)
463
+ *
464
+ * @example
465
+ * parseRuleId('standalone-migration')
466
+ * // Returns: { category: 'standalone', type: 'transform' }
467
+ *
468
+ * parseRuleId('solid-dependency-inversion')
469
+ * // Returns: { category: 'solid', type: 'analysis' }
470
+ */
471
+ function parseRuleId(ruleId) {
472
+ // Common transformation patterns
473
+ const transformPatterns = [
474
+ 'migration',
475
+ 'transform',
476
+ 'refactor',
477
+ 'modernize',
478
+ 'convert',
479
+ 'inject',
480
+ ];
481
+ // Determine if it's a transform or analysis rule
482
+ const isTransform = transformPatterns.some((pattern) => ruleId.toLowerCase().includes(pattern));
483
+ // Extract category (use ruleId as category if no clear pattern)
484
+ const category = ruleId.split('-')[0] ?? ruleId;
485
+ return {
486
+ category,
487
+ type: isTransform ? 'transform' : 'analysis',
488
+ };
489
+ }
490
+ /**
491
+ * Detect Angular file type from file path using naming conventions.
492
+ *
493
+ * Analyzes the file name to determine the Angular file type based on standard
494
+ * Angular CLI naming conventions (e.g., '.component.ts', '.service.ts').
495
+ *
496
+ * @param filePath - The full or relative path to the file
497
+ *
498
+ * @returns The detected Angular file type:
499
+ * - 'component': Component files (*.component.ts)
500
+ * - 'service': Service files (*.service.ts)
501
+ * - 'module': NgModule files (*.module.ts)
502
+ * - 'directive': Directive files (*.directive.ts)
503
+ * - 'pipe': Pipe files (*.pipe.ts)
504
+ * - 'guard': Route guard files (*.guard.ts)
505
+ * - 'interceptor': HTTP interceptor files (*.interceptor.ts)
506
+ * - 'resolver': Route resolver files (*.resolver.ts)
507
+ * - 'model': Model/interface files (*.model.ts)
508
+ * - 'config': Configuration files (*.config.ts)
509
+ * - 'spec': Test files (*.spec.ts)
510
+ * - 'barrel': Barrel export files (index.ts, public-api.ts)
511
+ * - 'other': Any file that doesn't match the above patterns
512
+ *
513
+ * @example
514
+ * detectFileType('/src/app/user.component.ts')
515
+ * // Returns: 'component'
516
+ *
517
+ * detectFileType('auth.service.ts')
518
+ * // Returns: 'service'
519
+ */
520
+ function detectFileType(filePath) {
521
+ const fileName = path.basename(filePath).toLowerCase();
522
+ if (fileName.includes('.component.')) {
523
+ return 'component';
524
+ }
525
+ if (fileName.includes('.service.')) {
526
+ return 'service';
527
+ }
528
+ if (fileName.includes('.module.')) {
529
+ return 'module';
530
+ }
531
+ if (fileName.includes('.directive.')) {
532
+ return 'directive';
533
+ }
534
+ if (fileName.includes('.pipe.')) {
535
+ return 'pipe';
536
+ }
537
+ if (fileName.includes('.guard.')) {
538
+ return 'guard';
539
+ }
540
+ if (fileName.includes('.interceptor.')) {
541
+ return 'interceptor';
542
+ }
543
+ if (fileName.includes('.resolver.')) {
544
+ return 'resolver';
545
+ }
546
+ if (fileName.includes('.model.')) {
547
+ return 'model';
548
+ }
549
+ if (fileName.includes('.config.')) {
550
+ return 'config';
551
+ }
552
+ if (fileName.includes('.spec.')) {
553
+ return 'spec';
554
+ }
555
+ if (fileName === 'index.ts' || fileName === 'public-api.ts') {
556
+ return 'barrel';
557
+ }
558
+ return 'other';
559
+ }
560
+ /**
561
+ * Estimate complexity metrics by analyzing file contents.
562
+ *
563
+ * Reads the target file and calculates basic complexity metrics including
564
+ * non-comment lines of code and cyclomatic complexity estimate based on
565
+ * control flow statements.
566
+ *
567
+ * @param filePath - The absolute or relative path to the file to analyze
568
+ *
569
+ * @returns A promise resolving to an object containing:
570
+ * - linesOfCode: Number of non-empty, non-comment lines
571
+ * - complexity: Estimated cyclomatic complexity (count of control flow statements)
572
+ *
573
+ * @remarks
574
+ * - Fallback values (100 LOC, 5 complexity) are returned if the file cannot be read
575
+ * - Complexity calculation counts: if, for, while, switch, catch, &&, ||
576
+ * - Empty lines and single-line comments are excluded from line count
577
+ *
578
+ * @example
579
+ * await estimateComplexity('/src/app/user.service.ts')
580
+ * // Returns: { linesOfCode: 245, complexity: 18 }
581
+ *
582
+ * await estimateComplexity('/non/existent/file.ts')
583
+ * // Returns: { linesOfCode: 100, complexity: 5 } // Fallback values
584
+ */
585
+ async function estimateComplexity(filePath) {
586
+ try {
587
+ const fs = await import('node:fs/promises');
588
+ const content = await fs.readFile(filePath, 'utf-8');
589
+ const lines = content.split('\n');
590
+ const linesOfCode = lines.filter((line) => line.trim() !== '' && !line.trim().startsWith('//')).length;
591
+ // Basic complexity estimation (count control flow statements)
592
+ const complexity = (content.match(/\b(if|for|while|switch|catch|&&|\|\|)\b/g) ?? []).length;
593
+ return { linesOfCode, complexity };
594
+ }
595
+ catch (_error) {
596
+ // Fallback to default values if file cannot be read
597
+ return { linesOfCode: 100, complexity: 5 };
598
+ }
599
+ }
600
+ /**
601
+ * Type guard to validate if a parsed value matches the StructuredDiff interface.
602
+ *
603
+ * Performs runtime validation of the parsed JSON data to ensure it contains
604
+ * all required properties with correct types for the StructuredDiff format.
605
+ *
606
+ * @param value - The unknown value to validate (typically from JSON.parse)
607
+ *
608
+ * @returns True if the value is a valid StructuredDiff object, false otherwise
609
+ *
610
+ * @remarks
611
+ * Validates the presence and type of essential StructuredDiff properties:
612
+ * - linesAdded, linesRemoved, linesModified (numbers)
613
+ * - fileType, semanticIntent (strings)
614
+ * - confidence (number between 0.0 and 1.0)
615
+ *
616
+ * @example
617
+ * const parsed = JSON.parse(diffJson);
618
+ * if (isStructuredDiff(parsed)) {
619
+ * // TypeScript knows parsed is StructuredDiff
620
+ * console.info(parsed.linesAdded);
621
+ * }
622
+ */
623
+ function isStructuredDiff(value) {
624
+ if (typeof value !== 'object' || value === null) {
625
+ return false;
626
+ }
627
+ const obj = value;
628
+ return (typeof obj['linesAdded'] === 'number' &&
629
+ typeof obj['linesRemoved'] === 'number' &&
630
+ typeof obj['linesModified'] === 'number' &&
631
+ typeof obj['fileType'] === 'string' &&
632
+ typeof obj['semanticIntent'] === 'string' &&
633
+ typeof obj['confidence'] === 'number' &&
634
+ typeof obj['confidence'] === 'number' &&
635
+ obj['confidence'] >= 0 &&
636
+ typeof obj['confidence'] === 'number' &&
637
+ obj['confidence'] <= 1);
638
+ }
639
+ /**
640
+ * Build validation result object from optional validation input.
641
+ *
642
+ * Transforms the simplified validation input (boolean flags) into the detailed
643
+ * validation result structure required by the TransformationFeedback schema.
644
+ *
645
+ * @param validation - Optional validation input containing:
646
+ * - buildSuccess: Whether the build succeeded
647
+ * - testsPass: Whether tests passed
648
+ * - lintSuccess: Whether linting succeeded
649
+ *
650
+ * @returns A validation result object with detailed structures for build, tests, and lint.
651
+ * Returns empty object if no validation input provided.
652
+ *
653
+ * @remarks
654
+ * - Only includes sections for validation checks that were performed (defined in input)
655
+ * - Defaults numeric values (duration, counts) to 0 and arrays to empty
656
+ * - Manual feedback typically doesn't have detailed metrics, so defaults are appropriate
657
+ *
658
+ * @example
659
+ * buildValidationResult({ buildSuccess: true, testsPass: false })
660
+ * // Returns: {
661
+ * // build: { success: true, duration: 0, errors: [], warnings: [] },
662
+ * // tests: { success: false, duration: 0, testsRun: 0, testsPassed: 0, testsFailed: 0 }
663
+ * // }
664
+ */
665
+ function buildValidationResult(validation) {
666
+ const result = {};
667
+ if (validation?.buildSuccess !== undefined) {
668
+ result.build = {
669
+ success: validation.buildSuccess,
670
+ duration: 0,
671
+ errors: [],
672
+ warnings: [],
673
+ };
674
+ }
675
+ if (validation?.testsPass !== undefined) {
676
+ result.tests = {
677
+ success: validation.testsPass,
678
+ duration: 0,
679
+ testsRun: 0,
680
+ testsPassed: 0,
681
+ testsFailed: 0,
682
+ };
683
+ }
684
+ if (validation?.lintSuccess !== undefined) {
685
+ result.lint = {
686
+ success: validation.lintSuccess,
687
+ errors: 0,
688
+ warnings: 0,
689
+ fixable: 0,
690
+ };
691
+ }
692
+ return result;
693
+ }
694
+ /**
695
+ * Determine transformation outcome status based on execution and validation results.
696
+ *
697
+ * Analyzes the transformation execution success and optional validation results
698
+ * to classify the overall outcome into one of four status categories.
699
+ *
700
+ * @param succeeded - Whether the transformation execution succeeded
701
+ *
702
+ * @param validation - Optional validation results containing:
703
+ * - buildSuccess: Whether the post-transformation build succeeded
704
+ * - testsPass: Whether tests passed after transformation
705
+ *
706
+ * @returns The transformation status:
707
+ * - 'success': Transformation succeeded and all validations passed
708
+ * - 'partial-success': Transformation succeeded but build/tests failed
709
+ * - 'failure': Transformation execution failed
710
+ * - 'rolled-back': Not returned by this function (handled elsewhere)
711
+ *
712
+ * @remarks
713
+ * - Returns 'failure' immediately if transformation execution failed
714
+ * - Returns 'partial-success' if execution succeeded but validation failed
715
+ * - Returns 'success' only if execution succeeded and no validation failures
716
+ *
717
+ * @example
718
+ * determineStatus(true, { buildSuccess: true, testsPass: true })
719
+ * // Returns: 'success'
720
+ *
721
+ * determineStatus(true, { buildSuccess: false })
722
+ * // Returns: 'partial-success'
723
+ *
724
+ * determineStatus(false)
725
+ * // Returns: 'failure'
726
+ */
727
+ function determineStatus(succeeded, validation) {
728
+ if (!succeeded) {
729
+ return 'failure';
730
+ }
731
+ if (validation?.buildSuccess === false || validation?.testsPass === false) {
732
+ return 'partial-success';
733
+ }
734
+ return 'success';
735
+ }
736
+ /**
737
+ * Get array of storage locations based on the configured storage strategy.
738
+ *
739
+ * Converts the storage location strategy enum into an array of concrete
740
+ * location identifiers for iteration and file operations.
741
+ *
742
+ * @param storageLocation - The storage strategy ('project', 'platform', or 'both')
743
+ *
744
+ * @returns An array of location identifiers:
745
+ * - ['project']: Store only in user's project
746
+ * - ['platform']: Store only in platform root
747
+ * - ['project', 'platform']: Store in both locations (default for 'both')
748
+ *
749
+ * @remarks
750
+ * - Default case returns both locations for safety
751
+ * - Returned array determines which directories receive feedback storage
752
+ * - Used internally by ensureSessionExists() and execute() for dual-storage
753
+ *
754
+ * @example
755
+ * getStorageLocations('both')
756
+ * // Returns: ['project', 'platform']
757
+ *
758
+ * getStorageLocations('project')
759
+ * // Returns: ['project']
760
+ */
761
+ function getStorageLocations(storageLocation) {
762
+ switch (storageLocation) {
763
+ case 'project':
764
+ return ['project'];
765
+ case 'platform':
766
+ return ['platform'];
767
+ case 'both':
768
+ return ['project', 'platform'];
769
+ default:
770
+ return ['project', 'platform'];
771
+ }
772
+ }
773
+ //# sourceMappingURL=collect-feedback.js.map