Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(02-01): add backup service and scheduler
Adam Eivy8a01c2bbb431
diff --git a/server/services/backup.js b/server/services/backup.jsnew file mode 100644index 0000000000..ea1e3a4e09--- /dev/null+++ b/server/services/backup.js@@ -0,0 +1,264 @@+/**+ * Backup Service+ *+ * Rsync-based incremental backup from ./data/ to an external drive.+ * Generates SHA-256 manifests for integrity verification.+ * Integrates with eventScheduler for daily cron scheduling.+ */++import { spawn } from 'child_process';+import { createHash } from 'crypto';+import { createReadStream } from 'fs';+import { access, readFile, readdir, stat, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { getEvent } from './eventScheduler.js';++// Module-level state+let isRunning = false;++const STATE_PATH = join(PATHS.data, 'backup', 'state.json');+const DEFAULT_STATE = {+ lastRun: null,+ status: 'never',+ lastSnapshotId: null,+ filesChanged: 0,+ error: null+};++// =============================================================================+// INTERNAL HELPERS+// =============================================================================++/**+ * Run rsync from srcDir to destDir with optional flags.+ * Resolves with array of changed file lines. Rejects on non-zero exit (except 24).+ */+function runRsync(srcDir, destDir, flags = []) {+ return new Promise((resolve, reject) => {+ const args = ['--archive', '--itemize-changes', ...flags, srcDir + '/', destDir];+ const proc = spawn('/usr/bin/rsync', args, { shell: false });++ const changed = [];+ let stderr = '';++ proc.stdout.on('data', (chunk) => {+ const lines = chunk.toString().split('\n').filter(Boolean);+ for (const line of lines) {+ if (line.startsWith('>') || line.startsWith('<')) {+ changed.push(line);+ }+ }+ });++ proc.stderr.on('data', (chunk) => {+ stderr += chunk.toString();+ });++ proc.on('close', (code) => {+ // Exit code 24 = some files vanished mid-transfer (normal for active system)+ if (code === 0 || code === 24) {+ resolve(changed);+ } else {+ reject(new Error(`rsync exited with code ${code}: ${stderr.trim()}`));+ }+ });++ proc.on('error', (err) => {+ reject(new Error(`rsync spawn error: ${err.message}`));+ });+ });+}++// =============================================================================+// EXPORTS+// =============================================================================++/**+ * Run a full backup snapshot from PATHS.data to destPath.+ * @param {string} destPath - Path to external drive backup root+ * @param {object|null} io - Socket.IO instance for real-time events (optional)+ */+export async function runBackup(destPath, io = null) {+ if (isRunning) {+ console.log('💾 Backup already running — skipping');+ return { skipped: true };+ }++ if (!destPath) {+ throw new Error('Backup destination not configured');+ }++ await access(destPath).catch(() => {+ throw new Error(`Backup destination not found: ${destPath}`);+ });++ isRunning = true;+ const snapshotId = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');+ const snapshotDir = join(destPath, 'snapshots', snapshotId);+ const dataDestDir = join(snapshotDir, 'data');++ console.log(`💾 Backup starting: snapshot ${snapshotId}`);+ if (io) io.emit('backup:started', { snapshotId });++ await ensureDir(dataDestDir);++ let changedFiles = [];+ let manifest;++ const complete = async (result) => {+ isRunning = false;+ return result;+ };++ const fail = async (err) => {+ isRunning = false;+ await saveState({ lastRun: new Date().toISOString(), status: 'error', error: err.message });+ throw err;+ };++ changedFiles = await runRsync(PATHS.data, dataDestDir).catch(fail);+ console.log(`💾 Backup rsync complete: ${changedFiles.length} files changed (exit 0)`);++ manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json')).catch(fail);++ const lastRun = new Date().toISOString();+ await saveState({+ lastRun,+ lastSnapshotId: snapshotId,+ status: 'ok',+ filesChanged: changedFiles.length,+ error: null+ }).catch(fail);++ if (io) io.emit('backup:completed', { snapshotId, filesChanged: changedFiles.length });++ return complete({ snapshotId, filesChanged: changedFiles.length, lastRun, manifest });+}++/**+ * Generate a SHA-256 manifest for all files in snapshotDataDir.+ * @param {string} snapshotDataDir - Directory to hash+ * @param {string} manifestPath - Path to write manifest.json+ */+export async function generateManifest(snapshotDataDir, manifestPath) {+ const entries = await readdir(snapshotDataDir, { recursive: true }).catch(() => []);+ const files = {};++ for (const entry of entries) {+ const filePath = join(snapshotDataDir, entry);+ const info = await stat(filePath).catch(() => null);+ if (!info || !info.isFile()) continue;++ const relativePath = entry;+ let hash;++ if (info.size < 512 * 1024) {+ // Small file: read all at once+ const content = await readFile(filePath);+ hash = createHash('sha256').update(content).digest('hex');+ } else {+ // Large file: streaming hash+ hash = await new Promise((resolve, reject) => {+ const stream = createReadStream(filePath);+ const hasher = createHash('sha256');+ stream.pipe(hasher);+ stream.on('error', reject);+ hasher.on('finish', () => resolve(hasher.digest('hex')));+ hasher.on('error', reject);+ });+ }++ files[relativePath] = hash;+ }++ const manifest = {+ generatedAt: new Date().toISOString(),+ fileCount: Object.keys(files).length,+ files+ };++ await writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');+ console.log(`💾 Backup manifest: ${manifest.fileCount} files`);+ return manifest;+}++/**+ * List all snapshots in the backup destination.+ * @param {string} destPath - Path to external drive backup root+ * @returns {Array<{ id, createdAt, fileCount }>} sorted newest-first+ */+export async function listSnapshots(destPath) {+ if (!destPath) return [];++ const snapshotsDir = join(destPath, 'snapshots');+ const entries = await readdir(snapshotsDir).catch(() => []);++ const snapshots = await Promise.all(+ entries.map(async (id) => {+ const manifestPath = join(snapshotsDir, id, 'manifest.json');+ const manifest = await readJSONFile(manifestPath, null);+ return {+ id,+ createdAt: manifest?.generatedAt ?? null,+ fileCount: manifest?.fileCount ?? 0+ };+ })+ );++ return snapshots.sort((a, b) => {+ if (!a.createdAt) return 1;+ if (!b.createdAt) return -1;+ return b.createdAt.localeCompare(a.createdAt);+ });+}++/**+ * Restore a snapshot back to PATHS.data using rsync.+ * @param {string} destPath - Path to external drive backup root+ * @param {string} snapshotId - Snapshot ID to restore+ * @param {object} options+ * @param {boolean} [options.dryRun=true] - If true, do not write any files+ * @param {string|null} [options.subdirFilter=null] - Limit restore to a subdirectory+ */+export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {}) {+ const srcDir = join(destPath, 'snapshots', snapshotId, 'data');++ const flags = ['--itemize-changes'];+ if (dryRun) flags.push('--dry-run');+ if (subdirFilter) {+ flags.push(`--include=${subdirFilter}/***`);+ flags.push('--include=*/');+ flags.push('--exclude=*');+ }++ const changedFiles = await runRsync(srcDir, PATHS.data, flags);+ return { dryRun, snapshotId, subdirFilter, changedFiles };+}++/**+ * Get current backup state from disk.+ */+export async function getState() {+ return readJSONFile(STATE_PATH, DEFAULT_STATE);+}++/**+ * Merge patch into current backup state and persist.+ * @param {object} patch - Fields to merge into state+ */+export async function saveState(patch) {+ await ensureDir(join(PATHS.data, 'backup'));+ const current = await getState();+ const updated = { ...current, ...patch };+ await writeFile(STATE_PATH, JSON.stringify(updated, null, 2), 'utf-8');+}++/**+ * Get the next scheduled backup run time from eventScheduler.+ * @returns {string|null} ISO timestamp of next run, or null+ */+export function getNextRunTime() {+ const event = getEvent('backup-daily');+ return event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null;+}diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.jsnew file mode 100644index 0000000000..07f6531642--- /dev/null+++ b/server/services/backupScheduler.js@@ -0,0 +1,53 @@+/**+ * Backup Scheduler Service+ *+ * Registers a daily cron job for automated backups using eventScheduler.+ * Mirrors the brainScheduler.js pattern.+ */++import { schedule, cancel } from './eventScheduler.js';+import { getSettings } from './settings.js';+import { runBackup } from './backup.js';++/**+ * Start the backup scheduler.+ * Reads backup settings and registers a daily cron job with eventScheduler.+ * No-ops if backup is disabled or destPath is not configured.+ */+export async function startBackupScheduler() {+ const settings = await getSettings();++ if (settings.backup?.enabled === false) {+ console.log('💾 Backup scheduler: disabled in settings — skipping');+ return;+ }++ if (!settings.backup?.destPath) {+ console.log('💾 Backup scheduler: no destPath configured — skipping');+ return;+ }++ const cronExpression = settings.backup?.cronExpression || '0 2 * * *';+ const destPath = settings.backup.destPath;++ schedule({+ id: 'backup-daily',+ type: 'cron',+ cron: cronExpression,+ handler: async () => {+ console.log('💾 Backup scheduler: running scheduled backup');+ await runBackup(destPath);+ },+ metadata: { source: 'backupScheduler' }+ });++ console.log(`💾 Backup scheduler: registered daily backup at cron "${cronExpression}" -> ${destPath}`);+}++/**+ * Stop the backup scheduler by cancelling the scheduled event.+ */+export function stopBackupScheduler() {+ cancel('backup-daily');+ console.log('💾 Backup scheduler: stopped');+}