baseguard 1.0.5 → 1.0.6

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 (80) hide show
  1. package/dist/ai/gemini-analyzer.d.ts.map +1 -1
  2. package/dist/ai/gemini-analyzer.js +1 -1
  3. package/dist/ai/gemini-analyzer.js.map +1 -1
  4. package/dist/ai/gemini-code-fixer.d.ts.map +1 -1
  5. package/dist/ai/gemini-code-fixer.js +2 -7
  6. package/dist/ai/gemini-code-fixer.js.map +1 -1
  7. package/dist/ai/jules-implementer.d.ts +8 -0
  8. package/dist/ai/jules-implementer.d.ts.map +1 -1
  9. package/dist/ai/jules-implementer.js +115 -17
  10. package/dist/ai/jules-implementer.js.map +1 -1
  11. package/package.json +1 -1
  12. package/src/ai/__tests__/gemini-analyzer.test.ts +0 -181
  13. package/src/ai/agentkit-orchestrator.ts +0 -534
  14. package/src/ai/fix-manager.ts +0 -362
  15. package/src/ai/gemini-analyzer.ts +0 -665
  16. package/src/ai/gemini-code-fixer.ts +0 -539
  17. package/src/ai/index.ts +0 -4
  18. package/src/ai/jules-implementer.ts +0 -504
  19. package/src/ai/unified-code-fixer.ts +0 -347
  20. package/src/commands/automation.ts +0 -344
  21. package/src/commands/check.ts +0 -298
  22. package/src/commands/config.ts +0 -584
  23. package/src/commands/fix.ts +0 -269
  24. package/src/commands/index.ts +0 -7
  25. package/src/commands/init.ts +0 -156
  26. package/src/commands/status.ts +0 -307
  27. package/src/core/api-key-manager.ts +0 -298
  28. package/src/core/baseguard.ts +0 -757
  29. package/src/core/baseline-checker.ts +0 -566
  30. package/src/core/cache-manager.ts +0 -272
  31. package/src/core/configuration-recovery.ts +0 -672
  32. package/src/core/configuration.ts +0 -596
  33. package/src/core/debug-logger.ts +0 -590
  34. package/src/core/directory-filter.ts +0 -421
  35. package/src/core/error-handler.ts +0 -518
  36. package/src/core/file-processor.ts +0 -338
  37. package/src/core/gitignore-manager.ts +0 -169
  38. package/src/core/graceful-degradation-manager.ts +0 -596
  39. package/src/core/index.ts +0 -17
  40. package/src/core/lazy-loader.ts +0 -317
  41. package/src/core/logger.ts +0 -0
  42. package/src/core/memory-manager.ts +0 -290
  43. package/src/core/parser-worker.ts +0 -33
  44. package/src/core/startup-optimizer.ts +0 -246
  45. package/src/core/system-error-handler.ts +0 -755
  46. package/src/git/automation-engine.ts +0 -361
  47. package/src/git/github-manager.ts +0 -190
  48. package/src/git/hook-manager.ts +0 -210
  49. package/src/git/index.ts +0 -4
  50. package/src/index.ts +0 -8
  51. package/src/parsers/feature-validator.ts +0 -559
  52. package/src/parsers/index.ts +0 -8
  53. package/src/parsers/parser-manager.ts +0 -418
  54. package/src/parsers/parser.ts +0 -26
  55. package/src/parsers/react-parser-optimized.ts +0 -161
  56. package/src/parsers/react-parser.ts +0 -359
  57. package/src/parsers/svelte-parser.ts +0 -510
  58. package/src/parsers/vanilla-parser.ts +0 -685
  59. package/src/parsers/vue-parser.ts +0 -476
  60. package/src/types/index.ts +0 -96
  61. package/src/ui/components.ts +0 -567
  62. package/src/ui/help.ts +0 -193
  63. package/src/ui/index.ts +0 -4
  64. package/src/ui/prompts.ts +0 -681
  65. package/src/ui/terminal-header.ts +0 -59
  66. package/tests/e2e/baseguard.e2e.test.ts +0 -516
  67. package/tests/e2e/cross-platform.e2e.test.ts +0 -420
  68. package/tests/e2e/git-integration.e2e.test.ts +0 -487
  69. package/tests/fixtures/react-project/package.json +0 -14
  70. package/tests/fixtures/react-project/src/App.css +0 -76
  71. package/tests/fixtures/react-project/src/App.tsx +0 -77
  72. package/tests/fixtures/svelte-project/package.json +0 -11
  73. package/tests/fixtures/svelte-project/src/App.svelte +0 -369
  74. package/tests/fixtures/vanilla-project/index.html +0 -76
  75. package/tests/fixtures/vanilla-project/script.js +0 -331
  76. package/tests/fixtures/vanilla-project/styles.css +0 -359
  77. package/tests/fixtures/vue-project/package.json +0 -12
  78. package/tests/fixtures/vue-project/src/App.vue +0 -216
  79. package/tmp-smoke/.baseguard/backups/config-2026-02-19T12-04-11-067Z-auto.json +0 -30
  80. package/tmp-smoke/src/bad.css +0 -3
@@ -1,757 +0,0 @@
1
- import type { Violation, Analysis, Fix, Configuration } from '../types/index.js';
2
- import { ParserManager } from '../parsers/parser-manager.js';
3
- import { BaselineChecker } from './baseline-checker.js';
4
- import { FileProcessor } from './file-processor.js';
5
- import { DirectoryFilter } from './directory-filter.js';
6
- import { CacheManager } from './cache-manager.js';
7
- import { SystemErrorHandler } from './system-error-handler.js';
8
- import { GracefulDegradationManager } from './graceful-degradation-manager.js';
9
- import { ConfigurationRecovery } from './configuration-recovery.js';
10
- import { logger } from './debug-logger.js';
11
- import chalk from 'chalk';
12
-
13
- /**
14
- * Main BaseGuard class that orchestrates compatibility checking and fixing
15
- */
16
- export class BaseGuard {
17
- private config: Configuration;
18
- private parserManager!: ParserManager;
19
- private baselineChecker!: BaselineChecker;
20
- private fileProcessor!: FileProcessor;
21
- private directoryFilter!: DirectoryFilter;
22
- private cacheManager!: CacheManager;
23
- private categoryLogger: ReturnType<typeof logger.createCategoryLogger>;
24
- private initialized = false;
25
- private initializationPromise: Promise<void> | null = null;
26
-
27
- constructor(config: Configuration) {
28
- this.config = config;
29
- this.categoryLogger = logger.createCategoryLogger('baseguard');
30
- }
31
-
32
- /**
33
- * Initialize BaseGuard components with error recovery
34
- */
35
- private async initializeComponents(): Promise<void> {
36
- try {
37
- this.categoryLogger.info('Initializing BaseGuard components');
38
-
39
- // Initialize graceful degradation manager
40
- await GracefulDegradationManager.initialize();
41
-
42
- // Initialize components with error handling
43
- this.cacheManager = await SystemErrorHandler.handleGracefully(
44
- async () => {
45
- return new CacheManager({
46
- maxCacheSize: parseInt(process.env.BASEGUARD_CACHE_SIZE || '2000'),
47
- cacheValidityMs: 10 * 60 * 1000 // 10 minutes
48
- });
49
- },
50
- new CacheManager({ maxCacheSize: 1000, cacheValidityMs: 5 * 60 * 1000 }),
51
- { operation: 'cache_manager_init' }
52
- );
53
-
54
- this.parserManager = await SystemErrorHandler.handleGracefully(
55
- async () => {
56
- return new ParserManager();
57
- },
58
- new ParserManager(),
59
- { operation: 'parser_manager_init' }
60
- );
61
-
62
- this.baselineChecker = await SystemErrorHandler.handleGracefully(
63
- async () => {
64
- return new BaselineChecker();
65
- },
66
- new BaselineChecker(),
67
- { operation: 'baseline_checker_init' }
68
- );
69
-
70
- const maxWorkers = parseInt(process.env.BASEGUARD_MAX_WORKERS || '8');
71
- const maxFiles = parseInt(process.env.BASEGUARD_MAX_FILES || '5000');
72
-
73
- this.fileProcessor = await SystemErrorHandler.handleGracefully(
74
- async () => {
75
- return new FileProcessor({
76
- maxWorkers,
77
- cacheManager: this.cacheManager
78
- });
79
- },
80
- new FileProcessor({ maxWorkers: 2, cacheManager: this.cacheManager }),
81
- { operation: 'file_processor_init' }
82
- );
83
-
84
- this.directoryFilter = await SystemErrorHandler.handleGracefully(
85
- async () => {
86
- return new DirectoryFilter({
87
- maxDepth: 8,
88
- maxFiles
89
- });
90
- },
91
- new DirectoryFilter({ maxDepth: 4, maxFiles: 1000 }),
92
- { operation: 'directory_filter_init' }
93
- );
94
-
95
- this.initialized = true;
96
- this.categoryLogger.info('BaseGuard components initialized successfully');
97
-
98
- } catch (error) {
99
- this.categoryLogger.error('Failed to initialize BaseGuard components', { error });
100
- throw new Error(`BaseGuard initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
101
- }
102
- }
103
-
104
- /**
105
- * Ensure BaseGuard is properly initialized
106
- */
107
- private async ensureInitialized(): Promise<void> {
108
- if (!this.initialized) {
109
- if (!this.initializationPromise) {
110
- this.initializationPromise = this.initializeComponents().catch(error => {
111
- this.initializationPromise = null;
112
- throw error;
113
- });
114
- }
115
- await this.initializationPromise;
116
- }
117
- }
118
-
119
- /**
120
- * Check files for compatibility violations with enhanced error recovery
121
- */
122
- async checkViolations(patterns: string[] = []): Promise<Violation[]> {
123
- await this.ensureInitialized();
124
-
125
- logger.startSession('check-violations');
126
- this.categoryLogger.startPerformance('check-violations');
127
-
128
- try {
129
- const violations: Violation[] = [];
130
-
131
- // Find files using smart filtering and caching with error recovery
132
- const allFiles = await SystemErrorHandler.withRetry(
133
- async () => {
134
- return patterns.length > 0
135
- ? await this.directoryFilter.findFilesWithGlob(patterns)
136
- : await this.directoryFilter.findFiles(['src', 'app', 'pages', 'components'], {
137
- includeHidden: false
138
- });
139
- },
140
- { operation: 'find_files', details: { patterns } },
141
- 3 // max retries
142
- );
143
-
144
- if (allFiles.length === 0) {
145
- this.categoryLogger.warn('No supported files found to check', { patterns });
146
- return violations;
147
- }
148
-
149
- this.categoryLogger.info(`Processing ${allFiles.length} files for violations`);
150
-
151
- // Process files concurrently with caching and error recovery
152
- const allFeatures = await SystemErrorHandler.handleGracefully(
153
- () => this.fileProcessor.processFiles(allFiles),
154
- [], // fallback to empty array
155
- { operation: 'process_files', details: { fileCount: allFiles.length } },
156
- {
157
- logError: true,
158
- showWarning: true,
159
- attemptRecovery: true
160
- }
161
- );
162
-
163
- this.categoryLogger.info(`Extracted ${allFeatures.length} features from ${allFiles.length} files`);
164
-
165
- // Check each feature for compatibility violations with error recovery
166
- let processedFeatures = 0;
167
- let failedFeatures = 0;
168
-
169
- for (const feature of allFeatures) {
170
- try {
171
- const compatibilityResult = await SystemErrorHandler.handleGracefully(
172
- () => this.baselineChecker.checkCompatibility(feature, this.config.targets),
173
- { violations: [], featureData: null }, // fallback result
174
- {
175
- operation: 'check_compatibility',
176
- file: feature.file,
177
- details: { feature: feature.feature }
178
- }
179
- );
180
-
181
- // Add violations with file context
182
- for (const violation of compatibilityResult.violations) {
183
- violations.push({
184
- ...violation,
185
- file: feature.file || 'unknown',
186
- line: feature.line,
187
- column: feature.column,
188
- context: feature.context
189
- });
190
- }
191
-
192
- processedFeatures++;
193
- } catch (error) {
194
- failedFeatures++;
195
- this.categoryLogger.warn('Failed to check feature compatibility', {
196
- feature: feature.feature,
197
- file: feature.file,
198
- error: error instanceof Error ? error.message : 'Unknown error'
199
- });
200
-
201
- // Continue processing other features
202
- continue;
203
- }
204
- }
205
-
206
- const duration = this.categoryLogger.endPerformance('check-violations', {
207
- totalFiles: allFiles.length,
208
- processedFeatures,
209
- failedFeatures,
210
- violationsFound: violations.length
211
- });
212
-
213
- this.categoryLogger.info('Violation check completed', {
214
- duration,
215
- totalFiles: allFiles.length,
216
- processedFeatures,
217
- failedFeatures,
218
- violationsFound: violations.length
219
- });
220
-
221
- return violations;
222
-
223
- } catch (error) {
224
- this.categoryLogger.error('Violation check failed', { error });
225
-
226
- // Try graceful degradation
227
- const mode = GracefulDegradationManager.getCurrentMode();
228
- if (mode?.capabilities.baselineChecking) {
229
- this.categoryLogger.info('Attempting graceful degradation for violation checking');
230
-
231
- try {
232
- // Simplified violation checking with minimal features
233
- const basicViolations = await this.performBasicViolationCheck(patterns);
234
- this.categoryLogger.info('Graceful degradation successful', { violationsFound: basicViolations.length });
235
- return basicViolations;
236
- } catch (degradationError) {
237
- this.categoryLogger.error('Graceful degradation also failed', { error: degradationError });
238
- }
239
- }
240
-
241
- throw error;
242
- } finally {
243
- await logger.endSession();
244
- }
245
- }
246
-
247
- /**
248
- * Perform basic violation checking as fallback
249
- */
250
- private async performBasicViolationCheck(patterns: string[]): Promise<Violation[]> {
251
- const violations: Violation[] = [];
252
-
253
- try {
254
- // Use minimal file processing
255
- const basicFiles = patterns.length > 0 ? patterns : ['src/**/*.{js,ts,jsx,tsx,css,vue,svelte}'];
256
-
257
- // Simple file enumeration without complex processing
258
- const { glob } = await import('glob');
259
- const files = await glob(basicFiles.join(','), { ignore: ['node_modules/**', 'dist/**', 'build/**'] });
260
-
261
- this.categoryLogger.info(`Basic violation check on ${files.length} files`);
262
-
263
- // Process a limited number of files to avoid overwhelming the system
264
- const limitedFiles = files.slice(0, 100);
265
-
266
- for (const file of limitedFiles) {
267
- try {
268
- // Basic feature extraction without complex parsing
269
- const basicFeatures = await this.extractBasicFeatures(file);
270
-
271
- for (const feature of basicFeatures) {
272
- const result = await this.baselineChecker.checkCompatibility(feature, this.config.targets);
273
- violations.push(...result.violations);
274
- }
275
- } catch (error) {
276
- // Skip individual file errors in basic mode
277
- this.categoryLogger.debug('Skipped file in basic mode', { file, error: error instanceof Error ? error.message : 'Unknown error' });
278
- }
279
- }
280
-
281
- } catch (error) {
282
- this.categoryLogger.error('Basic violation check failed', { error });
283
- }
284
-
285
- return violations;
286
- }
287
-
288
- /**
289
- * Extract basic features without complex parsing
290
- */
291
- private async extractBasicFeatures(_file: string): Promise<any[]> {
292
- // This is a simplified feature extraction for fallback mode
293
- // In a real implementation, this would do basic text pattern matching
294
- return [];
295
- }
296
-
297
- /**
298
- * Get processing statistics
299
- */
300
- async getProcessingStats(directories: string[] = ['src']): Promise<{
301
- directoryStats: any;
302
- processorStats: any;
303
- cacheStats: any;
304
- }> {
305
- const directoryStats = await Promise.all(
306
- directories.map(dir => this.directoryFilter.getDirectoryStats(dir))
307
- );
308
-
309
- return {
310
- directoryStats: directoryStats.reduce((acc, stats) => ({
311
- totalFiles: acc.totalFiles + stats.totalFiles,
312
- supportedFiles: acc.supportedFiles + stats.supportedFiles,
313
- directories: acc.directories + stats.directories,
314
- excludedDirectories: acc.excludedDirectories + stats.excludedDirectories,
315
- largestFiles: [...acc.largestFiles, ...stats.largestFiles]
316
- .sort((a, b) => b.size - a.size)
317
- .slice(0, 10)
318
- }), {
319
- totalFiles: 0,
320
- supportedFiles: 0,
321
- directories: 0,
322
- excludedDirectories: 0,
323
- largestFiles: []
324
- }),
325
- processorStats: this.fileProcessor.getStats(),
326
- cacheStats: this.cacheManager.getStats()
327
- };
328
- }
329
-
330
- /**
331
- * Clear all caches
332
- */
333
- clearCache(): void {
334
- this.cacheManager.clearAll();
335
- }
336
-
337
- /**
338
- * Cleanup resources with error handling
339
- */
340
- async cleanup(): Promise<void> {
341
- this.categoryLogger.info('Starting BaseGuard cleanup');
342
-
343
- try {
344
- // Cleanup file processor
345
- await SystemErrorHandler.handleGracefully(
346
- async () => {
347
- await this.fileProcessor.cleanup();
348
- return undefined;
349
- },
350
- undefined,
351
- { operation: 'file_processor_cleanup' },
352
- { logError: false, showWarning: false }
353
- );
354
-
355
- // Clear caches
356
- await SystemErrorHandler.handleGracefully(
357
- async () => {
358
- this.cacheManager.clearAll();
359
- return undefined;
360
- },
361
- undefined,
362
- { operation: 'cache_cleanup' },
363
- { logError: false, showWarning: false }
364
- );
365
-
366
- // Cleanup graceful degradation manager
367
- await SystemErrorHandler.handleGracefully(
368
- async () => {
369
- await GracefulDegradationManager.cleanupCache();
370
- return undefined;
371
- },
372
- undefined,
373
- { operation: 'degradation_cleanup' },
374
- { logError: false, showWarning: false }
375
- );
376
-
377
- // Cleanup old logs
378
- await SystemErrorHandler.handleGracefully(
379
- async () => {
380
- await logger.cleanupOldLogs();
381
- return undefined;
382
- },
383
- undefined,
384
- { operation: 'log_cleanup' },
385
- { logError: false, showWarning: false }
386
- );
387
-
388
- this.categoryLogger.info('BaseGuard cleanup completed');
389
-
390
- } catch (error) {
391
- this.categoryLogger.warn('Some cleanup operations failed', { error: error instanceof Error ? error.message : 'Unknown error' });
392
- }
393
- }
394
-
395
- /**
396
- * Create auto-backup of configuration
397
- */
398
- async createConfigBackup(): Promise<string | null> {
399
- try {
400
- return await ConfigurationRecovery.createAutoBackup();
401
- } catch (error) {
402
- this.categoryLogger.error('Failed to create config backup', { error });
403
- return null;
404
- }
405
- }
406
-
407
- /**
408
- * Show system status and health
409
- */
410
- async showSystemStatus(): Promise<void> {
411
- console.log(chalk.cyan('🔍 BaseGuard System Status\n'));
412
-
413
- const health = await this.getHealthStatus();
414
-
415
- // Overall status
416
- const statusIcon = health.overall === 'healthy' ? '✅' : health.overall === 'degraded' ? '⚠️' : '❌';
417
- const statusColor = health.overall === 'healthy' ? chalk.green : health.overall === 'degraded' ? chalk.yellow : chalk.red;
418
-
419
- console.log(statusColor(`${statusIcon} Overall Status: ${health.overall.toUpperCase()}`));
420
- console.log(chalk.dim(`Degradation Mode: ${health.degradationMode}\n`));
421
-
422
- // Component status
423
- console.log(chalk.cyan('📊 Component Status:'));
424
- for (const [component, status] of Object.entries(health.components)) {
425
- const componentIcon = status.status === 'healthy' ? '✅' : status.status === 'degraded' ? '⚠️' : '❌';
426
- console.log(` ${componentIcon} ${component}: ${status.status}`);
427
-
428
- if (status.details && status.status !== 'healthy') {
429
- if (status.details.errors?.length > 0) {
430
- console.log(chalk.dim(` Errors: ${status.details.errors.slice(0, 2).join(', ')}`));
431
- }
432
- if (status.details.error) {
433
- console.log(chalk.dim(` Error: ${status.details.error}`));
434
- }
435
- }
436
- }
437
-
438
- // Recommendations
439
- if (health.recommendations.length > 0) {
440
- console.log(chalk.cyan('\n💡 Recommendations:'));
441
- health.recommendations.forEach(rec => {
442
- console.log(chalk.cyan(` • ${rec}`));
443
- });
444
- }
445
-
446
- // Show degradation status
447
- GracefulDegradationManager.showStatus();
448
- }
449
-
450
- /**
451
- * Analyze violations using AI with graceful degradation
452
- */
453
- async analyzeViolations(violations: Violation[]): Promise<Analysis[]> {
454
- await this.ensureInitialized();
455
-
456
- logger.startSession('analyze-violations');
457
- this.categoryLogger.startPerformance('analyze-violations');
458
-
459
- try {
460
- const analyses: Analysis[] = [];
461
- const mode = GracefulDegradationManager.getCurrentMode();
462
-
463
- if (!mode?.capabilities.aiAnalysis) {
464
- this.categoryLogger.info('AI analysis disabled in current mode, using fallback analysis');
465
-
466
- // Create fallback analyses for all violations
467
- for (const violation of violations) {
468
- const fallbackAnalysis = GracefulDegradationManager.createFallbackAnalysis(
469
- violation,
470
- 'AI analysis unavailable in current mode'
471
- );
472
- analyses.push(fallbackAnalysis);
473
- }
474
-
475
- return analyses;
476
- }
477
-
478
- // Try to use cached analyses first
479
- for (const violation of violations) {
480
- const cached = await GracefulDegradationManager.loadCachedAnalysis(violation);
481
- if (cached) {
482
- analyses.push(cached);
483
- } else {
484
- // Will need AI analysis
485
- const fallbackAnalysis = GracefulDegradationManager.createFallbackAnalysis(
486
- violation,
487
- 'AI analysis not yet implemented'
488
- );
489
- analyses.push(fallbackAnalysis);
490
- }
491
- }
492
-
493
- const duration = this.categoryLogger.endPerformance('analyze-violations', {
494
- violationCount: violations.length,
495
- analysesCreated: analyses.length
496
- });
497
-
498
- this.categoryLogger.info('Violation analysis completed', {
499
- duration,
500
- violationCount: violations.length,
501
- analysesCreated: analyses.length
502
- });
503
-
504
- return analyses;
505
-
506
- } catch (error) {
507
- this.categoryLogger.error('Violation analysis failed', { error });
508
-
509
- // Fallback to basic analysis
510
- const fallbackAnalyses = violations.map(violation =>
511
- GracefulDegradationManager.createFallbackAnalysis(violation, 'Analysis failed, using fallback')
512
- );
513
-
514
- return fallbackAnalyses;
515
- } finally {
516
- await logger.endSession();
517
- }
518
- }
519
-
520
- /**
521
- * Generate fixes for violations with graceful degradation
522
- */
523
- async generateFixes(violations: Violation[], analyses: Analysis[]): Promise<Fix[]> {
524
- await this.ensureInitialized();
525
-
526
- logger.startSession('generate-fixes');
527
- this.categoryLogger.startPerformance('generate-fixes');
528
-
529
- try {
530
- const fixes: Fix[] = [];
531
- const mode = GracefulDegradationManager.getCurrentMode();
532
-
533
- if (!mode?.capabilities.autoFix) {
534
- this.categoryLogger.info('Auto-fix disabled in current mode, creating manual fix suggestions');
535
-
536
- // Create manual fix suggestions
537
- for (let i = 0; i < violations.length; i++) {
538
- const violation = violations[i];
539
- const analysis = analyses[i];
540
-
541
- if (violation && analysis) {
542
- const manualFix = GracefulDegradationManager.createBasicFixSuggestion(violation, analysis);
543
- fixes.push(manualFix);
544
- }
545
- }
546
-
547
- return fixes;
548
- }
549
-
550
- // Auto-fix would be implemented here when available
551
- this.categoryLogger.info('Auto-fix not yet implemented, creating manual suggestions');
552
-
553
- for (let i = 0; i < violations.length; i++) {
554
- const violation = violations[i];
555
- const analysis = analyses[i];
556
-
557
- if (violation && analysis) {
558
- const manualFix = GracefulDegradationManager.createBasicFixSuggestion(violation, analysis);
559
- fixes.push(manualFix);
560
- }
561
- }
562
-
563
- const duration = this.categoryLogger.endPerformance('generate-fixes', {
564
- violationCount: violations.length,
565
- fixesGenerated: fixes.length
566
- });
567
-
568
- this.categoryLogger.info('Fix generation completed', {
569
- duration,
570
- violationCount: violations.length,
571
- fixesGenerated: fixes.length
572
- });
573
-
574
- return fixes;
575
-
576
- } catch (error) {
577
- this.categoryLogger.error('Fix generation failed', { error });
578
- throw error;
579
- } finally {
580
- await logger.endSession();
581
- }
582
- }
583
-
584
- /**
585
- * Apply fixes to files with error recovery
586
- */
587
- async applyFixes(fixes: Fix[]): Promise<void> {
588
- await this.ensureInitialized();
589
-
590
- logger.startSession('apply-fixes');
591
- this.categoryLogger.startPerformance('apply-fixes');
592
-
593
- try {
594
- this.categoryLogger.info(`Applying ${fixes.length} fixes`);
595
-
596
- let appliedCount = 0;
597
- let failedCount = 0;
598
-
599
- for (const fix of fixes) {
600
- try {
601
- await SystemErrorHandler.withRetry(
602
- async () => {
603
- // Fix application would be implemented here
604
- this.categoryLogger.debug('Fix application not yet implemented', {
605
- file: fix.filePath,
606
- feature: fix.violation.feature
607
- });
608
-
609
- // For now, just log the fix that would be applied
610
- console.log(chalk.cyan(`Would apply fix for ${fix.violation.feature} in ${fix.filePath}`));
611
- },
612
- {
613
- operation: 'apply_fix',
614
- file: fix.filePath,
615
- details: { feature: fix.violation.feature }
616
- },
617
- 2 // max retries
618
- );
619
-
620
- appliedCount++;
621
- } catch (error) {
622
- failedCount++;
623
- this.categoryLogger.error('Failed to apply fix', {
624
- file: fix.filePath,
625
- feature: fix.violation.feature,
626
- error: error instanceof Error ? error.message : 'Unknown error'
627
- });
628
- }
629
- }
630
-
631
- const duration = this.categoryLogger.endPerformance('apply-fixes', {
632
- totalFixes: fixes.length,
633
- appliedCount,
634
- failedCount
635
- });
636
-
637
- this.categoryLogger.info('Fix application completed', {
638
- duration,
639
- totalFixes: fixes.length,
640
- appliedCount,
641
- failedCount
642
- });
643
-
644
- if (failedCount > 0) {
645
- console.log(chalk.yellow(`⚠️ ${failedCount} fixes failed to apply. Check logs for details.`));
646
- }
647
-
648
- } catch (error) {
649
- this.categoryLogger.error('Fix application process failed', { error });
650
- throw error;
651
- } finally {
652
- await logger.endSession();
653
- }
654
- }
655
-
656
- /**
657
- * Recover from configuration corruption
658
- */
659
- async recoverConfiguration(): Promise<Configuration> {
660
- this.categoryLogger.info('Attempting configuration recovery');
661
-
662
- const recoveryResult = await ConfigurationRecovery.recoverConfiguration({
663
- createBackup: true,
664
- validateConfig: true,
665
- migrateVersion: true,
666
- repairCorruption: true,
667
- useDefaults: true
668
- });
669
-
670
- if (recoveryResult.success && recoveryResult.config) {
671
- this.config = recoveryResult.config;
672
- this.categoryLogger.info('Configuration recovered successfully');
673
-
674
- if (recoveryResult.warnings.length > 0) {
675
- this.categoryLogger.warn('Configuration recovery warnings', { warnings: recoveryResult.warnings });
676
- }
677
-
678
- return this.config;
679
- } else {
680
- const error = new Error(`Configuration recovery failed: ${recoveryResult.errors.join(', ')}`);
681
- this.categoryLogger.error('Configuration recovery failed', { errors: recoveryResult.errors });
682
- throw error;
683
- }
684
- }
685
-
686
- /**
687
- * Get system health status
688
- */
689
- async getHealthStatus(): Promise<{
690
- overall: 'healthy' | 'degraded' | 'critical';
691
- components: Record<string, { status: string; details?: any }>;
692
- degradationMode: string;
693
- recommendations: string[];
694
- }> {
695
- const health = {
696
- overall: 'healthy' as 'healthy' | 'degraded' | 'critical',
697
- components: {} as Record<string, { status: string; details?: any }>,
698
- degradationMode: 'unknown',
699
- recommendations: [] as string[]
700
- };
701
-
702
- try {
703
- // Check configuration health
704
- const configIntegrity = await ConfigurationRecovery.validateIntegrity();
705
- health.components.configuration = {
706
- status: configIntegrity.valid ? 'healthy' : 'degraded',
707
- details: { errors: configIntegrity.errors, suggestions: configIntegrity.suggestions }
708
- };
709
-
710
- // Check degradation mode
711
- const mode = GracefulDegradationManager.getCurrentMode();
712
- health.degradationMode = mode?.name || 'unknown';
713
-
714
- if (mode?.name !== 'Full Functionality') {
715
- health.overall = 'degraded';
716
- health.recommendations.push(`Currently in ${mode?.name} mode`);
717
- health.recommendations.push(...(mode?.limitations || []));
718
- }
719
-
720
- // Check service status
721
- const serviceStatus = GracefulDegradationManager.getServiceStatus();
722
- for (const [service, status] of serviceStatus) {
723
- health.components[service] = {
724
- status: status.available ? 'healthy' : 'degraded',
725
- details: { lastCheck: status.lastCheck, error: status.error }
726
- };
727
-
728
- if (!status.available) {
729
- health.overall = 'degraded';
730
- health.recommendations.push(`${service} service is unavailable`);
731
- }
732
- }
733
-
734
- // Check error summary
735
- const errorSummary = logger.getErrorSummary();
736
- health.components.errors = {
737
- status: errorSummary.totalErrors > 10 ? 'critical' : errorSummary.totalErrors > 0 ? 'degraded' : 'healthy',
738
- details: errorSummary
739
- };
740
-
741
- if (errorSummary.totalErrors > 10) {
742
- health.overall = 'critical';
743
- health.recommendations.push('High error count detected - check logs');
744
- }
745
-
746
- } catch (error) {
747
- health.overall = 'critical';
748
- health.components.healthCheck = {
749
- status: 'failed',
750
- details: { error: error instanceof Error ? error.message : 'Unknown error' }
751
- };
752
- health.recommendations.push('Health check failed - system may be unstable');
753
- }
754
-
755
- return health;
756
- }
757
- }