aios-core 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.aios-core/.session/current-session.json +14 -0
- package/.aios-core/core/registry/registry-schema.json +166 -166
- package/.aios-core/core/registry/service-registry.json +6585 -6585
- package/.aios-core/data/entity-registry.yaml +208 -8
- package/.aios-core/data/registry-update-log.jsonl +165 -0
- package/.aios-core/development/scripts/approval-workflow.js +642 -642
- package/.aios-core/development/scripts/backup-manager.js +606 -606
- package/.aios-core/development/scripts/branch-manager.js +389 -389
- package/.aios-core/development/scripts/code-quality-improver.js +1311 -1311
- package/.aios-core/development/scripts/commit-message-generator.js +849 -849
- package/.aios-core/development/scripts/conflict-resolver.js +674 -674
- package/.aios-core/development/scripts/dependency-analyzer.js +637 -637
- package/.aios-core/development/scripts/diff-generator.js +351 -351
- package/.aios-core/development/scripts/elicitation-engine.js +384 -384
- package/.aios-core/development/scripts/elicitation-session-manager.js +299 -299
- package/.aios-core/development/scripts/git-wrapper.js +461 -461
- package/.aios-core/development/scripts/manifest-preview.js +244 -244
- package/.aios-core/development/scripts/metrics-tracker.js +775 -775
- package/.aios-core/development/scripts/modification-validator.js +554 -554
- package/.aios-core/development/scripts/pattern-learner.js +1224 -1224
- package/.aios-core/development/scripts/performance-analyzer.js +757 -757
- package/.aios-core/development/scripts/refactoring-suggester.js +1138 -1138
- package/.aios-core/development/scripts/rollback-handler.js +530 -530
- package/.aios-core/development/scripts/security-checker.js +358 -358
- package/.aios-core/development/scripts/template-engine.js +239 -239
- package/.aios-core/development/scripts/template-validator.js +278 -278
- package/.aios-core/development/scripts/test-generator.js +843 -843
- package/.aios-core/development/scripts/transaction-manager.js +589 -589
- package/.aios-core/development/scripts/usage-tracker.js +673 -673
- package/.aios-core/development/scripts/validate-filenames.js +226 -226
- package/.aios-core/development/scripts/version-tracker.js +526 -526
- package/.aios-core/development/scripts/yaml-validator.js +396 -396
- package/.aios-core/development/tasks/validate-next-story.md +99 -2
- package/.aios-core/development/templates/service-template/README.md.hbs +158 -158
- package/.aios-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
- package/.aios-core/development/templates/service-template/client.ts.hbs +403 -403
- package/.aios-core/development/templates/service-template/errors.ts.hbs +182 -182
- package/.aios-core/development/templates/service-template/index.ts.hbs +120 -120
- package/.aios-core/development/templates/service-template/package.json.hbs +87 -87
- package/.aios-core/development/templates/service-template/types.ts.hbs +145 -145
- package/.aios-core/development/templates/squad-template/LICENSE +21 -21
- package/.aios-core/docs/SHARD-TRANSLATION-GUIDE.md +335 -0
- package/.aios-core/docs/component-creation-guide.md +458 -0
- package/.aios-core/docs/session-update-pattern.md +307 -0
- package/.aios-core/docs/standards/AIOS-FRAMEWORK-MASTER.md +1963 -0
- package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1-SUMMARY.md +1190 -0
- package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1.md +439 -0
- package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO.md +5398 -0
- package/.aios-core/docs/standards/V3-ARCHITECTURAL-DECISIONS.md +523 -0
- package/.aios-core/docs/template-syntax.md +267 -0
- package/.aios-core/docs/troubleshooting-guide.md +625 -0
- package/.aios-core/infrastructure/templates/aios-sync.yaml.template +193 -193
- package/.aios-core/infrastructure/templates/coderabbit.yaml.template +279 -279
- package/.aios-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
- package/.aios-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
- package/.aios-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
- package/.aios-core/infrastructure/templates/gitignore/gitignore-aios-base.tmpl +63 -63
- package/.aios-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
- package/.aios-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
- package/.aios-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
- package/.aios-core/infrastructure/tests/utilities-audit-results.json +501 -0
- package/.aios-core/install-manifest.yaml +101 -101
- package/.aios-core/local-config.yaml.template +70 -70
- package/.aios-core/manifests/agents.csv +29 -0
- package/.aios-core/manifests/schema/manifest-schema.json +190 -190
- package/.aios-core/manifests/tasks.csv +198 -0
- package/.aios-core/manifests/workers.csv +204 -0
- package/.aios-core/monitor/hooks/lib/__init__.py +1 -1
- package/.aios-core/monitor/hooks/lib/enrich.py +58 -58
- package/.aios-core/monitor/hooks/lib/send_event.py +47 -47
- package/.aios-core/monitor/hooks/notification.py +29 -29
- package/.aios-core/monitor/hooks/post_tool_use.py +45 -45
- package/.aios-core/monitor/hooks/pre_compact.py +29 -29
- package/.aios-core/monitor/hooks/pre_tool_use.py +40 -40
- package/.aios-core/monitor/hooks/stop.py +29 -29
- package/.aios-core/monitor/hooks/subagent_stop.py +29 -29
- package/.aios-core/monitor/hooks/user_prompt_submit.py +38 -38
- package/.aios-core/product/templates/adr.hbs +125 -125
- package/.aios-core/product/templates/component-react-tmpl.tsx +98 -98
- package/.aios-core/product/templates/dbdr.hbs +241 -241
- package/.aios-core/product/templates/engine/schemas/adr.schema.json +102 -102
- package/.aios-core/product/templates/engine/schemas/dbdr.schema.json +205 -205
- package/.aios-core/product/templates/engine/schemas/epic.schema.json +175 -175
- package/.aios-core/product/templates/engine/schemas/pmdr.schema.json +175 -175
- package/.aios-core/product/templates/engine/schemas/prd-v2.schema.json +300 -300
- package/.aios-core/product/templates/engine/schemas/prd.schema.json +152 -152
- package/.aios-core/product/templates/engine/schemas/story.schema.json +222 -222
- package/.aios-core/product/templates/engine/schemas/task.schema.json +154 -154
- package/.aios-core/product/templates/epic.hbs +212 -212
- package/.aios-core/product/templates/eslintrc-security.json +32 -32
- package/.aios-core/product/templates/github-actions-cd.yml +212 -212
- package/.aios-core/product/templates/github-actions-ci.yml +172 -172
- package/.aios-core/product/templates/pmdr.hbs +186 -186
- package/.aios-core/product/templates/prd-v2.0.hbs +216 -216
- package/.aios-core/product/templates/prd.hbs +201 -201
- package/.aios-core/product/templates/shock-report-tmpl.html +502 -502
- package/.aios-core/product/templates/story.hbs +263 -263
- package/.aios-core/product/templates/task.hbs +170 -170
- package/.aios-core/product/templates/tmpl-comment-on-examples.sql +158 -158
- package/.aios-core/product/templates/tmpl-migration-script.sql +91 -91
- package/.aios-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
- package/.aios-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
- package/.aios-core/product/templates/tmpl-rls-roles.sql +135 -135
- package/.aios-core/product/templates/tmpl-rls-simple.sql +77 -77
- package/.aios-core/product/templates/tmpl-rls-tenant.sql +152 -152
- package/.aios-core/product/templates/tmpl-rollback-script.sql +77 -77
- package/.aios-core/product/templates/tmpl-seed-data.sql +140 -140
- package/.aios-core/product/templates/tmpl-smoke-test.sql +16 -16
- package/.aios-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
- package/.aios-core/product/templates/tmpl-stored-proc.sql +140 -140
- package/.aios-core/product/templates/tmpl-trigger.sql +152 -152
- package/.aios-core/product/templates/tmpl-view-materialized.sql +133 -133
- package/.aios-core/product/templates/tmpl-view.sql +177 -177
- package/.aios-core/product/templates/token-exports-css-tmpl.css +240 -240
- package/.aios-core/quality/schemas/quality-metrics.schema.json +233 -233
- package/.aios-core/scripts/migrate-framework-docs.sh +300 -300
- package/.aios-core/scripts/pm.sh +0 -0
- package/.claude/hooks/enforce-architecture-first.py +196 -196
- package/.claude/hooks/mind-clone-governance.py +192 -192
- package/.claude/hooks/read-protection.py +151 -151
- package/.claude/hooks/slug-validation.py +176 -176
- package/.claude/hooks/sql-governance.py +182 -182
- package/.claude/hooks/write-path-validation.py +194 -194
- package/.claude/rules/agent-authority.md +105 -0
- package/.claude/rules/coderabbit-integration.md +93 -0
- package/.claude/rules/ids-principles.md +112 -0
- package/.claude/rules/story-lifecycle.md +139 -0
- package/.claude/rules/workflow-execution.md +150 -0
- package/LICENSE +48 -48
- package/bin/aios-minimal.js +0 -0
- package/bin/aios.js +0 -0
- package/package.json +1 -1
- package/packages/aios-install/bin/aios-install.js +0 -0
- package/packages/aios-install/bin/edmcp.js +0 -0
- package/packages/aios-pro-cli/bin/aios-pro.js +0 -0
- package/packages/installer/src/wizard/pro-setup.js +433 -49
- package/scripts/check-markdown-links.py +352 -352
- package/scripts/code-intel-health-check.js +343 -0
- package/scripts/dashboard-parallel-dev.sh +0 -0
- package/scripts/dashboard-parallel-phase3.sh +0 -0
- package/scripts/dashboard-parallel-phase4.sh +0 -0
- package/scripts/glue/README.md +355 -0
- package/scripts/glue/compose-agent-prompt.cjs +362 -0
- package/scripts/install-monitor-hooks.sh +0 -0
- package/.aios-core/lib/build.json +0 -1
|
@@ -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;
|