Skip to content

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

docs(02-data-backup-recovery): create phase plan

Adam Eivy7700e0b26572
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index 6f0db57f34..da85b5baf6 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -43,11 +43,11 @@ Plans:
3. Backup runs automatically on a daily schedule and can be triggered manually from the dashboard
4. Dashboard widget displays last backup time, next scheduled time, and health status (green/yellow/red)
5. User can restore from a named snapshot with dry-run preview, and can selectively restore individual directories
-**Plans**: TBD
+**Plans**: 2 plans
Plans:
-- [ ] 02-01: TBD
-- [ ] 02-02: TBD
+- [ ] 02-01-PLAN.md -- Backup engine, scheduler, REST routes, validation schemas, and client API functions (BAK-01, BAK-02, BAK-03)
+- [ ] 02-02-PLAN.md -- Dashboard backup widget with health status, manual trigger, snapshot list, and restore UI (BAK-04, BAK-05, BAK-06, BAK-07)
### Phase 3: Apple Health Integration
**Goal**: Apple Health data flows into PortOS via JSON ingest and bulk XML import, with health metrics visible on the MeatSpace dashboard
diff --git a/.planning/phases/02-data-backup-recovery/02-01-PLAN.md b/.planning/phases/02-data-backup-recovery/02-01-PLAN.md
new file mode 100644
index 0000000000..701f4cd096
--- /dev/null
+++ b/.planning/phases/02-data-backup-recovery/02-01-PLAN.md
@@ -0,0 +1,365 @@
+---
+phase: 02-data-backup-recovery
+plan: "01"
+type: execute
+wave: 1
+depends_on: []
+files_modified:
+ - server/services/backup.js
+ - server/services/backupScheduler.js
+ - server/routes/backup.js
+ - server/lib/validation.js
+ - server/index.js
+ - client/src/services/api.js
+autonomous: true
+requirements:
+ - BAK-01
+ - BAK-02
+ - BAK-03
+
+must_haves:
+ truths:
+ - "Running POST /api/backup/run copies changed files from ./data/ to the configured external drive path via rsync"
+ - "A manifest.json with SHA-256 hashes exists inside each snapshot directory after backup completes"
+ - "Backup runs automatically on a daily cron schedule registered with eventScheduler"
+ - "GET /api/backup/status returns last backup time, next scheduled time, and current status"
+ - "GET /api/backup/snapshots returns a list of all snapshots with creation time and file count"
+ artifacts:
+ - path: "server/services/backup.js"
+ provides: "Core backup engine: runBackup, generateManifest, listSnapshots, restoreSnapshot, getState"
+ exports: ["runBackup", "generateManifest", "listSnapshots", "restoreSnapshot", "getState", "getNextRunTime"]
+ - path: "server/services/backupScheduler.js"
+ provides: "Scheduler registration mirroring brainScheduler.js pattern"
+ exports: ["startBackupScheduler", "stopBackupScheduler"]
+ - path: "server/routes/backup.js"
+ provides: "REST API: GET /status, POST /run, GET /snapshots, POST /restore"
+ - path: "server/lib/validation.js"
+ provides: "Zod schemas: backupConfigSchema, restoreRequestSchema"
+ contains: "backupConfigSchema"
+ - path: "client/src/services/api.js"
+ provides: "Client API functions: getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup"
+ key_links:
+ - from: "server/routes/backup.js"
+ to: "server/services/backup.js"
+ via: "import and call runBackup, listSnapshots, getState, restoreSnapshot"
+ pattern: "import.*backup"
+ - from: "server/services/backupScheduler.js"
+ to: "server/services/eventScheduler.js"
+ via: "schedule() call with cron type"
+ pattern: "eventScheduler.*schedule"
+ - from: "server/index.js"
+ to: "server/routes/backup.js"
+ via: "app.use('/api/backup', backupRoutes)"
+ pattern: "app\\.use.*backup"
+ - from: "server/index.js"
+ to: "server/services/backupScheduler.js"
+ via: "startBackupScheduler() call at server startup"
+ pattern: "startBackupScheduler"
+---
+
+<objective>
+Build the backup engine, scheduler, REST routes, and client API functions for PortOS data backup.
+
+Purpose: Establish the core backup infrastructure — rsync-based incremental copy from `./data/` to an external drive, SHA-256 manifest generation for integrity verification, cron scheduling via the existing eventScheduler, and a complete REST API. This enables Plan 02 to wire up the dashboard widget and restore UI.
+
+Output: Working backup service with scheduler, validated routes, and client API functions ready for widget consumption.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/02-data-backup-recovery/02-RESEARCH.md
+
+<interfaces>
+<!-- Key types and contracts the executor needs. Extracted from codebase. -->
+<!-- Executor should use these directly -- no codebase exploration needed. -->
+
+From server/services/eventScheduler.js:
+```javascript
+export {
+ schedule, // schedule({ id, type, cron, intervalMs, delayMs, handler, metadata })
+ cancel, // cancel(id) -> boolean
+ pause, // pause(id) -> boolean
+ resume, // resume(id) -> boolean
+ getScheduledEvents, // -> Array<{ id, type, active, nextRunAt, lastRunAt, runCount, metadata }>
+ getEvent, // getEvent(id) -> { id, type, active, cron, intervalMs, nextRunAt, lastRunAt, runCount, metadata } | null
+ getHistory,
+ getStats,
+ cancelAll,
+ triggerNow, // triggerNow(id) -> Promise<boolean>
+ parseCronToNextRun,
+ MAX_TIMEOUT
+}
+```
+
+From server/services/brainScheduler.js (pattern to mirror):
+```javascript
+export function startBrainScheduler() { ... } // Called at server startup in index.js
+export function stopBrainScheduler() { ... }
+```
+
+From server/services/settings.js:
+```javascript
+export const getSettings = load; // -> Promise<object> (reads data/settings.json)
+export const updateSettings = async (patch) => { ... }; // -> Promise<merged>
+```
+
+From server/lib/fileUtils.js:
+```javascript
+export const PATHS = {
+ root: join(__lib_dirname, '../..'),
+ data: join(__lib_dirname, '../../data'),
+ // ... other paths ...
+ meatspace: join(__lib_dirname, '../../data/meatspace')
+};
+export async function ensureDir(dir) { ... }
+export async function readJSONFile(filePath, defaultValue = null, { allowArray, logError } = {}) { ... }
+```
+
+From server/lib/errorHandler.js:
+```javascript
+export class ServerError extends Error { ... }
+export function asyncHandler(fn) { ... } // Wraps async route handlers
+export function normalizeError(err) { ... }
+```
+
+From server/lib/validation.js:
+```javascript
+export function validateRequest(schema, data) { ... } // Throws ServerError on failure
+```
+
+From server/index.js (route registration pattern):
+```javascript
+import backupRoutes from './routes/backup.js'; // alphabetical with other imports
+app.use('/api/backup', backupRoutes); // alphabetical among app.use() calls
+import { startBackupScheduler } from './services/backupScheduler.js';
+startBackupScheduler(); // after startBrainScheduler() call on line 228
+```
+
+From client/src/services/api.js (pattern):
+```javascript
+async function request(endpoint, options = {}) { ... } // base request function
+export const getBackupStatus = (options) => request('/backup/status', options);
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create backup service and scheduler</name>
+ <files>
+ server/services/backup.js
+ server/services/backupScheduler.js
+ </files>
+ <action>
+Create `server/services/backup.js` with these exports:
+
+1. **`runBackup(destPath, io = null)`** — Core backup function:
+ - Check `isRunning` flag; if true, log and return `{ skipped: true }`.
+ - Validate `destPath` exists with `fs.access(destPath)`. If missing, throw `new Error('Backup destination not found: ${destPath}')`.
+ - Set `isRunning = true`.
+ - Create snapshot ID from ISO timestamp with colons replaced: `new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '')`.
+ - Create snapshot dir: `join(destPath, 'snapshots', snapshotId)` and data subdir: `join(snapshotDir, 'data')`.
+ - Spawn rsync: `spawn('/usr/bin/rsync', ['--archive', '--itemize-changes', srcDir + '/', dataDestDir], { shell: false })`.
+ - Collect changed file lines from stdout (lines starting with `>` or `<`).
+ - Accept exit codes 0 and 24 as success (24 = vanished files, normal for active system). Reject on other codes.
+ - After rsync, call `generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'))`.
+ - Save state via `saveState({ lastRun, lastSnapshotId, status: 'ok', filesChanged, error: null })`.
+ - Set `isRunning = false` in a finally-equivalent pattern (set in both success path and error path).
+ - If `io` is provided, emit `backup:started` and `backup:completed` events.
+ - Use `PATHS.data` from `../lib/fileUtils.js` as source directory.
+
+2. **`generateManifest(snapshotDataDir, manifestPath)`** — Walk the snapshot data directory recursively:
+ - Use `fs.readdir` with `{ recursive: true }` and `fs.stat` to find regular files.
+ - For files under 512KB: `createHash('sha256').update(await readFile(filePath)).digest('hex')`.
+ - For files 512KB+: use streaming hash with `fs.createReadStream(filePath)` piped to `createHash('sha256')`.
+ - Write `manifest.json`: `{ generatedAt, fileCount, files: { relativePath: sha256Hash } }`.
+ - Return the manifest object.
+
+3. **`listSnapshots(destPath)`** — Read `join(destPath, 'snapshots')` directory, for each entry read its `manifest.json` if exists, return `[{ id, createdAt, fileCount }]` sorted newest-first.
+
+4. **`restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {})`** — Reverse rsync from snapshot back to `PATHS.data`:
+ - Build flags array: if `dryRun`, add `'--dry-run'`. Always include `'--archive'`, `'--itemize-changes'`.
+ - If `subdirFilter`, add `--include=${subdirFilter}/***`, `--include=*/`, `--exclude=*`.
+ - Spawn rsync from `join(destPath, 'snapshots', snapshotId, 'data')` to `PATHS.data`.
+ - Return `{ dryRun, snapshotId, subdirFilter, changedFiles }`.
+
+5. **`getState()`** — Read `join(PATHS.data, 'backup', 'state.json')` via `readJSONFile` with default `{ lastRun: null, status: 'never', lastSnapshotId: null, filesChanged: 0, error: null }`.
+
+6. **`saveState(patch)`** — Read current state, merge patch, write back to `join(PATHS.data, 'backup', 'state.json')`. Ensure `data/backup/` directory exists via `ensureDir`.
+
+7. **`getNextRunTime()`** — Import `getEvent` from `eventScheduler.js`, call `getEvent('backup-daily')`, return `event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null`.
+
+Internal helper **`runRsync(srcDir, destDir, flags = [])`** — as described in research Pattern 2. Use `spawn('/usr/bin/rsync', ...)` with `shell: false`.
+
+Logging: Use single-line emoji format per CLAUDE.md convention with `console.log()`:
+- `console.log('backup starting: snapshot ${snapshotId}')` (with appropriate emoji)
+- `console.log('backup rsync complete: ${changed.length} files changed (exit ${code})')` (with appropriate emoji)
+- `console.log('backup manifest: ${manifest.fileCount} files')` (with appropriate emoji)
+
+Create `server/services/backupScheduler.js` mirroring `brainScheduler.js` pattern:
+
+1. **`startBackupScheduler()`** — Import `schedule` from `eventScheduler.js` and `getSettings` from `settings.js`. Call `schedule({ id: 'backup-daily', type: 'cron', cron: settings.backup?.cronExpression || '0 2 * * *', handler: async () => { ... call runBackup ... }, metadata: { source: 'backupScheduler' } })`. Only schedule if `settings.backup?.enabled !== false` and `settings.backup?.destPath` exists. Log startup.
+
+2. **`stopBackupScheduler()`** — Import `cancel` from `eventScheduler.js`, cancel `'backup-daily'`.
+
+No try/catch blocks — errors bubble up per CLAUDE.md convention. The only exceptions are the `.catch()` patterns for file reads returning defaults (e.g., `readdir(...).catch(() => [])` in listSnapshots) which are acceptable project patterns.
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./services/backup.js').then(m => { console.log('exports:', Object.keys(m)); })" && node -e "import('./services/backupScheduler.js').then(m => { console.log('exports:', Object.keys(m)); })"</automated>
+ </verify>
+ <done>
+ - backup.js exports: runBackup, generateManifest, listSnapshots, restoreSnapshot, getState, saveState, getNextRunTime
+ - backupScheduler.js exports: startBackupScheduler, stopBackupScheduler
+ - No syntax errors on import
+ </done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create routes, validation schemas, wire into server, and add client API functions</name>
+ <files>
+ server/routes/backup.js
+ server/lib/validation.js
+ server/index.js
+ client/src/services/api.js
+ </files>
+ <action>
+**1. Add Zod schemas to `server/lib/validation.js`:**
+
+Add at the end of the file (before the closing comment if any), in a new section:
+
+```javascript
+// =============================================================================
+// BACKUP SCHEMAS
+// =============================================================================
+
+export const backupConfigSchema = z.object({
+ destPath: z.string().min(1),
+ cronExpression: z.string().optional(),
+ enabled: z.boolean().optional().default(true)
+});
+
+export const restoreRequestSchema = z.object({
+ snapshotId: z.string().min(1),
+ subdirFilter: z.string().optional().nullable(),
+ dryRun: z.boolean().optional().default(true)
+});
+```
+
+**2. Create `server/routes/backup.js`:**
+
+```javascript
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { restoreRequestSchema } from '../lib/validation.js';
+import * as backup from '../services/backup.js';
+import { getSettings } from '../services/settings.js';
+
+const router = Router();
+
+// GET /api/backup/status
+router.get('/status', asyncHandler(async (req, res) => {
+ const state = await backup.getState();
+ const settings = await getSettings();
+ const nextRun = backup.getNextRunTime();
+ res.json({ ...state, destPath: settings.backup?.destPath ?? null, nextRun });
+}));
+
+// POST /api/backup/run
+router.post('/run', asyncHandler(async (req, res) => {
+ const settings = await getSettings();
+ const io = req.app.get('io');
+ const result = await backup.runBackup(settings.backup?.destPath, io);
+ res.json(result);
+}));
+
+// GET /api/backup/snapshots
+router.get('/snapshots', asyncHandler(async (req, res) => {
+ const settings = await getSettings();
+ const snapshots = await backup.listSnapshots(settings.backup?.destPath);
+ res.json(snapshots);
+}));
+
+// POST /api/backup/restore
+router.post('/restore', asyncHandler(async (req, res) => {
+ const { snapshotId, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
+ const settings = await getSettings();
+ const result = await backup.restoreSnapshot(settings.backup?.destPath, snapshotId, { dryRun, subdirFilter });
+ res.json(result);
+}));
+
+export default router;
+```
+
+**3. Wire into `server/index.js`:**
+
+- Add import alphabetically among the existing route imports (after `autobiographyRoutes`, before `brainRoutes`):
+ `import backupRoutes from './routes/backup.js';`
+
+- Add route registration alphabetically among `app.use()` calls (after `/api/attachments` and before `/api/brain`):
+ `app.use('/api/backup', backupRoutes);`
+
+- Add scheduler import alongside the `brainScheduler` import:
+ `import { startBackupScheduler } from './services/backupScheduler.js';`
+
+- Add `startBackupScheduler();` call right after the existing `startBrainScheduler();` call (around line 228-229).
+
+**4. Add client API functions to `client/src/services/api.js`:**
+
+Add these exports at an appropriate location (alphabetically near other domain-grouped functions, or at the end before the file's last export group):
+
+```javascript
+// Backup
+export const getBackupStatus = (options) => request('/backup/status', options);
+export const triggerBackup = () => request('/backup/run', { method: 'POST' });
+export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
+export const restoreBackup = (data) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } });
+```
+
+Note: Check if `request()` already sets `Content-Type: application/json` header by default (it likely does based on the existing patterns). If so, omit the explicit headers in `restoreBackup`. Match the existing pattern in the file.
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/server && npm test 2>&1 | tail -5</automated>
+ </verify>
+ <done>
+ - All existing server tests pass (no regressions)
+ - `server/routes/backup.js` exists with GET /status, POST /run, GET /snapshots, POST /restore handlers
+ - `server/lib/validation.js` contains backupConfigSchema and restoreRequestSchema
+ - `server/index.js` imports and mounts backup routes at `/api/backup`
+ - `server/index.js` calls `startBackupScheduler()` at startup
+ - `client/src/services/api.js` exports getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup
+ </done>
+</task>
+
+</tasks>
+
+<verification>
+1. `node -e "import('./server/services/backup.js').then(m => console.log(Object.keys(m)))"` — confirms exports
+2. `node -e "import('./server/services/backupScheduler.js').then(m => console.log(Object.keys(m)))"` — confirms exports
+3. `cd server && npm test` — all existing tests pass (no regressions from validation.js or index.js changes)
+4. `grep -c 'backupConfigSchema\|restoreRequestSchema' server/lib/validation.js` — returns 2+
+5. `grep 'api/backup' server/index.js` — confirms route mount
+6. `grep 'startBackupScheduler' server/index.js` — confirms scheduler wired
+7. `grep 'getBackupStatus\|triggerBackup\|getBackupSnapshots\|restoreBackup' client/src/services/api.js` — confirms client functions
+</verification>
+
+<success_criteria>
+- backup.js and backupScheduler.js exist and import without errors
+- Validation schemas added to validation.js
+- Routes mounted at /api/backup in index.js
+- Scheduler starts at server boot
+- Client API functions available for widget consumption
+- All existing server tests pass
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/02-data-backup-recovery/02-01-SUMMARY.md`
+</output>
diff --git a/.planning/phases/02-data-backup-recovery/02-02-PLAN.md b/.planning/phases/02-data-backup-recovery/02-02-PLAN.md
new file mode 100644
index 0000000000..621427db0f
--- /dev/null
+++ b/.planning/phases/02-data-backup-recovery/02-02-PLAN.md
@@ -0,0 +1,271 @@
+---
+phase: 02-data-backup-recovery
+plan: "02"
+type: execute
+wave: 2
+depends_on:
+ - "02-01"
+files_modified:
+ - client/src/components/BackupWidget.jsx
+ - client/src/pages/Dashboard.jsx
+autonomous: false
+requirements:
+ - BAK-04
+ - BAK-05
+ - BAK-06
+ - BAK-07
+
+must_haves:
+ truths:
+ - "Dashboard displays a backup widget showing last backup time, next scheduled time, and health status with green/yellow/red indicator"
+ - "User can click a button in the widget to trigger a manual backup and sees toast feedback"
+ - "User can view a list of snapshots and initiate a restore with dry-run preview"
+ - "User can selectively restore a specific directory (e.g., brain/) from a snapshot"
+ artifacts:
+ - path: "client/src/components/BackupWidget.jsx"
+ provides: "Dashboard widget: status display, manual trigger, health indicator, snapshot list, restore UI"
+ min_lines: 80
+ - path: "client/src/pages/Dashboard.jsx"
+ provides: "BackupWidget imported and rendered in dashboard grid"
+ contains: "BackupWidget"
+ key_links:
+ - from: "client/src/components/BackupWidget.jsx"
+ to: "client/src/services/api.js"
+ via: "import and call getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup"
+ pattern: "api\\.getBackupStatus|api\\.triggerBackup"
+ - from: "client/src/components/BackupWidget.jsx"
+ to: "client/src/hooks/useAutoRefetch.js"
+ via: "useAutoRefetch hook for status polling"
+ pattern: "useAutoRefetch"
+ - from: "client/src/pages/Dashboard.jsx"
+ to: "client/src/components/BackupWidget.jsx"
+ via: "import and render in JSX grid"
+ pattern: "import BackupWidget"
+---
+
+<objective>
+Build the dashboard backup widget with health status display, manual backup trigger, snapshot listing, and restore UI with dry-run preview and selective directory restore.
+
+Purpose: Give the user visibility into backup health and one-click control over backup/restore operations directly from the dashboard. This completes the user-facing half of the backup system.
+
+Output: BackupWidget component rendered on the Dashboard, providing all BAK-04 through BAK-07 functionality.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/02-data-backup-recovery/02-RESEARCH.md
[email protected]/phases/02-data-backup-recovery/02-01-SUMMARY.md
+
+<interfaces>
+<!-- Key types and contracts the executor needs from Plan 02-01. -->
+
+From client/src/services/api.js (added by Plan 02-01):
+```javascript
+export const getBackupStatus = (options) => request('/backup/status', options);
+export const triggerBackup = () => request('/backup/run', { method: 'POST' });
+export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
+export const restoreBackup = (data) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data) });
+```
+
+API response shapes:
+
+GET /api/backup/status:
+```json
+{
+ "lastRun": "2026-02-26T02:00:00.000Z",
+ "lastSnapshotId": "2026-02-26T02-00-00",
+ "status": "ok" | "running" | "error" | "never",
+ "filesChanged": 12,
+ "error": null | "error message",
+ "destPath": "/Volumes/BackupDrive/PortOS",
+ "nextRun": "2026-02-27T02:00:00.000Z"
+}
+```
+
+GET /api/backup/snapshots:
+```json
+[
+ { "id": "2026-02-26T02-00-00", "createdAt": "2026-02-26T02-00-00", "fileCount": 245 },
+ { "id": "2026-02-25T02-00-00", "createdAt": "2026-02-25T02-00-00", "fileCount": 240 }
+]
+```
+
+POST /api/backup/restore (request):
+```json
+{ "snapshotId": "2026-02-26T02-00-00", "dryRun": true, "subdirFilter": "brain" }
+```
+
+POST /api/backup/restore (response):
+```json
+{ "dryRun": true, "snapshotId": "2026-02-26T02-00-00", "subdirFilter": "brain", "changedFiles": [">f..t...... brain/captures.json"] }
+```
+
+From client/src/hooks/useAutoRefetch.js:
+```javascript
+export function useAutoRefetch(fetchFn, intervalMs) {
+ // Returns { data, loading }
+}
+```
+
+From client/src/pages/Dashboard.jsx (existing imports and widget grid):
+```jsx
+import SystemHealthWidget from '../components/SystemHealthWidget';
+import CosDashboardWidget from '../components/CosDashboardWidget';
+// ... other widget imports ...
+// Widgets rendered inside a grid layout
+```
+
+Design tokens from CLAUDE.md:
+```
+port-bg: #0f0f0f port-card: #1a1a1a
+port-border: #2a2a2a port-accent: #3b82f6
+port-success: #22c55e port-warning: #f59e0b
+port-error: #ef4444
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create BackupWidget component and add to Dashboard</name>
+ <files>
+ client/src/components/BackupWidget.jsx
+ client/src/pages/Dashboard.jsx
+ </files>
+ <action>
+**Create `client/src/components/BackupWidget.jsx`:**
+
+A functional React component using `memo` (consistent with other widgets). Structure:
+
+**1. Status Section (always visible):**
+- Use `useAutoRefetch(() => api.getBackupStatus({ silent: true }).catch(() => null), 60000)` for status polling.
+- Show health indicator dot: green (`port-success`) if last run < 25 hours ago with no error, yellow (`port-warning`) if 25-49 hours or status is 'never', red (`port-error`) if > 49 hours or status is 'error'.
+- Display: "Last backup: {relative time}" (e.g., "2 hours ago"), "Next: {relative time}" (e.g., "in 22 hours"), destination path.
+- If `status === 'never'`, show "No backups yet" with guidance text.
+- If `status === 'running'`, show a spinner/indicator.
+- If `status === 'error'`, show the error message in red text.
+
+**2. Manual Trigger Button (BAK-05):**
+- Button labeled "Backup Now".
+- On click: call `api.triggerBackup()`, show `toast('Backup started', { icon: '...' })` on success, `toast.error('Backup failed: ' + err.message)` on failure. Use react-hot-toast (already imported pattern in api.js).
+- Disable button while status is 'running'.
+- No `window.alert` or `window.confirm` per CLAUDE.md.
+
+**3. Snapshots & Restore Section (expandable/collapsible):**
+- A toggle to show/hide snapshot list (keeps widget compact by default).
+- When expanded, fetch snapshots via `api.getBackupSnapshots()`.
+- List snapshots with date and file count.
+- Each snapshot has a "Restore" action that expands an inline restore panel (not a modal without URL per CLAUDE.md, but since this is a widget action within the dashboard, an inline expandable is acceptable).
+
+**4. Restore Panel (BAK-06, BAK-07):**
+- Shows for the selected snapshot.
+- Has a text input for `subdirFilter` (optional, placeholder: "e.g., brain" — for selective directory restore).
+- "Preview" button: calls `api.restoreBackup({ snapshotId, dryRun: true, subdirFilter: filter || null })`. Displays the list of files that would change.
+- "Restore" button (only enabled after preview): calls `api.restoreBackup({ snapshotId, dryRun: false, subdirFilter })`. Shows toast on completion.
+- The dry-run preview list shows each changed file path in a scrollable container.
+
+**5. Health computation helper function (not a hook, just a pure function):**
+```javascript
+function computeHealth(status) {
+ if (!status || status.status === 'error') return 'critical';
+ if (status.status === 'never') return 'warning';
+ if (status.status === 'running') return 'healthy';
+ if (!status.lastRun) return 'warning';
+ const hoursSince = (Date.now() - new Date(status.lastRun).getTime()) / (1000 * 60 * 60);
+ if (hoursSince < 25) return 'healthy';
+ if (hoursSince < 49) return 'warning';
+ return 'critical';
+}
+```
+
+**6. Relative time helper:**
+Use a simple relative time formatter (compute from Date.now() - target). Examples: "2 hours ago", "in 22 hours", "3 days ago". No external dependency needed — a small pure function is sufficient.
+
+**Styling:** Use Tailwind classes with the project's design tokens:
+- Widget card: `bg-port-card border border-port-border rounded-lg p-4`
+- Health dot: `w-2.5 h-2.5 rounded-full` with `bg-port-success`, `bg-port-warning`, or `bg-port-error`
+- Buttons: Match existing button patterns in the codebase (look at SystemHealthWidget or other widgets for consistent styling)
+- Text: `text-gray-400` for secondary, `text-white` for primary
+
+**Wire into `client/src/pages/Dashboard.jsx`:**
+
+- Add import alphabetically among widget imports (after `BrailleSpinner`, before `CosDashboardWidget`):
+ `import BackupWidget from '../components/BackupWidget';`
+
+- Add `<BackupWidget />` in the dashboard grid. Place it near SystemHealthWidget (it's infrastructure status). Look at the existing grid layout and add it in a logical position — after SystemHealthWidget is a good spot since both are system-status widgets.
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS && grep -c 'BackupWidget' client/src/pages/Dashboard.jsx && grep -c 'useAutoRefetch\|getBackupStatus\|triggerBackup\|restoreBackup' client/src/components/BackupWidget.jsx</automated>
+ </verify>
+ <done>
+ - BackupWidget.jsx exists with health status display, manual trigger button, snapshot list, and restore panel
+ - Dashboard.jsx imports and renders BackupWidget
+ - Health indicator uses green/yellow/red color coding
+ - Manual trigger uses toast notifications (no window.alert)
+ - Restore supports dry-run preview and selective directory filter
+ </done>
+</task>
+
+<task type="checkpoint:human-verify" gate="blocking">
+ <name>Task 2: Verify complete backup system end-to-end</name>
+ <files>client/src/components/BackupWidget.jsx</files>
+ <action>
+Human verification of the complete backup system. Before requesting verification, run these automated pre-checks:
+
+1. `curl -s http://localhost:5554/api/backup/status | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log('status:',j.status,'nextRun:',j.nextRun)})"` -- confirms API responds
+2. `mkdir -p /tmp/portos-backup-test && curl -s -X PUT http://localhost:5554/api/settings -H 'Content-Type: application/json' -d '{"backup":{"destPath":"/tmp/portos-backup-test","enabled":true}}'` -- configure test destination
+3. `curl -s -X POST http://localhost:5554/api/backup/run | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log('snapshot:',j.snapshotId,'files:',j.fileCount)})"` -- run a test backup
+4. `ls /tmp/portos-backup-test/snapshots/` -- verify snapshot directory created
+
+Then request human verification:
+- Open the PortOS dashboard in browser
+- Verify BackupWidget is visible with health indicator (green after test backup)
+- Click "Backup Now" button -- verify toast notification appears
+- Expand snapshot list -- verify snapshot appears with file count
+- Select a snapshot, type "brain" in filter field, click "Preview" -- verify dry-run file list appears
+ </action>
+ <verify>
+ <automated>curl -s http://localhost:5554/api/backup/status | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log(j.status!=='never'?'PASS':'FAIL')})"</automated>
+ </verify>
+ <done>
+ - Dashboard shows BackupWidget with correct health status
+ - Manual backup trigger works end-to-end
+ - Snapshot list displays correctly
+ - Dry-run restore preview shows expected file changes
+ - User has approved the visual and functional verification
+ </done>
+</task>
+
+</tasks>
+
+<verification>
+1. Dashboard shows BackupWidget with health status indicator
+2. Manual backup trigger works end-to-end (rsync copies files, manifest generated)
+3. Snapshot list displays with file counts
+4. Dry-run restore preview shows changed files
+5. Selective directory filter limits restore scope
+6. No window.alert or window.confirm usage
+7. Toast notifications for all user actions
+8. Health indicator correctly reflects backup age (green < 25h, yellow 25-49h, red > 49h)
+</verification>
+
+<success_criteria>
+- BackupWidget renders on Dashboard with current backup status
+- Health indicator shows green/yellow/red based on backup recency
+- "Backup Now" triggers manual backup with toast feedback
+- Snapshot list is viewable from the widget
+- Restore with dry-run preview works for both full and selective (subdirectory) restore
+- All existing tests still pass
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/02-data-backup-recovery/02-02-SUMMARY.md`
+</output>