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
address review (codex): atomic restore (--single-transaction), --clean dump for live-DB restore, unlink partial dumps, degraded in City vault
Adam Eivy49d83cb29507
diff --git a/client/src/utils/cityBackupVault.js b/client/src/utils/cityBackupVault.jsindex 881b04eb36..2f39483992 100644--- a/client/src/utils/cityBackupVault.js+++ b/client/src/utils/cityBackupVault.js@@ -21,18 +21,23 @@ const HEALTH_COLORS = {aging: '#f59e0b', // port-warning — getting oldstale: '#ef4444', // port-error — overdueerror: '#ef4444', // port-error — last run failed+ degraded: '#f59e0b', // port-warning — files saved but DB dump failednever: '#64748b', // slate — never backed up / not configuredrunning: '#3b82f6', // port-accent — a backup is in flight};// Map persisted backup state → a health classification. `state.status` is the stored-// status ('never' | 'ok' | 'error'); `state.lastRun` is the ISO timestamp of the last+// status ('never' | 'ok' | 'degraded' | 'error'); `state.lastRun` is the ISO timestamp of the last// run (or null); `state.running` is set true while a backup is in flight (socket-driven).// `now` is injected so the staleness derivation is deterministic in tests.export function vaultHealth(state, now = Date.now()) {if (state?.running) return 'running';const status = state?.status || 'never';if (status === 'error') return 'error';+ // 'degraded' = files backed up but the DB dump failed — alert, don't read as+ // PROTECTED. Classified before the staleness path so a recent degraded run+ // (fresh lastRun) can't fall through to 'ok'.+ if (status === 'degraded') return 'degraded';if (status === 'never' || !state?.lastRun) return 'never';const last = new Date(state.lastRun).getTime();if (!Number.isFinite(last)) return 'never';@@ -48,7 +53,7 @@ export function vaultColor(health) {// Should the vault read as needing attention (urgent pulse, brighter glow)?export function vaultIsAlerting(health) {- return health === 'stale' || health === 'error';+ return health === 'stale' || health === 'error' || health === 'degraded';}// Short uppercase label rendered under the monument.@@ -59,6 +64,7 @@ export function vaultStatusLabel(health) {case 'aging': return 'AGING';case 'stale': return 'STALE';case 'error': return 'FAILED';+ case 'degraded': return 'DB FAILED';default: return 'NO BACKUP';}}diff --git a/client/src/utils/cityBackupVault.test.js b/client/src/utils/cityBackupVault.test.jsindex c6390b3d8d..ab5726b3be 100644--- a/client/src/utils/cityBackupVault.test.js+++ b/client/src/utils/cityBackupVault.test.js@@ -47,6 +47,10 @@ describe('vaultHealth', () => {it('reports "running" when a backup is in flight, overriding everything', () => {expect(vaultHealth({ status: 'error', lastRun: daysAgo(9), running: true }, NOW)).toBe('running');});++ it('reports "degraded" when files saved but the DB dump failed, even on a fresh run', () => {+ expect(vaultHealth({ status: 'degraded', lastRun: hoursAgo(1) }, NOW)).toBe('degraded');+ });});describe('vaultColor', () => {@@ -57,6 +61,7 @@ describe('vaultColor', () => {expect(vaultColor('error')).toBe('#ef4444');expect(vaultColor('running')).toBe('#3b82f6');expect(vaultColor('never')).toBe('#64748b');+ expect(vaultColor('degraded')).toBe('#f59e0b');});it('falls back to the never color for an unknown health', () => {@@ -65,9 +70,10 @@ describe('vaultColor', () => {});describe('vaultIsAlerting', () => {- it('alerts only on stale or error', () => {+ it('alerts on stale, error, or degraded', () => {expect(vaultIsAlerting('stale')).toBe(true);expect(vaultIsAlerting('error')).toBe(true);+ expect(vaultIsAlerting('degraded')).toBe(true);expect(vaultIsAlerting('ok')).toBe(false);expect(vaultIsAlerting('aging')).toBe(false);expect(vaultIsAlerting('running')).toBe(false);@@ -82,6 +88,7 @@ describe('vaultStatusLabel', () => {expect(vaultStatusLabel('aging')).toBe('AGING');expect(vaultStatusLabel('stale')).toBe('STALE');expect(vaultStatusLabel('error')).toBe('FAILED');+ expect(vaultStatusLabel('degraded')).toBe('DB FAILED');expect(vaultStatusLabel('never')).toBe('NO BACKUP');expect(vaultStatusLabel('bogus')).toBe('NO BACKUP');});diff --git a/server/services/backup.js b/server/services/backup.jsindex 6ecdf0c311..120aee3e5b 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -7,7 +7,7 @@*/import { spawn } from 'child_process';-import { access, readdir, readFile, stat, writeFile } from 'fs/promises';+import { access, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';import { hostname } from 'os';import { join, resolve, relative, isAbsolute } from 'path';import { PATHS, ensureDir, readJSONFile, sha256File } from '../lib/fileUtils.js';@@ -252,6 +252,10 @@ export async function dumpPostgres(outputPath) {}return new Promise((resolve) => {+ // --clean --if-exists: the dump DROPs each object before recreating it, so it+ // replays cleanly into the live, already-initialized PortOS database (the+ // common Restore-DB target) instead of erroring "relation already exists" on+ // the first CREATE. Without it the dump is only restorable into an empty DB.const proc = spawn('pg_dump', ['-h', pgHost,'-p', pgPort,@@ -259,6 +263,8 @@ export async function dumpPostgres(outputPath) {'-d', pgDb,'--no-owner','--no-acl',+ '--clean',+ '--if-exists','-f', outputPath], {shell: false,@@ -271,6 +277,10 @@ export async function dumpPostgres(outputPath) {proc.on('close', async (code) => {if (code !== 0) {console.warn(`⚠️ pg_dump failed (code ${code}): ${stderr.trim()}`);+ // pg_dump can exit non-zero after writing a partial file (e.g. mid-dump+ // connection loss). Remove it so a later restore can't trust a truncated+ // dump on size alone — a failed dump must leave no restorable artifact.+ await unlink(outputPath).catch(() => {});resolve({ status: 'failed', reason: 'dump_error', error: stderr.trim() });return;}@@ -450,11 +460,15 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =const pgUser = process.env.PGUSER || 'portos';return new Promise((resolveP) => {- // ON_ERROR_STOP=1 makes psql abort and exit non-zero on the first failed- // statement. Without it psql replays best-effort and exits 0 even when- // statements fail — a partial restore would falsely report success.+ // ON_ERROR_STOP=1 aborts on the first failed statement; --single-transaction+ // wraps the whole replay in one transaction so that abort ROLLs BACK every+ // prior statement. Together they make the restore atomic: it either fully+ // applies or leaves the live DB untouched — never a mixed snapshot/current+ // state. (The dump is written with --clean --if-exists, so the DROPs and+ // recreates all commit or roll back as one unit.)const proc = spawn('psql', ['-v', 'ON_ERROR_STOP=1',+ '--single-transaction','-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-f', sqlPath], { shell: false, env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 12615d5c96..ca2bd1f2fb 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -193,6 +193,18 @@ describe('dumpPostgres status classification', () => {expect(result.error).toContain('auth failed');});+ it('unlinks the partial dump file on non-zero exit (no restorable artifact left behind)', async () => {+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const unlinkSpy = vi.spyOn(fs, 'unlink').mockResolvedValue();+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const p = dumpPostgres('/tmp/x.sql');+ await flush();+ proc.emit('close', 1);+ await p;+ expect(unlinkSpy).toHaveBeenCalledWith('/tmp/x.sql');+ });+it('returns failed/empty_dump when exit 0 but file is 0 bytes', async () => {checkHealth.mockResolvedValue({ connected: true, hasSchema: true });vi.spyOn(fs, 'stat').mockResolvedValue({ size: 0 });