aios-core 4.2.13 → 4.2.15

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 (95) hide show
  1. package/.aios-core/core/code-intel/helpers/dev-helper.js +206 -0
  2. package/.aios-core/core/registry/registry-schema.json +166 -166
  3. package/.aios-core/core/synapse/diagnostics/collectors/hook-collector.js +3 -3
  4. package/.aios-core/data/entity-registry.yaml +27 -0
  5. package/.aios-core/development/scripts/approval-workflow.js +642 -642
  6. package/.aios-core/development/scripts/backup-manager.js +606 -606
  7. package/.aios-core/development/scripts/branch-manager.js +389 -389
  8. package/.aios-core/development/scripts/code-quality-improver.js +1311 -1311
  9. package/.aios-core/development/scripts/commit-message-generator.js +849 -849
  10. package/.aios-core/development/scripts/conflict-resolver.js +674 -674
  11. package/.aios-core/development/scripts/dependency-analyzer.js +637 -637
  12. package/.aios-core/development/scripts/diff-generator.js +351 -351
  13. package/.aios-core/development/scripts/elicitation-engine.js +384 -384
  14. package/.aios-core/development/scripts/elicitation-session-manager.js +299 -299
  15. package/.aios-core/development/scripts/git-wrapper.js +461 -461
  16. package/.aios-core/development/scripts/manifest-preview.js +244 -244
  17. package/.aios-core/development/scripts/metrics-tracker.js +775 -775
  18. package/.aios-core/development/scripts/modification-validator.js +554 -554
  19. package/.aios-core/development/scripts/pattern-learner.js +1224 -1224
  20. package/.aios-core/development/scripts/performance-analyzer.js +757 -757
  21. package/.aios-core/development/scripts/refactoring-suggester.js +1138 -1138
  22. package/.aios-core/development/scripts/rollback-handler.js +530 -530
  23. package/.aios-core/development/scripts/security-checker.js +358 -358
  24. package/.aios-core/development/scripts/template-engine.js +239 -239
  25. package/.aios-core/development/scripts/template-validator.js +278 -278
  26. package/.aios-core/development/scripts/test-generator.js +843 -843
  27. package/.aios-core/development/scripts/transaction-manager.js +589 -589
  28. package/.aios-core/development/scripts/usage-tracker.js +673 -673
  29. package/.aios-core/development/scripts/validate-filenames.js +226 -226
  30. package/.aios-core/development/scripts/version-tracker.js +526 -526
  31. package/.aios-core/development/scripts/yaml-validator.js +396 -396
  32. package/.aios-core/development/tasks/build-autonomous.md +10 -4
  33. package/.aios-core/development/tasks/create-service.md +23 -0
  34. package/.aios-core/development/tasks/dev-develop-story.md +12 -6
  35. package/.aios-core/development/tasks/dev-suggest-refactoring.md +7 -1
  36. package/.aios-core/development/tasks/publish-npm.md +3 -3
  37. package/.aios-core/hooks/unified/README.md +1 -1
  38. package/.aios-core/install-manifest.yaml +65 -61
  39. package/.aios-core/manifests/schema/manifest-schema.json +190 -190
  40. package/.aios-core/product/templates/component-react-tmpl.tsx +98 -98
  41. package/.aios-core/product/templates/engine/schemas/adr.schema.json +102 -102
  42. package/.aios-core/product/templates/engine/schemas/dbdr.schema.json +205 -205
  43. package/.aios-core/product/templates/engine/schemas/epic.schema.json +175 -175
  44. package/.aios-core/product/templates/engine/schemas/pmdr.schema.json +175 -175
  45. package/.aios-core/product/templates/engine/schemas/prd-v2.schema.json +300 -300
  46. package/.aios-core/product/templates/engine/schemas/prd.schema.json +152 -152
  47. package/.aios-core/product/templates/engine/schemas/story.schema.json +222 -222
  48. package/.aios-core/product/templates/engine/schemas/task.schema.json +154 -154
  49. package/.aios-core/product/templates/eslintrc-security.json +32 -32
  50. package/.aios-core/product/templates/github-actions-cd.yml +212 -212
  51. package/.aios-core/product/templates/github-actions-ci.yml +172 -172
  52. package/.aios-core/product/templates/shock-report-tmpl.html +502 -502
  53. package/.aios-core/product/templates/token-exports-css-tmpl.css +240 -240
  54. package/.aios-core/quality/schemas/quality-metrics.schema.json +233 -233
  55. package/.aios-core/scripts/migrate-framework-docs.sh +300 -300
  56. package/README.en.md +747 -0
  57. package/README.md +4 -2
  58. package/bin/aios.js +7 -4
  59. package/package.json +1 -1
  60. package/packages/aios-pro-cli/src/recover.js +1 -1
  61. package/packages/installer/src/wizard/ide-config-generator.js +6 -6
  62. package/packages/installer/src/wizard/pro-setup.js +3 -3
  63. package/pro/license/degradation.js +220 -220
  64. package/pro/license/errors.js +450 -450
  65. package/pro/license/feature-gate.js +354 -354
  66. package/pro/license/index.js +181 -181
  67. package/pro/license/license-cache.js +523 -523
  68. package/pro/license/license-crypto.js +303 -303
  69. package/scripts/package-synapse.js +5 -5
  70. package/scripts/validate-package-completeness.js +3 -3
  71. package/.aios-core/.session/current-session.json +0 -14
  72. package/.aios-core/data/registry-update-log.jsonl +0 -191
  73. package/.aios-core/docs/SHARD-TRANSLATION-GUIDE.md +0 -335
  74. package/.aios-core/docs/component-creation-guide.md +0 -458
  75. package/.aios-core/docs/session-update-pattern.md +0 -307
  76. package/.aios-core/docs/standards/AIOS-FRAMEWORK-MASTER.md +0 -1963
  77. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1-SUMMARY.md +0 -1190
  78. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1.md +0 -439
  79. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO.md +0 -5398
  80. package/.aios-core/docs/standards/V3-ARCHITECTURAL-DECISIONS.md +0 -523
  81. package/.aios-core/docs/template-syntax.md +0 -267
  82. package/.aios-core/docs/troubleshooting-guide.md +0 -625
  83. package/.aios-core/infrastructure/tests/utilities-audit-results.json +0 -501
  84. package/.aios-core/manifests/agents.csv +0 -29
  85. package/.aios-core/manifests/tasks.csv +0 -198
  86. package/.aios-core/manifests/workers.csv +0 -204
  87. package/.claude/rules/agent-authority.md +0 -105
  88. package/.claude/rules/coderabbit-integration.md +0 -93
  89. package/.claude/rules/ids-principles.md +0 -112
  90. package/.claude/rules/story-lifecycle.md +0 -139
  91. package/.claude/rules/workflow-execution.md +0 -150
  92. package/scripts/glue/README.md +0 -355
  93. package/scripts/glue/compose-agent-prompt.cjs +0 -362
  94. /package/.claude/hooks/{precompact-session-digest.js → precompact-session-digest.cjs} +0 -0
  95. /package/.claude/hooks/{synapse-engine.js → synapse-engine.cjs} +0 -0
@@ -1,607 +1,607 @@
1
- const fs = require('fs').promises;
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const crypto = require('crypto');
5
- const tar = require('tar');
6
- const { promisify } = require('util');
7
- const zlib = require('zlib');
8
- const _gzip = promisify(zlib.gzip);
9
- const _gunzip = promisify(zlib.gunzip);
10
-
11
- /**
12
- * Manages backups for safe self-modification rollback
13
- */
14
- class BackupManager {
15
- constructor(options = {}) {
16
- this.rootPath = options.rootPath || process.cwd();
17
- this.backupDir = path.join(this.rootPath, '.aios', 'backup');
18
- this.maxBackups = options.maxBackups || 10;
19
- this.compressionLevel = options.compressionLevel || 6;
20
-
21
- // Active backup tracking
22
- this.activeBackup = null;
23
-
24
- // Backup metadata
25
- this.metadataFile = path.join(this.backupDir, 'backup-metadata.json');
26
- }
27
-
28
- /**
29
- * Initialize backup system
30
- * @returns {Promise<void>}
31
- */
32
- async initialize() {
33
- try {
34
- await fs.mkdir(this.backupDir, { recursive: true });
35
-
36
- // Initialize metadata if not exists
37
- try {
38
- await fs.access(this.metadataFile);
39
- } catch {
40
- await this.saveMetadata({
41
- version: '1.0.0',
42
- backups: [],
43
- statistics: {
44
- total_backups: 0,
45
- successful_restores: 0,
46
- failed_restores: 0,
47
- total_size: 0
48
- }
49
- });
50
- }
51
- } catch (error) {
52
- console.error(chalk.red(`Failed to initialize backup system: ${error.message}`));
53
- }
54
- }
55
-
56
- /**
57
- * Create full backup of specified files
58
- * @param {Object} params - Backup parameters
59
- * @returns {Promise<string>} Backup ID
60
- */
61
- async createFullBackup(params) {
62
- const { files, metadata = {} } = params;
63
-
64
- await this.initialize();
65
-
66
- console.log(chalk.blue('📦 Creating backup...'));
67
-
68
- const backupId = this.generateBackupId();
69
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
70
- const backupInfo = {
71
- id: backupId,
72
- timestamp: new Date().toISOString(),
73
- files: files.map(f => path.relative(this.rootPath, f)),
74
- metadata,
75
- size: 0,
76
- checksums: {},
77
- compressed: true,
78
- status: 'creating'
79
- };
80
-
81
- try {
82
- // Create temporary directory for backup files
83
- const tempDir = path.join(this.backupDir, `temp-${backupId}`);
84
- await fs.mkdir(tempDir, { recursive: true });
85
-
86
- // Copy files to temp directory maintaining structure
87
- for (const file of files) {
88
- const relPath = path.relative(this.rootPath, file);
89
- const tempPath = path.join(tempDir, relPath);
90
-
91
- await fs.mkdir(path.dirname(tempPath), { recursive: true });
92
-
93
- try {
94
- await fs.copyFile(file, tempPath);
95
-
96
- // Calculate checksum
97
- const content = await fs.readFile(file);
98
- const checksum = crypto.createHash('sha256').update(content).digest('hex');
99
- backupInfo.checksums[relPath] = checksum;
100
- } catch (error) {
101
- console.warn(chalk.yellow(`Warning: Could not backup ${file}: ${error.message}`));
102
- }
103
- }
104
-
105
- // Create backup manifest
106
- await fs.writeFile(
107
- path.join(tempDir, 'backup-manifest.json'),
108
- JSON.stringify(backupInfo, null, 2)
109
- );
110
-
111
- // Create tar archive
112
- await tar.create(
113
- {
114
- gzip: { level: this.compressionLevel },
115
- file: backupPath,
116
- cwd: tempDir
117
- },
118
- ['.']
119
- );
120
-
121
- // Get backup size
122
- const stats = await fs.stat(backupPath);
123
- backupInfo.size = stats.size;
124
- backupInfo.status = 'completed';
125
-
126
- // Clean up temp directory
127
- await fs.rm(tempDir, { recursive: true, force: true });
128
-
129
- // Update metadata
130
- await this.addBackupToMetadata(backupInfo);
131
-
132
- // Set as active backup
133
- this.activeBackup = backupId;
134
-
135
- // Clean old backups
136
- await this.cleanOldBackups();
137
-
138
- console.log(chalk.green(`✅ Backup created: ${backupId}`));
139
- console.log(chalk.gray(` Files: ${files.length}, Size: ${this.formatSize(backupInfo.size)}`));
140
-
141
- return backupId;
142
-
143
- } catch (error) {
144
- // Clean up on failure
145
- try {
146
- await fs.unlink(backupPath);
147
- } catch {}
148
-
149
- throw new Error(`Backup creation failed: ${error.message}`);
150
- }
151
- }
152
-
153
- /**
154
- * Restore backup
155
- * @param {string} backupId - Backup ID to restore
156
- * @param {Object} options - Restore options
157
- * @returns {Promise<Object>} Restore result
158
- */
159
- async restoreBackup(backupId, options = {}) {
160
- const { targetPath = this.rootPath, dryRun = false } = options;
161
-
162
- console.log(chalk.blue(`🔄 Restoring backup: ${backupId}`));
163
-
164
- const result = {
165
- success: true,
166
- backupId,
167
- restored_files: [],
168
- failed_files: [],
169
- warnings: []
170
- };
171
-
172
- try {
173
- // Load backup metadata
174
- const metadata = await this.loadMetadata();
175
- const backupInfo = metadata.backups.find(b => b.id === backupId);
176
-
177
- if (!backupInfo) {
178
- throw new Error(`Backup not found: ${backupId}`);
179
- }
180
-
181
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
182
-
183
- // Verify backup exists
184
- try {
185
- await fs.access(backupPath);
186
- } catch {
187
- throw new Error(`Backup file missing: ${backupPath}`);
188
- }
189
-
190
- // Create restore temp directory
191
- const restoreTemp = path.join(this.backupDir, `restore-${Date.now()}`);
192
- await fs.mkdir(restoreTemp, { recursive: true });
193
-
194
- // Extract backup
195
- await tar.extract({
196
- file: backupPath,
197
- cwd: restoreTemp
198
- });
199
-
200
- // Load manifest
201
- const manifestPath = path.join(restoreTemp, 'backup-manifest.json');
202
- const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf-8'));
203
-
204
- // Verify checksums
205
- for (const [relPath, expectedChecksum] of Object.entries(manifest.checksums)) {
206
- const tempFile = path.join(restoreTemp, relPath);
207
- try {
208
- const content = await fs.readFile(tempFile);
209
- const actualChecksum = crypto.createHash('sha256').update(content).digest('hex');
210
-
211
- if (actualChecksum !== expectedChecksum) {
212
- result.warnings.push(`Checksum mismatch for ${relPath}`);
213
- }
214
- } catch (error) {
215
- result.warnings.push(`Could not verify ${relPath}: ${error.message}`);
216
- }
217
- }
218
-
219
- if (!dryRun) {
220
- // Restore files
221
- for (const relPath of manifest.files) {
222
- const sourcePath = path.join(restoreTemp, relPath);
223
- const destPath = path.join(targetPath, relPath);
224
-
225
- try {
226
- // Create backup of current file if it exists
227
- try {
228
- await fs.access(destPath);
229
- await fs.copyFile(destPath, `${destPath}.pre-restore`);
230
- } catch {}
231
-
232
- // Ensure directory exists
233
- await fs.mkdir(path.dirname(destPath), { recursive: true });
234
-
235
- // Restore file
236
- await fs.copyFile(sourcePath, destPath);
237
- result.restored_files.push(relPath);
238
-
239
- } catch (error) {
240
- result.failed_files.push({
241
- file: relPath,
242
- error: error.message
243
- });
244
- result.success = false;
245
- }
246
- }
247
- }
248
-
249
- // Clean up
250
- await fs.rm(restoreTemp, { recursive: true, force: true });
251
-
252
- // Update statistics
253
- if (!dryRun && result.success) {
254
- metadata.statistics.successful_restores++;
255
- } else if (!dryRun) {
256
- metadata.statistics.failed_restores++;
257
- }
258
- await this.saveMetadata(metadata);
259
-
260
- console.log(chalk.green(`✅ Restore ${dryRun ? 'preview' : 'completed'}`));
261
- console.log(chalk.gray(` Restored: ${result.restored_files.length} files`));
262
- if (result.failed_files.length > 0) {
263
- console.log(chalk.red(` Failed: ${result.failed_files.length} files`));
264
- }
265
-
266
- } catch (error) {
267
- result.success = false;
268
- result.error = error.message;
269
- console.error(chalk.red(`Restore failed: ${error.message}`));
270
- }
271
-
272
- return result;
273
- }
274
-
275
- /**
276
- * Emergency restore - restores the last active backup
277
- * @returns {Promise<Object>} Restore result
278
- */
279
- async emergencyRestore() {
280
- console.log(chalk.red('🚨 EMERGENCY RESTORE INITIATED'));
281
-
282
- if (!this.activeBackup) {
283
- // Find most recent backup
284
- const metadata = await this.loadMetadata();
285
- const backups = metadata.backups
286
- .filter(b => b.status === 'completed')
287
- .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
288
-
289
- if (backups.length === 0) {
290
- throw new Error('No backups available for emergency restore');
291
- }
292
-
293
- this.activeBackup = backups[0].id;
294
- }
295
-
296
- console.log(chalk.yellow(`Restoring backup: ${this.activeBackup}`));
297
- return await this.restoreBackup(this.activeBackup);
298
- }
299
-
300
- /**
301
- * List available backups
302
- * @param {Object} filter - Filter options
303
- * @returns {Promise<Array>} List of backups
304
- */
305
- async listBackups(filter = {}) {
306
- const metadata = await this.loadMetadata();
307
- let backups = metadata.backups;
308
-
309
- // Apply filters
310
- if (filter.status) {
311
- backups = backups.filter(b => b.status === filter.status);
312
- }
313
-
314
- if (filter.after) {
315
- const afterDate = new Date(filter.after);
316
- backups = backups.filter(b => new Date(b.timestamp) > afterDate);
317
- }
318
-
319
- if (filter.metadata) {
320
- backups = backups.filter(b => {
321
- return Object.entries(filter.metadata).every(([key, value]) =>
322
- b.metadata[key] === value
323
- );
324
- });
325
- }
326
-
327
- // Sort by timestamp (newest first)
328
- backups.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
329
-
330
- return backups.map(b => ({
331
- id: b.id,
332
- timestamp: b.timestamp,
333
- files: b.files.length,
334
- size: this.formatSize(b.size),
335
- metadata: b.metadata,
336
- isActive: b.id === this.activeBackup
337
- }));
338
- }
339
-
340
- /**
341
- * Delete specific backup
342
- * @param {string} backupId - Backup ID to delete
343
- * @returns {Promise<boolean>} Success status
344
- */
345
- async deleteBackup(backupId) {
346
- try {
347
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
348
- await fs.unlink(backupPath);
349
-
350
- // Remove from metadata
351
- const metadata = await this.loadMetadata();
352
- const index = metadata.backups.findIndex(b => b.id === backupId);
353
-
354
- if (index !== -1) {
355
- const backup = metadata.backups[index];
356
- metadata.statistics.total_size -= backup.size;
357
- metadata.backups.splice(index, 1);
358
- await this.saveMetadata(metadata);
359
- }
360
-
361
- // Clear active backup if deleted
362
- if (this.activeBackup === backupId) {
363
- this.activeBackup = null;
364
- }
365
-
366
- console.log(chalk.gray(`Deleted backup: ${backupId}`));
367
- return true;
368
-
369
- } catch (error) {
370
- console.error(chalk.red(`Failed to delete backup: ${error.message}`));
371
- return false;
372
- }
373
- }
374
-
375
- /**
376
- * Get backup details
377
- * @param {string} backupId - Backup ID
378
- * @returns {Promise<Object>} Backup details
379
- */
380
- async getBackupDetails(backupId) {
381
- const metadata = await this.loadMetadata();
382
- const backup = metadata.backups.find(b => b.id === backupId);
383
-
384
- if (!backup) {
385
- throw new Error(`Backup not found: ${backupId}`);
386
- }
387
-
388
- return backup;
389
- }
390
-
391
- /**
392
- * Verify backup integrity
393
- * @param {string} backupId - Backup ID to verify
394
- * @returns {Promise<Object>} Verification result
395
- */
396
- async verifyBackup(backupId) {
397
- console.log(chalk.blue(`🔍 Verifying backup: ${backupId}`));
398
-
399
- const result = {
400
- valid: true,
401
- backupId,
402
- errors: [],
403
- warnings: []
404
- };
405
-
406
- try {
407
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
408
-
409
- // Check file exists
410
- try {
411
- await fs.access(backupPath);
412
- } catch {
413
- result.valid = false;
414
- result.errors.push('Backup file not found');
415
- return result;
416
- }
417
-
418
- // Try to list archive contents
419
- try {
420
- const entries = [];
421
- await tar.list({
422
- file: backupPath,
423
- onentry: entry => entries.push(entry.path)
424
- });
425
-
426
- if (!entries.includes('./backup-manifest.json')) {
427
- result.valid = false;
428
- result.errors.push('Missing backup manifest');
429
- }
430
- } catch (error) {
431
- result.valid = false;
432
- result.errors.push(`Archive corrupted: ${error.message}`);
433
- }
434
-
435
- } catch (error) {
436
- result.valid = false;
437
- result.errors.push(`Verification failed: ${error.message}`);
438
- }
439
-
440
- return result;
441
- }
442
-
443
- /**
444
- * Check if has active backup
445
- * @returns {boolean}
446
- */
447
- hasActiveBackup() {
448
- return this.activeBackup !== null;
449
- }
450
-
451
- /**
452
- * Load metadata
453
- * @private
454
- */
455
- async loadMetadata() {
456
- try {
457
- const content = await fs.readFile(this.metadataFile, 'utf-8');
458
- return JSON.parse(content);
459
- } catch {
460
- return {
461
- version: '1.0.0',
462
- backups: [],
463
- statistics: {
464
- total_backups: 0,
465
- successful_restores: 0,
466
- failed_restores: 0,
467
- total_size: 0
468
- }
469
- };
470
- }
471
- }
472
-
473
- /**
474
- * Save metadata
475
- * @private
476
- */
477
- async saveMetadata(metadata) {
478
- await fs.writeFile(
479
- this.metadataFile,
480
- JSON.stringify(metadata, null, 2)
481
- );
482
- }
483
-
484
- /**
485
- * Add backup to metadata
486
- * @private
487
- */
488
- async addBackupToMetadata(backupInfo) {
489
- const metadata = await this.loadMetadata();
490
-
491
- metadata.backups.push(backupInfo);
492
- metadata.statistics.total_backups++;
493
- metadata.statistics.total_size += backupInfo.size;
494
-
495
- await this.saveMetadata(metadata);
496
- }
497
-
498
- /**
499
- * Clean old backups
500
- * @private
501
- */
502
- async cleanOldBackups() {
503
- const metadata = await this.loadMetadata();
504
- const backups = metadata.backups
505
- .filter(b => b.status === 'completed')
506
- .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
507
-
508
- if (backups.length > this.maxBackups) {
509
- const toDelete = backups.slice(this.maxBackups);
510
-
511
- for (const backup of toDelete) {
512
- await this.deleteBackup(backup.id);
513
- }
514
-
515
- console.log(chalk.gray(`Cleaned ${toDelete.length} old backups`));
516
- }
517
- }
518
-
519
- /**
520
- * Generate backup ID
521
- * @private
522
- */
523
- generateBackupId() {
524
- const timestamp = Date.now();
525
- const random = crypto.randomBytes(4).toString('hex');
526
- return `backup-${timestamp}-${random}`;
527
- }
528
-
529
- /**
530
- * Format file size
531
- * @private
532
- */
533
- formatSize(bytes) {
534
- const units = ['B', 'KB', 'MB', 'GB'];
535
- let size = bytes;
536
- let unitIndex = 0;
537
-
538
- while (size >= 1024 && unitIndex < units.length - 1) {
539
- size /= 1024;
540
- unitIndex++;
541
- }
542
-
543
- return `${size.toFixed(2)} ${units[unitIndex]}`;
544
- }
545
-
546
- /**
547
- * Export backup for external storage
548
- * @param {string} backupId - Backup ID to export
549
- * @param {string} exportPath - Path to export to
550
- * @returns {Promise<Object>} Export result
551
- */
552
- async exportBackup(backupId, exportPath) {
553
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
554
- const metadataPath = path.join(this.backupDir, `${backupId}-metadata.json`);
555
-
556
- try {
557
- // Copy backup file
558
- await fs.copyFile(backupPath, exportPath);
559
-
560
- // Export metadata
561
- const metadata = await this.getBackupDetails(backupId);
562
- await fs.writeFile(
563
- metadataPath,
564
- JSON.stringify(metadata, null, 2)
565
- );
566
-
567
- return {
568
- success: true,
569
- exported: exportPath,
570
- metadata: metadataPath,
571
- size: metadata.size
572
- };
573
-
574
- } catch (error) {
575
- throw new Error(`Export failed: ${error.message}`);
576
- }
577
- }
578
-
579
- /**
580
- * Import external backup
581
- * @param {string} importPath - Path to backup file
582
- * @param {Object} metadata - Backup metadata
583
- * @returns {Promise<string>} Imported backup ID
584
- */
585
- async importBackup(importPath, metadata) {
586
- const backupId = metadata.id || this.generateBackupId();
587
- const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
588
-
589
- try {
590
- // Copy backup file
591
- await fs.copyFile(importPath, backupPath);
592
-
593
- // Update metadata
594
- metadata.id = backupId;
595
- metadata.imported = new Date().toISOString();
596
-
597
- await this.addBackupToMetadata(metadata);
598
-
599
- return backupId;
600
-
601
- } catch (error) {
602
- throw new Error(`Import failed: ${error.message}`);
603
- }
604
- }
605
- }
606
-
1
+ const fs = require('fs').promises;
2
+ const path = require('path');
3
+ const chalk = require('chalk');
4
+ const crypto = require('crypto');
5
+ const tar = require('tar');
6
+ const { promisify } = require('util');
7
+ const zlib = require('zlib');
8
+ const _gzip = promisify(zlib.gzip);
9
+ const _gunzip = promisify(zlib.gunzip);
10
+
11
+ /**
12
+ * Manages backups for safe self-modification rollback
13
+ */
14
+ class BackupManager {
15
+ constructor(options = {}) {
16
+ this.rootPath = options.rootPath || process.cwd();
17
+ this.backupDir = path.join(this.rootPath, '.aios', 'backup');
18
+ this.maxBackups = options.maxBackups || 10;
19
+ this.compressionLevel = options.compressionLevel || 6;
20
+
21
+ // Active backup tracking
22
+ this.activeBackup = null;
23
+
24
+ // Backup metadata
25
+ this.metadataFile = path.join(this.backupDir, 'backup-metadata.json');
26
+ }
27
+
28
+ /**
29
+ * Initialize backup system
30
+ * @returns {Promise<void>}
31
+ */
32
+ async initialize() {
33
+ try {
34
+ await fs.mkdir(this.backupDir, { recursive: true });
35
+
36
+ // Initialize metadata if not exists
37
+ try {
38
+ await fs.access(this.metadataFile);
39
+ } catch {
40
+ await this.saveMetadata({
41
+ version: '1.0.0',
42
+ backups: [],
43
+ statistics: {
44
+ total_backups: 0,
45
+ successful_restores: 0,
46
+ failed_restores: 0,
47
+ total_size: 0
48
+ }
49
+ });
50
+ }
51
+ } catch (error) {
52
+ console.error(chalk.red(`Failed to initialize backup system: ${error.message}`));
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Create full backup of specified files
58
+ * @param {Object} params - Backup parameters
59
+ * @returns {Promise<string>} Backup ID
60
+ */
61
+ async createFullBackup(params) {
62
+ const { files, metadata = {} } = params;
63
+
64
+ await this.initialize();
65
+
66
+ console.log(chalk.blue('📦 Creating backup...'));
67
+
68
+ const backupId = this.generateBackupId();
69
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
70
+ const backupInfo = {
71
+ id: backupId,
72
+ timestamp: new Date().toISOString(),
73
+ files: files.map(f => path.relative(this.rootPath, f)),
74
+ metadata,
75
+ size: 0,
76
+ checksums: {},
77
+ compressed: true,
78
+ status: 'creating'
79
+ };
80
+
81
+ try {
82
+ // Create temporary directory for backup files
83
+ const tempDir = path.join(this.backupDir, `temp-${backupId}`);
84
+ await fs.mkdir(tempDir, { recursive: true });
85
+
86
+ // Copy files to temp directory maintaining structure
87
+ for (const file of files) {
88
+ const relPath = path.relative(this.rootPath, file);
89
+ const tempPath = path.join(tempDir, relPath);
90
+
91
+ await fs.mkdir(path.dirname(tempPath), { recursive: true });
92
+
93
+ try {
94
+ await fs.copyFile(file, tempPath);
95
+
96
+ // Calculate checksum
97
+ const content = await fs.readFile(file);
98
+ const checksum = crypto.createHash('sha256').update(content).digest('hex');
99
+ backupInfo.checksums[relPath] = checksum;
100
+ } catch (error) {
101
+ console.warn(chalk.yellow(`Warning: Could not backup ${file}: ${error.message}`));
102
+ }
103
+ }
104
+
105
+ // Create backup manifest
106
+ await fs.writeFile(
107
+ path.join(tempDir, 'backup-manifest.json'),
108
+ JSON.stringify(backupInfo, null, 2)
109
+ );
110
+
111
+ // Create tar archive
112
+ await tar.create(
113
+ {
114
+ gzip: { level: this.compressionLevel },
115
+ file: backupPath,
116
+ cwd: tempDir
117
+ },
118
+ ['.']
119
+ );
120
+
121
+ // Get backup size
122
+ const stats = await fs.stat(backupPath);
123
+ backupInfo.size = stats.size;
124
+ backupInfo.status = 'completed';
125
+
126
+ // Clean up temp directory
127
+ await fs.rm(tempDir, { recursive: true, force: true });
128
+
129
+ // Update metadata
130
+ await this.addBackupToMetadata(backupInfo);
131
+
132
+ // Set as active backup
133
+ this.activeBackup = backupId;
134
+
135
+ // Clean old backups
136
+ await this.cleanOldBackups();
137
+
138
+ console.log(chalk.green(`✅ Backup created: ${backupId}`));
139
+ console.log(chalk.gray(` Files: ${files.length}, Size: ${this.formatSize(backupInfo.size)}`));
140
+
141
+ return backupId;
142
+
143
+ } catch (error) {
144
+ // Clean up on failure
145
+ try {
146
+ await fs.unlink(backupPath);
147
+ } catch {}
148
+
149
+ throw new Error(`Backup creation failed: ${error.message}`);
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Restore backup
155
+ * @param {string} backupId - Backup ID to restore
156
+ * @param {Object} options - Restore options
157
+ * @returns {Promise<Object>} Restore result
158
+ */
159
+ async restoreBackup(backupId, options = {}) {
160
+ const { targetPath = this.rootPath, dryRun = false } = options;
161
+
162
+ console.log(chalk.blue(`🔄 Restoring backup: ${backupId}`));
163
+
164
+ const result = {
165
+ success: true,
166
+ backupId,
167
+ restored_files: [],
168
+ failed_files: [],
169
+ warnings: []
170
+ };
171
+
172
+ try {
173
+ // Load backup metadata
174
+ const metadata = await this.loadMetadata();
175
+ const backupInfo = metadata.backups.find(b => b.id === backupId);
176
+
177
+ if (!backupInfo) {
178
+ throw new Error(`Backup not found: ${backupId}`);
179
+ }
180
+
181
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
182
+
183
+ // Verify backup exists
184
+ try {
185
+ await fs.access(backupPath);
186
+ } catch {
187
+ throw new Error(`Backup file missing: ${backupPath}`);
188
+ }
189
+
190
+ // Create restore temp directory
191
+ const restoreTemp = path.join(this.backupDir, `restore-${Date.now()}`);
192
+ await fs.mkdir(restoreTemp, { recursive: true });
193
+
194
+ // Extract backup
195
+ await tar.extract({
196
+ file: backupPath,
197
+ cwd: restoreTemp
198
+ });
199
+
200
+ // Load manifest
201
+ const manifestPath = path.join(restoreTemp, 'backup-manifest.json');
202
+ const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf-8'));
203
+
204
+ // Verify checksums
205
+ for (const [relPath, expectedChecksum] of Object.entries(manifest.checksums)) {
206
+ const tempFile = path.join(restoreTemp, relPath);
207
+ try {
208
+ const content = await fs.readFile(tempFile);
209
+ const actualChecksum = crypto.createHash('sha256').update(content).digest('hex');
210
+
211
+ if (actualChecksum !== expectedChecksum) {
212
+ result.warnings.push(`Checksum mismatch for ${relPath}`);
213
+ }
214
+ } catch (error) {
215
+ result.warnings.push(`Could not verify ${relPath}: ${error.message}`);
216
+ }
217
+ }
218
+
219
+ if (!dryRun) {
220
+ // Restore files
221
+ for (const relPath of manifest.files) {
222
+ const sourcePath = path.join(restoreTemp, relPath);
223
+ const destPath = path.join(targetPath, relPath);
224
+
225
+ try {
226
+ // Create backup of current file if it exists
227
+ try {
228
+ await fs.access(destPath);
229
+ await fs.copyFile(destPath, `${destPath}.pre-restore`);
230
+ } catch {}
231
+
232
+ // Ensure directory exists
233
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
234
+
235
+ // Restore file
236
+ await fs.copyFile(sourcePath, destPath);
237
+ result.restored_files.push(relPath);
238
+
239
+ } catch (error) {
240
+ result.failed_files.push({
241
+ file: relPath,
242
+ error: error.message
243
+ });
244
+ result.success = false;
245
+ }
246
+ }
247
+ }
248
+
249
+ // Clean up
250
+ await fs.rm(restoreTemp, { recursive: true, force: true });
251
+
252
+ // Update statistics
253
+ if (!dryRun && result.success) {
254
+ metadata.statistics.successful_restores++;
255
+ } else if (!dryRun) {
256
+ metadata.statistics.failed_restores++;
257
+ }
258
+ await this.saveMetadata(metadata);
259
+
260
+ console.log(chalk.green(`✅ Restore ${dryRun ? 'preview' : 'completed'}`));
261
+ console.log(chalk.gray(` Restored: ${result.restored_files.length} files`));
262
+ if (result.failed_files.length > 0) {
263
+ console.log(chalk.red(` Failed: ${result.failed_files.length} files`));
264
+ }
265
+
266
+ } catch (error) {
267
+ result.success = false;
268
+ result.error = error.message;
269
+ console.error(chalk.red(`Restore failed: ${error.message}`));
270
+ }
271
+
272
+ return result;
273
+ }
274
+
275
+ /**
276
+ * Emergency restore - restores the last active backup
277
+ * @returns {Promise<Object>} Restore result
278
+ */
279
+ async emergencyRestore() {
280
+ console.log(chalk.red('🚨 EMERGENCY RESTORE INITIATED'));
281
+
282
+ if (!this.activeBackup) {
283
+ // Find most recent backup
284
+ const metadata = await this.loadMetadata();
285
+ const backups = metadata.backups
286
+ .filter(b => b.status === 'completed')
287
+ .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
288
+
289
+ if (backups.length === 0) {
290
+ throw new Error('No backups available for emergency restore');
291
+ }
292
+
293
+ this.activeBackup = backups[0].id;
294
+ }
295
+
296
+ console.log(chalk.yellow(`Restoring backup: ${this.activeBackup}`));
297
+ return await this.restoreBackup(this.activeBackup);
298
+ }
299
+
300
+ /**
301
+ * List available backups
302
+ * @param {Object} filter - Filter options
303
+ * @returns {Promise<Array>} List of backups
304
+ */
305
+ async listBackups(filter = {}) {
306
+ const metadata = await this.loadMetadata();
307
+ let backups = metadata.backups;
308
+
309
+ // Apply filters
310
+ if (filter.status) {
311
+ backups = backups.filter(b => b.status === filter.status);
312
+ }
313
+
314
+ if (filter.after) {
315
+ const afterDate = new Date(filter.after);
316
+ backups = backups.filter(b => new Date(b.timestamp) > afterDate);
317
+ }
318
+
319
+ if (filter.metadata) {
320
+ backups = backups.filter(b => {
321
+ return Object.entries(filter.metadata).every(([key, value]) =>
322
+ b.metadata[key] === value
323
+ );
324
+ });
325
+ }
326
+
327
+ // Sort by timestamp (newest first)
328
+ backups.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
329
+
330
+ return backups.map(b => ({
331
+ id: b.id,
332
+ timestamp: b.timestamp,
333
+ files: b.files.length,
334
+ size: this.formatSize(b.size),
335
+ metadata: b.metadata,
336
+ isActive: b.id === this.activeBackup
337
+ }));
338
+ }
339
+
340
+ /**
341
+ * Delete specific backup
342
+ * @param {string} backupId - Backup ID to delete
343
+ * @returns {Promise<boolean>} Success status
344
+ */
345
+ async deleteBackup(backupId) {
346
+ try {
347
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
348
+ await fs.unlink(backupPath);
349
+
350
+ // Remove from metadata
351
+ const metadata = await this.loadMetadata();
352
+ const index = metadata.backups.findIndex(b => b.id === backupId);
353
+
354
+ if (index !== -1) {
355
+ const backup = metadata.backups[index];
356
+ metadata.statistics.total_size -= backup.size;
357
+ metadata.backups.splice(index, 1);
358
+ await this.saveMetadata(metadata);
359
+ }
360
+
361
+ // Clear active backup if deleted
362
+ if (this.activeBackup === backupId) {
363
+ this.activeBackup = null;
364
+ }
365
+
366
+ console.log(chalk.gray(`Deleted backup: ${backupId}`));
367
+ return true;
368
+
369
+ } catch (error) {
370
+ console.error(chalk.red(`Failed to delete backup: ${error.message}`));
371
+ return false;
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Get backup details
377
+ * @param {string} backupId - Backup ID
378
+ * @returns {Promise<Object>} Backup details
379
+ */
380
+ async getBackupDetails(backupId) {
381
+ const metadata = await this.loadMetadata();
382
+ const backup = metadata.backups.find(b => b.id === backupId);
383
+
384
+ if (!backup) {
385
+ throw new Error(`Backup not found: ${backupId}`);
386
+ }
387
+
388
+ return backup;
389
+ }
390
+
391
+ /**
392
+ * Verify backup integrity
393
+ * @param {string} backupId - Backup ID to verify
394
+ * @returns {Promise<Object>} Verification result
395
+ */
396
+ async verifyBackup(backupId) {
397
+ console.log(chalk.blue(`🔍 Verifying backup: ${backupId}`));
398
+
399
+ const result = {
400
+ valid: true,
401
+ backupId,
402
+ errors: [],
403
+ warnings: []
404
+ };
405
+
406
+ try {
407
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
408
+
409
+ // Check file exists
410
+ try {
411
+ await fs.access(backupPath);
412
+ } catch {
413
+ result.valid = false;
414
+ result.errors.push('Backup file not found');
415
+ return result;
416
+ }
417
+
418
+ // Try to list archive contents
419
+ try {
420
+ const entries = [];
421
+ await tar.list({
422
+ file: backupPath,
423
+ onentry: entry => entries.push(entry.path)
424
+ });
425
+
426
+ if (!entries.includes('./backup-manifest.json')) {
427
+ result.valid = false;
428
+ result.errors.push('Missing backup manifest');
429
+ }
430
+ } catch (error) {
431
+ result.valid = false;
432
+ result.errors.push(`Archive corrupted: ${error.message}`);
433
+ }
434
+
435
+ } catch (error) {
436
+ result.valid = false;
437
+ result.errors.push(`Verification failed: ${error.message}`);
438
+ }
439
+
440
+ return result;
441
+ }
442
+
443
+ /**
444
+ * Check if has active backup
445
+ * @returns {boolean}
446
+ */
447
+ hasActiveBackup() {
448
+ return this.activeBackup !== null;
449
+ }
450
+
451
+ /**
452
+ * Load metadata
453
+ * @private
454
+ */
455
+ async loadMetadata() {
456
+ try {
457
+ const content = await fs.readFile(this.metadataFile, 'utf-8');
458
+ return JSON.parse(content);
459
+ } catch {
460
+ return {
461
+ version: '1.0.0',
462
+ backups: [],
463
+ statistics: {
464
+ total_backups: 0,
465
+ successful_restores: 0,
466
+ failed_restores: 0,
467
+ total_size: 0
468
+ }
469
+ };
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Save metadata
475
+ * @private
476
+ */
477
+ async saveMetadata(metadata) {
478
+ await fs.writeFile(
479
+ this.metadataFile,
480
+ JSON.stringify(metadata, null, 2)
481
+ );
482
+ }
483
+
484
+ /**
485
+ * Add backup to metadata
486
+ * @private
487
+ */
488
+ async addBackupToMetadata(backupInfo) {
489
+ const metadata = await this.loadMetadata();
490
+
491
+ metadata.backups.push(backupInfo);
492
+ metadata.statistics.total_backups++;
493
+ metadata.statistics.total_size += backupInfo.size;
494
+
495
+ await this.saveMetadata(metadata);
496
+ }
497
+
498
+ /**
499
+ * Clean old backups
500
+ * @private
501
+ */
502
+ async cleanOldBackups() {
503
+ const metadata = await this.loadMetadata();
504
+ const backups = metadata.backups
505
+ .filter(b => b.status === 'completed')
506
+ .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
507
+
508
+ if (backups.length > this.maxBackups) {
509
+ const toDelete = backups.slice(this.maxBackups);
510
+
511
+ for (const backup of toDelete) {
512
+ await this.deleteBackup(backup.id);
513
+ }
514
+
515
+ console.log(chalk.gray(`Cleaned ${toDelete.length} old backups`));
516
+ }
517
+ }
518
+
519
+ /**
520
+ * Generate backup ID
521
+ * @private
522
+ */
523
+ generateBackupId() {
524
+ const timestamp = Date.now();
525
+ const random = crypto.randomBytes(4).toString('hex');
526
+ return `backup-${timestamp}-${random}`;
527
+ }
528
+
529
+ /**
530
+ * Format file size
531
+ * @private
532
+ */
533
+ formatSize(bytes) {
534
+ const units = ['B', 'KB', 'MB', 'GB'];
535
+ let size = bytes;
536
+ let unitIndex = 0;
537
+
538
+ while (size >= 1024 && unitIndex < units.length - 1) {
539
+ size /= 1024;
540
+ unitIndex++;
541
+ }
542
+
543
+ return `${size.toFixed(2)} ${units[unitIndex]}`;
544
+ }
545
+
546
+ /**
547
+ * Export backup for external storage
548
+ * @param {string} backupId - Backup ID to export
549
+ * @param {string} exportPath - Path to export to
550
+ * @returns {Promise<Object>} Export result
551
+ */
552
+ async exportBackup(backupId, exportPath) {
553
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
554
+ const metadataPath = path.join(this.backupDir, `${backupId}-metadata.json`);
555
+
556
+ try {
557
+ // Copy backup file
558
+ await fs.copyFile(backupPath, exportPath);
559
+
560
+ // Export metadata
561
+ const metadata = await this.getBackupDetails(backupId);
562
+ await fs.writeFile(
563
+ metadataPath,
564
+ JSON.stringify(metadata, null, 2)
565
+ );
566
+
567
+ return {
568
+ success: true,
569
+ exported: exportPath,
570
+ metadata: metadataPath,
571
+ size: metadata.size
572
+ };
573
+
574
+ } catch (error) {
575
+ throw new Error(`Export failed: ${error.message}`);
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Import external backup
581
+ * @param {string} importPath - Path to backup file
582
+ * @param {Object} metadata - Backup metadata
583
+ * @returns {Promise<string>} Imported backup ID
584
+ */
585
+ async importBackup(importPath, metadata) {
586
+ const backupId = metadata.id || this.generateBackupId();
587
+ const backupPath = path.join(this.backupDir, `${backupId}.tar.gz`);
588
+
589
+ try {
590
+ // Copy backup file
591
+ await fs.copyFile(importPath, backupPath);
592
+
593
+ // Update metadata
594
+ metadata.id = backupId;
595
+ metadata.imported = new Date().toISOString();
596
+
597
+ await this.addBackupToMetadata(metadata);
598
+
599
+ return backupId;
600
+
601
+ } catch (error) {
602
+ throw new Error(`Import failed: ${error.message}`);
603
+ }
604
+ }
605
+ }
606
+
607
607
  module.exports = BackupManager;