vibecodingmachine-core 2026.2.20-438 → 2026.2.26-1642

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 (202) hide show
  1. package/README.md +240 -0
  2. package/package.json +10 -2
  3. package/src/agents/Agent.js +300 -0
  4. package/src/agents/AgentAdditionService.js +311 -0
  5. package/src/agents/AgentCheckService.js +690 -0
  6. package/src/agents/AgentInstallationService.js +140 -0
  7. package/src/agents/AgentSetupService.js +467 -0
  8. package/src/agents/AgentStatus.js +183 -0
  9. package/src/agents/AgentVerificationService.js +634 -0
  10. package/src/agents/ConfigurationSchemaValidator.js +543 -0
  11. package/src/agents/EnvironmentConfigurationManager.js +602 -0
  12. package/src/agents/InstallationErrorHandler.js +372 -0
  13. package/src/agents/InstallationLog.js +363 -0
  14. package/src/agents/InstallationMethod.js +510 -0
  15. package/src/agents/InstallationOrchestrator.js +352 -0
  16. package/src/agents/InstallationProgressReporter.js +372 -0
  17. package/src/agents/InstallationRetryManager.js +322 -0
  18. package/src/agents/InstallationType.js +254 -0
  19. package/src/agents/OperationTypes.js +310 -0
  20. package/src/agents/PerformanceMetricsCollector.js +493 -0
  21. package/src/agents/SecurityValidationService.js +534 -0
  22. package/src/agents/VerificationTest.js +354 -0
  23. package/src/agents/VerificationType.js +226 -0
  24. package/src/agents/WindowsPermissionHandler.js +518 -0
  25. package/src/agents/config/AgentConfigManager.js +393 -0
  26. package/src/agents/config/AgentDefaultsRegistry.js +373 -0
  27. package/src/agents/config/ConfigValidator.js +281 -0
  28. package/src/agents/discovery/AgentDiscoveryService.js +707 -0
  29. package/src/agents/logging/AgentLogger.js +511 -0
  30. package/src/agents/status/AgentStatusManager.js +481 -0
  31. package/src/agents/storage/FileManager.js +454 -0
  32. package/src/agents/verification/AgentCommunicationTester.js +474 -0
  33. package/src/agents/verification/BaseVerifier.js +430 -0
  34. package/src/agents/verification/CommandVerifier.js +480 -0
  35. package/src/agents/verification/FileOperationVerifier.js +453 -0
  36. package/src/agents/verification/ResultAnalyzer.js +707 -0
  37. package/src/agents/verification/TestRequirementManager.js +495 -0
  38. package/src/agents/verification/VerificationRunner.js +433 -0
  39. package/src/agents/windows/BaseWindowsInstaller.js +441 -0
  40. package/src/agents/windows/ChocolateyInstaller.js +509 -0
  41. package/src/agents/windows/DirectInstaller.js +443 -0
  42. package/src/agents/windows/InstallerFactory.js +391 -0
  43. package/src/agents/windows/NpmInstaller.js +505 -0
  44. package/src/agents/windows/PowerShellInstaller.js +458 -0
  45. package/src/agents/windows/WinGetInstaller.js +390 -0
  46. package/src/analysis/analysis-reporter.js +132 -0
  47. package/src/analysis/boundary-detector.js +712 -0
  48. package/src/analysis/categorizer.js +340 -0
  49. package/src/analysis/codebase-scanner.js +384 -0
  50. package/src/analysis/line-counter.js +513 -0
  51. package/src/analysis/priority-calculator.js +679 -0
  52. package/src/analysis/report/analysis-report.js +250 -0
  53. package/src/analysis/report/package-analyzer.js +278 -0
  54. package/src/analysis/report/recommendation-generator.js +382 -0
  55. package/src/analysis/report/statistics-generator.js +515 -0
  56. package/src/analysis/reports/analysis-report-model.js +101 -0
  57. package/src/analysis/reports/recommendation-generator.js +283 -0
  58. package/src/analysis/reports/report-generators.js +191 -0
  59. package/src/analysis/reports/statistics-calculator.js +231 -0
  60. package/src/analysis/reports/trend-analyzer.js +219 -0
  61. package/src/analysis/strategy-generator.js +814 -0
  62. package/src/auto-mode/AutoModeBusinessLogic.js +836 -0
  63. package/src/config/refactoring-config.js +307 -0
  64. package/src/health-tracking/json-storage.js +38 -2
  65. package/src/ide-integration/applescript-manager-core.js +233 -0
  66. package/src/ide-integration/applescript-manager.cjs +357 -28
  67. package/src/ide-integration/applescript-manager.js +89 -3599
  68. package/src/ide-integration/cdp-manager.js +306 -0
  69. package/src/ide-integration/claude-code-cli-manager.cjs +1 -1
  70. package/src/ide-integration/continuation-handler.js +337 -0
  71. package/src/ide-integration/ide-status-checker.js +292 -0
  72. package/src/ide-integration/macos-ide-manager.js +627 -0
  73. package/src/ide-integration/macos-text-sender.js +528 -0
  74. package/src/ide-integration/response-reader.js +548 -0
  75. package/src/ide-integration/windows-automation-manager.js +121 -0
  76. package/src/ide-integration/windows-ide-manager.js +373 -0
  77. package/src/index.cjs +25 -3
  78. package/src/index.js +15 -1
  79. package/src/llm/direct-llm-manager.cjs +90 -2
  80. package/src/models/compliance-report.js +538 -0
  81. package/src/models/file-analysis.js +681 -0
  82. package/src/models/refactoring-plan.js +770 -0
  83. package/src/monitoring/alert-system.js +834 -0
  84. package/src/monitoring/compliance-progress-tracker.js +437 -0
  85. package/src/monitoring/continuous-scan-notifications.js +661 -0
  86. package/src/monitoring/continuous-scanner.js +279 -0
  87. package/src/monitoring/file-monitor/file-analyzer.js +262 -0
  88. package/src/monitoring/file-monitor/file-monitor.js +237 -0
  89. package/src/monitoring/file-monitor/watcher.js +194 -0
  90. package/src/monitoring/file-monitor.js +17 -0
  91. package/src/monitoring/notification-manager.js +437 -0
  92. package/src/monitoring/scanner-core.js +368 -0
  93. package/src/monitoring/scanner-events.js +214 -0
  94. package/src/monitoring/violation-notification-system.js +515 -0
  95. package/src/refactoring/boundaries/cohesion-analyzer.js +316 -0
  96. package/src/refactoring/boundaries/extraction-result.js +285 -0
  97. package/src/refactoring/boundaries/extraction-strategies.js +392 -0
  98. package/src/refactoring/boundaries/module-boundary.js +209 -0
  99. package/src/refactoring/boundary/boundary-detector.js +741 -0
  100. package/src/refactoring/boundary/boundary-types.js +405 -0
  101. package/src/refactoring/boundary/extraction-strategies.js +554 -0
  102. package/src/refactoring/boundary-extraction-result.js +77 -0
  103. package/src/refactoring/boundary-extraction-strategies.js +330 -0
  104. package/src/refactoring/boundary-extractor.js +384 -0
  105. package/src/refactoring/boundary-types.js +46 -0
  106. package/src/refactoring/circular/circular-dependency.js +88 -0
  107. package/src/refactoring/circular/cycle-detection.js +147 -0
  108. package/src/refactoring/circular/dependency-node.js +82 -0
  109. package/src/refactoring/circular/dependency-result.js +107 -0
  110. package/src/refactoring/circular/dependency-types.js +58 -0
  111. package/src/refactoring/circular/graph-builder.js +213 -0
  112. package/src/refactoring/circular/resolution-strategy.js +72 -0
  113. package/src/refactoring/circular/strategy-generator.js +229 -0
  114. package/src/refactoring/circular-dependency-resolver-original.js +809 -0
  115. package/src/refactoring/circular-dependency-resolver.js +200 -0
  116. package/src/refactoring/code-mover.js +761 -0
  117. package/src/refactoring/file-splitter.js +696 -0
  118. package/src/refactoring/functionality-validator.js +816 -0
  119. package/src/refactoring/import-manager.js +774 -0
  120. package/src/refactoring/module-boundary.js +107 -0
  121. package/src/refactoring/refactoring-executor.js +672 -0
  122. package/src/refactoring/refactoring-rollback.js +614 -0
  123. package/src/refactoring/test-validator.js +631 -0
  124. package/src/requirement-management/default-requirement-manager.js +321 -0
  125. package/src/requirement-management/requirement-file-parser.js +159 -0
  126. package/src/requirement-management/requirement-sequencer.js +221 -0
  127. package/src/rui/commands/AgentCommandParser.js +600 -0
  128. package/src/rui/commands/AgentCommands.js +487 -0
  129. package/src/rui/commands/AgentResponseFormatter.js +832 -0
  130. package/src/scripts/verify-full-compliance.js +269 -0
  131. package/src/sync/sync-engine-core.js +1 -0
  132. package/src/sync/sync-engine-remote-handlers.js +135 -0
  133. package/src/task-generation/automated-task-generator.js +351 -0
  134. package/src/task-generation/prioritizer.js +287 -0
  135. package/src/task-generation/task-list-updater.js +215 -0
  136. package/src/task-generation/task-management-integration.js +480 -0
  137. package/src/task-generation/task-manager-integration.js +270 -0
  138. package/src/task-generation/violation-task-generator.js +474 -0
  139. package/src/task-management/continuous-scan-integration.js +342 -0
  140. package/src/timeout-management/index.js +12 -3
  141. package/src/timeout-management/response-time-tracker.js +167 -0
  142. package/src/timeout-management/timeout-calculator.js +159 -0
  143. package/src/timeout-management/timeout-config-manager.js +172 -0
  144. package/src/utils/ast-analyzer.js +417 -0
  145. package/src/utils/current-requirement-manager.js +276 -0
  146. package/src/utils/current-requirement-operations.js +472 -0
  147. package/src/utils/dependency-mapper.js +456 -0
  148. package/src/utils/download-with-progress.js +4 -2
  149. package/src/utils/electron-update-checker.js +4 -1
  150. package/src/utils/file-size-analyzer.js +272 -0
  151. package/src/utils/import-updater.js +280 -0
  152. package/src/utils/refactoring-tools.js +512 -0
  153. package/src/utils/report-generator.js +569 -0
  154. package/src/utils/reports/report-analysis.js +218 -0
  155. package/src/utils/reports/report-types.js +55 -0
  156. package/src/utils/reports/summary-generators.js +102 -0
  157. package/src/utils/requirement-file-management.js +157 -0
  158. package/src/utils/requirement-helpers/requirement-file-ops.js +392 -0
  159. package/src/utils/requirement-helpers/requirement-mover.js +414 -0
  160. package/src/utils/requirement-helpers/requirement-parser.js +326 -0
  161. package/src/utils/requirement-helpers/requirement-status.js +320 -0
  162. package/src/utils/requirement-helpers-new.js +55 -0
  163. package/src/utils/requirement-helpers-refactored.js +367 -0
  164. package/src/utils/requirement-helpers.js +291 -1191
  165. package/src/utils/requirement-movement-operations.js +450 -0
  166. package/src/utils/requirement-movement.js +312 -0
  167. package/src/utils/requirement-parsing-helpers.js +56 -0
  168. package/src/utils/requirement-statistics.js +200 -0
  169. package/src/utils/requirement-text-utils.js +58 -0
  170. package/src/utils/rollback/rollback-handlers.js +125 -0
  171. package/src/utils/rollback/rollback-operation.js +63 -0
  172. package/src/utils/rollback/rollback-recorder.js +166 -0
  173. package/src/utils/rollback/rollback-state-manager.js +175 -0
  174. package/src/utils/rollback/rollback-types.js +33 -0
  175. package/src/utils/rollback/rollback-utils.js +110 -0
  176. package/src/utils/rollback-manager-original.js +569 -0
  177. package/src/utils/rollback-manager.js +202 -0
  178. package/src/utils/smoke-test-cli.js +362 -0
  179. package/src/utils/smoke-test-gui.js +351 -0
  180. package/src/utils/smoke-test-orchestrator.js +321 -0
  181. package/src/utils/smoke-test-runner.js +60 -0
  182. package/src/utils/smoke-test-web.js +347 -0
  183. package/src/utils/specification-helpers.js +39 -13
  184. package/src/utils/specification-migration.js +97 -0
  185. package/src/utils/test-runner.js +579 -0
  186. package/src/utils/validation-framework.js +518 -0
  187. package/src/validation/compliance-analyzer.js +197 -0
  188. package/src/validation/compliance-report-generator.js +343 -0
  189. package/src/validation/compliance-reporter.js +711 -0
  190. package/src/validation/compliance-rules.js +127 -0
  191. package/src/validation/constitution-validator-new.js +196 -0
  192. package/src/validation/constitution-validator.js +17 -0
  193. package/src/validation/file-validators.js +170 -0
  194. package/src/validation/line-limit/file-analyzer.js +201 -0
  195. package/src/validation/line-limit/line-limit-validator.js +208 -0
  196. package/src/validation/line-limit/validation-result.js +144 -0
  197. package/src/validation/line-limit-core.js +225 -0
  198. package/src/validation/line-limit-reporter.js +134 -0
  199. package/src/validation/line-limit-result.js +125 -0
  200. package/src/validation/line-limit-validator.js +41 -0
  201. package/src/validation/metrics-calculator.js +660 -0
  202. package/src/sync/sync-engine-backup.js +0 -559
@@ -0,0 +1,672 @@
1
+ /**
2
+ * Refactoring Executor
3
+ *
4
+ * Orchestrates the entire refactoring process.
5
+ * Coordinates multiple refactoring operations and ensures consistency.
6
+ */
7
+
8
+ const { FileSplitter } = require('./file-splitter');
9
+ const { BoundaryExtractor } = require('./boundary-extractor');
10
+ const { CodeMover } = require('./code-mover');
11
+ const { ImportManager } = require('./import-manager');
12
+ const { CircularDependencyResolver } = require('./circular-dependency-resolver');
13
+ const { RollbackManager } = require('../utils/rollback-manager');
14
+ const { TestRunner } = require('../utils/test-runner');
15
+
16
+ /**
17
+ * Execution status
18
+ */
19
+ const EXECUTION_STATUS = {
20
+ PENDING: 'pending',
21
+ RUNNING: 'running',
22
+ COMPLETED: 'completed',
23
+ FAILED: 'failed',
24
+ PAUSED: 'paused',
25
+ CANCELLED: 'cancelled'
26
+ };
27
+
28
+ /**
29
+ * Refactoring operation class
30
+ */
31
+ class RefactoringOperation {
32
+ constructor(type, targetPath, options = {}) {
33
+ this.id = this.generateId();
34
+ this.type = type;
35
+ this.targetPath = targetPath;
36
+ this.options = options;
37
+ this.status = EXECUTION_STATUS.PENDING;
38
+ this.progress = 0;
39
+ this.result = null;
40
+ this.error = null;
41
+ this.startTime = null;
42
+ this.endTime = null;
43
+ this.dependencies = [];
44
+ this.dependents = [];
45
+ this.metadata = {
46
+ createdAt: new Date().toISOString(),
47
+ estimatedDuration: options.estimatedDuration || 0,
48
+ priority: options.priority || 'medium'
49
+ };
50
+ }
51
+
52
+ generateId() {
53
+ return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
54
+ }
55
+
56
+ setStatus(status) {
57
+ this.status = status;
58
+ if (status === EXECUTION_STATUS.RUNNING && !this.startTime) {
59
+ this.startTime = new Date().toISOString();
60
+ }
61
+ if ([EXECUTION_STATUS.COMPLETED, EXECUTION_STATUS.FAILED, EXECUTION_STATUS.CANCELLED].includes(status)) {
62
+ this.endTime = new Date().toISOString();
63
+ }
64
+ }
65
+
66
+ setProgress(progress) {
67
+ this.progress = Math.max(0, Math.min(100, progress));
68
+ }
69
+
70
+ setResult(result) {
71
+ this.result = result;
72
+ }
73
+
74
+ setError(error) {
75
+ this.error = error;
76
+ }
77
+
78
+ addDependency(operationId) {
79
+ if (!this.dependencies.includes(operationId)) {
80
+ this.dependencies.push(operationId);
81
+ }
82
+ }
83
+
84
+ addDependent(operationId) {
85
+ if (!this.dependents.includes(operationId)) {
86
+ this.dependents.push(operationId);
87
+ }
88
+ }
89
+
90
+ getDuration() {
91
+ if (!this.startTime) return 0;
92
+ const end = this.endTime ? new Date(this.endTime) : new Date();
93
+ const start = new Date(this.startTime);
94
+ return (end - start) / 1000; // seconds
95
+ }
96
+
97
+ isReady(dependencies) {
98
+ if (this.status !== EXECUTION_STATUS.PENDING) return false;
99
+
100
+ for (const depId of this.dependencies) {
101
+ const dep = dependencies.get(depId);
102
+ if (!dep || dep.status !== EXECUTION_STATUS.COMPLETED) {
103
+ return false;
104
+ }
105
+ }
106
+
107
+ return true;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Refactoring execution plan class
113
+ */
114
+ class RefactoringPlan {
115
+ constructor(name) {
116
+ this.id = this.generateId();
117
+ this.name = name;
118
+ this.operations = new Map();
119
+ this.status = EXECUTION_STATUS.PENDING;
120
+ this.metadata = {
121
+ createdAt: new Date().toISOString(),
122
+ estimatedDuration: 0,
123
+ totalOperations: 0
124
+ };
125
+ }
126
+
127
+ generateId() {
128
+ return `plan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
129
+ }
130
+
131
+ addOperation(operation) {
132
+ this.operations.set(operation.id, operation);
133
+ this.metadata.totalOperations = this.operations.size;
134
+ this.updateEstimatedDuration();
135
+ }
136
+
137
+ updateEstimatedDuration() {
138
+ this.metadata.estimatedDuration = Array.from(this.operations.values())
139
+ .reduce((total, op) => total + (op.metadata.estimatedDuration || 0), 0);
140
+ }
141
+
142
+ getReadyOperations() {
143
+ return Array.from(this.operations.values())
144
+ .filter(op => op.isReady(this.operations));
145
+ }
146
+
147
+ getCompletedOperations() {
148
+ return Array.from(this.operations.values())
149
+ .filter(op => op.status === EXECUTION_STATUS.COMPLETED);
150
+ }
151
+
152
+ getFailedOperations() {
153
+ return Array.from(this.operations.values())
154
+ .filter(op => op.status === EXECUTION_STATUS.FAILED);
155
+ }
156
+
157
+ getProgress() {
158
+ if (this.operations.size === 0) return 0;
159
+
160
+ const completed = this.getCompletedOperations().length;
161
+ return Math.round((completed / this.operations.size) * 100);
162
+ }
163
+
164
+ setStatus(status) {
165
+ this.status = status;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Refactoring executor result class
171
+ */
172
+ class RefactoringExecutorResult {
173
+ constructor(plan) {
174
+ this.plan = plan;
175
+ this.success = false;
176
+ this.executedOperations = 0;
177
+ this.failedOperations = 0;
178
+ this.skippedOperations = 0;
179
+ this.duration = 0;
180
+ this.errors = [];
181
+ this.warnings = [];
182
+ this.rollbackPerformed = false;
183
+ this.metadata = {
184
+ executedAt: new Date().toISOString(),
185
+ environment: process.env.NODE_ENV || 'development'
186
+ };
187
+ }
188
+
189
+ addError(error) {
190
+ this.errors.push({
191
+ message: error.message,
192
+ timestamp: new Date().toISOString(),
193
+ stack: error.stack
194
+ });
195
+ }
196
+
197
+ addWarning(warning) {
198
+ this.warnings.push({
199
+ message: warning,
200
+ timestamp: new Date().toISOString()
201
+ });
202
+ }
203
+
204
+ setSuccess(success) {
205
+ this.success = success;
206
+ }
207
+
208
+ setRollbackPerformed(rollbackPerformed) {
209
+ this.rollbackPerformed = rollbackPerformed;
210
+ }
211
+
212
+ getSummary() {
213
+ return {
214
+ planId: this.plan.id,
215
+ planName: this.plan.name,
216
+ success: this.success,
217
+ executedOperations: this.executedOperations,
218
+ failedOperations: this.failedOperations,
219
+ skippedOperations: this.skippedOperations,
220
+ totalOperations: this.plan.operations.size,
221
+ duration: this.duration,
222
+ progress: this.plan.getProgress(),
223
+ errorCount: this.errors.length,
224
+ warningCount: this.warnings.length,
225
+ rollbackPerformed: this.rollbackPerformed
226
+ };
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Refactoring executor class
232
+ */
233
+ class RefactoringExecutor {
234
+ constructor(options = {}) {
235
+ this.options = {
236
+ maxConcurrentOperations: 3,
237
+ enableRollback: true,
238
+ runTests: true,
239
+ validateAfterOperation: true,
240
+ pauseOnError: true,
241
+ ...options
242
+ };
243
+
244
+ this.rollbackManager = new RollbackManager();
245
+ this.testRunner = new TestRunner();
246
+ this.importManager = new ImportManager();
247
+ this.fileSplitter = new FileSplitter();
248
+ this.boundaryExtractor = new BoundaryExtractor();
249
+ this.codeMover = new CodeMover();
250
+ this.circularDependencyResolver = new CircularDependencyResolver();
251
+
252
+ this.currentPlan = null;
253
+ this.isExecuting = false;
254
+ this.executionQueue = [];
255
+ }
256
+
257
+ /**
258
+ * Execute a refactoring plan
259
+ */
260
+ async executePlan(plan) {
261
+ if (this.isExecuting) {
262
+ throw new Error('Executor is already running a plan');
263
+ }
264
+
265
+ this.currentPlan = plan;
266
+ this.isExecuting = true;
267
+ plan.setStatus(EXECUTION_STATUS.RUNNING);
268
+
269
+ const result = new RefactoringExecutorResult(plan);
270
+ const startTime = Date.now();
271
+
272
+ try {
273
+ console.log(`Executing refactoring plan: ${plan.name}`);
274
+ console.log(`Operations: ${plan.operations.size}`);
275
+
276
+ // Run baseline tests if enabled
277
+ if (this.options.runTests) {
278
+ console.log('Running baseline tests...');
279
+ await this.testRunner.runBaseline();
280
+ }
281
+
282
+ // Execute operations in dependency order
283
+ await this.executeOperations(plan, result);
284
+
285
+ // Run validation tests if enabled
286
+ if (this.options.runTests) {
287
+ console.log('Running validation tests...');
288
+ const testResult = await this.testRunner.runValidation();
289
+
290
+ if (testResult.hasRegressions) {
291
+ throw new Error('Tests detected regressions after refactoring');
292
+ }
293
+ }
294
+
295
+ result.setSuccess(true);
296
+ plan.setStatus(EXECUTION_STATUS.COMPLETED);
297
+
298
+ console.log(`Plan execution completed successfully`);
299
+
300
+ } catch (error) {
301
+ result.addError(error);
302
+ result.setSuccess(false);
303
+ plan.setStatus(EXECUTION_STATUS.FAILED);
304
+
305
+ console.error(`Plan execution failed: ${error.message}`);
306
+
307
+ // Rollback if enabled and there were failures
308
+ if (this.options.enableRollback && result.failedOperations > 0) {
309
+ console.log('Performing rollback...');
310
+ await this.rollbackManager.rollback();
311
+ result.setRollbackPerformed(true);
312
+ }
313
+
314
+ if (this.options.pauseOnError) {
315
+ console.log('Execution paused due to error');
316
+ plan.setStatus(EXECUTION_STATUS.PAUSED);
317
+ }
318
+
319
+ } finally {
320
+ result.duration = (Date.now() - startTime) / 1000;
321
+ this.isExecuting = false;
322
+ this.currentPlan = null;
323
+ }
324
+
325
+ return result;
326
+ }
327
+
328
+ /**
329
+ * Execute operations in dependency order
330
+ */
331
+ async executeOperations(plan, result) {
332
+ const executedOperations = new Set();
333
+ let pendingOperations = new Set(plan.operations.keys());
334
+
335
+ while (pendingOperations.size > 0) {
336
+ // Find ready operations
337
+ const readyOperations = Array.from(pendingOperations)
338
+ .map(id => plan.operations.get(id))
339
+ .filter(op => op.isReady(plan.operations) && !executedOperations.has(op.id));
340
+
341
+ if (readyOperations.length === 0) {
342
+ // Check for circular dependencies or blocked operations
343
+ const blockedOps = Array.from(pendingOperations)
344
+ .map(id => plan.operations.get(id))
345
+ .filter(op => !executedOperations.has(op.id));
346
+
347
+ if (blockedOps.length > 0) {
348
+ throw new Error(`Circular dependency detected or operations blocked: ${blockedOps.map(op => op.id).join(', ')}`);
349
+ }
350
+ break;
351
+ }
352
+
353
+ // Execute ready operations (with concurrency limit)
354
+ const batchSize = Math.min(readyOperations.length, this.options.maxConcurrentOperations);
355
+ const batch = readyOperations.slice(0, batchSize);
356
+
357
+ await Promise.all(batch.map(async operation => {
358
+ try {
359
+ await this.executeOperation(operation, result);
360
+ executedOperations.add(operation.id);
361
+ pendingOperations.delete(operation.id);
362
+ result.executedOperations++;
363
+ } catch (error) {
364
+ result.addError(error);
365
+ result.failedOperations++;
366
+ executedOperations.add(operation.id);
367
+ pendingOperations.delete(operation.id);
368
+
369
+ // Don't continue on error if pauseOnError is enabled
370
+ if (this.options.pauseOnError) {
371
+ throw error;
372
+ }
373
+ }
374
+ }));
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Execute a single operation
380
+ */
381
+ async executeOperation(operation, result) {
382
+ console.log(`Executing operation: ${operation.type} on ${operation.targetPath}`);
383
+ operation.setStatus(EXECUTION_STATUS.RUNNING);
384
+ operation.setProgress(0);
385
+
386
+ try {
387
+ let operationResult = null;
388
+
389
+ switch (operation.type) {
390
+ case 'split_file':
391
+ operationResult = await this.executeSplitFile(operation);
392
+ break;
393
+
394
+ case 'extract_boundaries':
395
+ operationResult = await this.executeExtractBoundaries(operation);
396
+ break;
397
+
398
+ case 'move_code':
399
+ operationResult = await this.executeMoveCode(operation);
400
+ break;
401
+
402
+ case 'update_imports':
403
+ operationResult = await this.executeUpdateImports(operation);
404
+ break;
405
+
406
+ case 'resolve_circular_deps':
407
+ operationResult = await this.executeResolveCircularDeps(operation);
408
+ break;
409
+
410
+ default:
411
+ throw new Error(`Unknown operation type: ${operation.type}`);
412
+ }
413
+
414
+ operation.setResult(operationResult);
415
+ operation.setStatus(EXECUTION_STATUS.COMPLETED);
416
+ operation.setProgress(100);
417
+
418
+ console.log(`Operation completed: ${operation.id}`);
419
+
420
+ } catch (error) {
421
+ operation.setError(error);
422
+ operation.setStatus(EXECUTION_STATUS.FAILED);
423
+ throw error;
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Execute file split operation
429
+ */
430
+ async executeSplitFile(operation) {
431
+ const { targetPath, splitPoints } = operation.options;
432
+
433
+ // Read file analysis (would come from operation context)
434
+ const fileAnalysis = await this.analyzeFile(targetPath);
435
+
436
+ const splitResult = await this.fileSplitter.splitFile(fileAnalysis, splitPoints);
437
+
438
+ if (!splitResult.success) {
439
+ throw new Error(`File split failed: ${splitResult.errors.map(e => e.message).join(', ')}`);
440
+ }
441
+
442
+ return splitResult;
443
+ }
444
+
445
+ /**
446
+ * Execute boundary extraction operation
447
+ */
448
+ async executeExtractBoundaries(operation) {
449
+ const { targetPath, boundaries } = operation.options;
450
+
451
+ const extractionResult = await this.boundaryExtractor.extractBoundaries(targetPath);
452
+
453
+ if (extractionResult.errors.length > 0) {
454
+ throw new Error(`Boundary extraction failed: ${extractionResult.errors.map(e => e.message).join(', ')}`);
455
+ }
456
+
457
+ return extractionResult;
458
+ }
459
+
460
+ /**
461
+ * Execute code move operation
462
+ */
463
+ async executeMoveCode(operation) {
464
+ const { sourcePath, targetPath, segment } = operation.options;
465
+
466
+ const moveOperation = {
467
+ type: 'extract',
468
+ sourcePath,
469
+ targetPath,
470
+ segmentName: segment.name,
471
+ startLine: segment.startLine,
472
+ endLine: segment.endLine
473
+ };
474
+
475
+ const moveResult = await this.codeMover.executeMove(moveOperation);
476
+
477
+ if (!moveResult.success) {
478
+ throw new Error(`Code move failed: ${moveResult.errors.map(e => e.message).join(', ')}`);
479
+ }
480
+
481
+ return moveResult;
482
+ }
483
+
484
+ /**
485
+ * Execute import update operation
486
+ */
487
+ async executeUpdateImports(operation) {
488
+ const { targetPath, changes } = operation.options;
489
+
490
+ const updateResult = await this.importManager.updateImports(targetPath, changes);
491
+
492
+ if (!updateResult.success) {
493
+ throw new Error(`Import update failed: ${updateResult.errors.map(e => e.message).join(', ')}`);
494
+ }
495
+
496
+ return updateResult;
497
+ }
498
+
499
+ /**
500
+ * Execute circular dependency resolution
501
+ */
502
+ async executeResolveCircularDeps(operation) {
503
+ const { rootPath, strategies } = operation.options;
504
+
505
+ const analysisResult = await this.circularDependencyResolver.analyze(rootPath);
506
+
507
+ if (analysisResult.errors.length > 0) {
508
+ throw new Error(`Circular dependency analysis failed: ${analysisResult.errors.map(e => e.message).join(', ')}`);
509
+ }
510
+
511
+ return analysisResult;
512
+ }
513
+
514
+ /**
515
+ * Analyze file for refactoring
516
+ */
517
+ async analyzeFile(filePath) {
518
+ // This would create a FileAnalysis object
519
+ // For now, return a placeholder
520
+ return {
521
+ filePath,
522
+ lineCount: 100,
523
+ needsRefactoring: true,
524
+ boundaries: null
525
+ };
526
+ }
527
+
528
+ /**
529
+ * Create refactoring plan from analysis results
530
+ */
531
+ createPlan(analysisResults, options = {}) {
532
+ const plan = new RefactoringResults(options.name || 'Auto-generated Plan');
533
+
534
+ // Create operations based on analysis
535
+ for (const analysis of analysisResults.files || []) {
536
+ if (analysis.needsRefactoring) {
537
+ // Add split operation
538
+ const splitOp = new RefactoringOperation('split_file', analysis.filePath, {
539
+ estimatedDuration: 5,
540
+ priority: analysis.urgentRefactoring ? 'high' : 'medium'
541
+ });
542
+ plan.addOperation(splitOp);
543
+ }
544
+ }
545
+
546
+ return plan;
547
+ }
548
+
549
+ /**
550
+ * Cancel current execution
551
+ */
552
+ async cancelExecution() {
553
+ if (!this.isExecuting || !this.currentPlan) {
554
+ return false;
555
+ }
556
+
557
+ this.currentPlan.setStatus(EXECUTION_STATUS.CANCELLED);
558
+ this.isExecuting = false;
559
+
560
+ // Cancel running operations
561
+ for (const operation of this.currentPlan.operations.values()) {
562
+ if (operation.status === EXECUTION_STATUS.RUNNING) {
563
+ operation.setStatus(EXECUTION_STATUS.CANCELLED);
564
+ }
565
+ }
566
+
567
+ return true;
568
+ }
569
+
570
+ /**
571
+ * Get execution status
572
+ */
573
+ getExecutionStatus() {
574
+ if (!this.currentPlan) {
575
+ return {
576
+ isExecuting: false,
577
+ plan: null,
578
+ progress: 0
579
+ };
580
+ }
581
+
582
+ return {
583
+ isExecuting: this.isExecuting,
584
+ plan: {
585
+ id: this.currentPlan.id,
586
+ name: this.currentPlan.name,
587
+ status: this.currentPlan.status,
588
+ progress: this.currentPlan.getProgress(),
589
+ totalOperations: this.currentPlan.operations.size,
590
+ completedOperations: this.currentPlan.getCompletedOperations().length,
591
+ failedOperations: this.currentPlan.getFailedOperations().length
592
+ }
593
+ };
594
+ }
595
+
596
+ /**
597
+ * Validate plan before execution
598
+ */
599
+ validatePlan(plan) {
600
+ const issues = [];
601
+
602
+ // Check for circular dependencies
603
+ const visited = new Set();
604
+ const recursionStack = new Set();
605
+
606
+ function hasCircularDeps(operationId) {
607
+ if (recursionStack.has(operationId)) {
608
+ return true;
609
+ }
610
+
611
+ if (visited.has(operationId)) {
612
+ return false;
613
+ }
614
+
615
+ visited.add(operationId);
616
+ recursionStack.add(operationId);
617
+
618
+ const operation = plan.operations.get(operationId);
619
+ if (operation) {
620
+ for (const depId of operation.dependencies) {
621
+ if (hasCircularDeps(depId)) {
622
+ return true;
623
+ }
624
+ }
625
+ }
626
+
627
+ recursionStack.delete(operationId);
628
+ return false;
629
+ }
630
+
631
+ for (const operationId of plan.operations.keys()) {
632
+ if (hasCircularDeps(operationId)) {
633
+ issues.push(`Circular dependency detected for operation: ${operationId}`);
634
+ }
635
+ }
636
+
637
+ // Check for missing dependencies
638
+ for (const operation of plan.operations.values()) {
639
+ for (const depId of operation.dependencies) {
640
+ if (!plan.operations.has(depId)) {
641
+ issues.push(`Missing dependency: ${depId} for operation: ${operation.id}`);
642
+ }
643
+ }
644
+ }
645
+
646
+ return {
647
+ isValid: issues.length === 0,
648
+ issues
649
+ };
650
+ }
651
+
652
+ /**
653
+ * Get execution statistics
654
+ */
655
+ getStatistics() {
656
+ return {
657
+ totalPlansExecuted: 0, // Would track this
658
+ averageExecutionTime: 0,
659
+ successRate: 0,
660
+ mostCommonOperations: {},
661
+ errorPatterns: []
662
+ };
663
+ }
664
+ }
665
+
666
+ module.exports = {
667
+ RefactoringExecutor,
668
+ RefactoringPlan,
669
+ RefactoringOperation,
670
+ RefactoringExecutorResult,
671
+ EXECUTION_STATUS
672
+ };