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
fix(backup): select a pg_dump matching the server major version
[._.]/ Adam Eivy9cf4a2480d31
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f9cf16e261..f1415f42af 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,6 +47,8 @@## Fixed+- **Backup: the database dump now picks a `pg_dump` new enough for your server** — on machines with more than one PostgreSQL install (the common Homebrew case, where an older `postgresql@NN` keg shadows the running server in `PATH`), the backup ran an out-of-date `pg_dump` and failed with "server version mismatch" — leaving the backup degraded (files saved, database not). The backup now reads the live server's major version and selects a `pg_dump` at least that new from the installed Homebrew kegs / Postgres.app bundles (set `PORTOS_PGDUMP` to force a specific binary). When nothing new enough is installed, the failure is reported as a distinct `version_mismatch` with a Settings → Backup hint to install a newer `pg_dump`, instead of the generic "is pg_dump installed / is PG reachable" message; the exact `pg_dump` error is also available on hover.+- **Songs: "500 Miles" now ships the correct melody, in G major** — the built-in "500 Miles" previously carried a placeholder verse melody in C major that didn't match the song. It's been re-transcribed in G major (the Hedy West lead sheet — G · Em · C · Am7 · D7 · G) with the correct verse tune, chords, and rhythm. Fresh installs get it directly; an existing install that still holds the old placeholder is upgraded automatically on boot (a migration that only touches the unedited shipped version — a score you've customized is left alone), and you can always pull the latest via the song's "Refresh from template" button.- **Sheet music: low notes no longer overlap their lyrics** — the lyric line was drawn at a fixed distance below the staff, so notes that dip below it (ledger-line pitches like A3) rendered their noteheads on top of the syllable. Lyrics now sit below the lowest note in each line.- **[issue-980] PostgreSQL restores now verify the backup against its manifest before replaying** — a snapshot's database dump is hashed into the snapshot's `manifest.json` when the backup is taken, but the restore path never checked that hash, so a corrupted or tampered dump would be fed straight into `psql`. Restores now recompute the dump's SHA-256 and compare it against the stored hash first; on a mismatch the restore refuses (no `psql` is run) rather than replaying a damaged dump over your live database. Older snapshots taken before manifests existed — or any manifest missing the dump's entry — still restore as before, since there's nothing recorded to verify against.diff --git a/.env.example b/.env.exampleindex 90c60018fc..c04842f37c 100644--- a/.env.example+++ b/.env.example@@ -41,5 +41,11 @@ PGPASSWORD=portos# Path to the Claude CLI binary (defaults to system PATH)# CLAUDE_PATH=/usr/local/bin/claude+# Path to a specific pg_dump binary for database backups. By default PortOS+# auto-selects one whose major version is >= the running server (it scans+# Homebrew kegs + Postgres.app). Set this if auto-discovery can't find a new+# enough pg_dump on your platform (e.g. Linux/Windows multi-version installs).+# PORTOS_PGDUMP=/opt/homebrew/opt/postgresql@17/bin/pg_dump+# Duration (minutes) for Moltworld agent sessions# MOLTWORLD_DURATION_MINUTES=60diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex b5d70d0f3c..ad2783475b 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -180,7 +180,12 @@ export function BackupTab() {if (pgBackup.status === 'skipped') {return <span className="text-gray-400">⏭️ Not configured (file mode)</span>;}- return <span className="text-port-warning">❌ Dump failed: {pgBackup.reason}</span>;+ // title carries the raw pg_dump stderr so the exact cause is one hover away.+ return (+ <span className="text-port-warning" title={pgBackup.error || undefined}>+ ❌ Dump failed: {pgBackup.reason}+ </span>+ );};const handleRestoreDb = async (snapshotId) => {@@ -213,7 +218,12 @@ export function BackupTab() {<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-5">{backupStatus === 'degraded' && (<div className="bg-port-warning/10 border border-port-warning/40 rounded-lg px-3 py-2 text-sm text-port-warning">- ⚠️ Last backup degraded — files were saved but the database dump failed. Check that <code>pg_dump</code> is installed and PostgreSQL is reachable.+ ⚠️ Last backup degraded — files were saved but the database dump failed.{' '}+ {pgBackup?.reason === 'version_mismatch' ? (+ <>Your <code>pg_dump</code> is older than the running PostgreSQL server. Install/point at a <code>pg_dump</code> at least as new as the server (e.g. <code>brew install postgresql@17</code>), or set <code>PORTOS_PGDUMP</code> to its path.</>+ ) : (+ <>Check that <code>pg_dump</code> is installed and PostgreSQL is reachable.</>+ )}</div>)}diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex b946dc846d..2f0287577c 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -39,7 +39,7 @@ The effective exclude list is computed by the pure `computeEffectiveExcludes()`| Result | Meaning | Effect on backup ||---|---|---|| `{ status: 'ok', sizeBytes, tableCount }` | Dump succeeded and is non-empty | Backup `ok` |-| `{ status: 'failed', reason: 'pg_unreachable' \| 'pg_dump_missing' \| 'dump_error' \| 'empty_dump' }` | Postgres is the active backend but the dump failed | Backup **`degraded`** + warning toast |+| `{ status: 'failed', reason: 'pg_unreachable' \| 'pg_dump_missing' \| 'version_mismatch' \| 'dump_error' \| 'empty_dump' }` | Postgres is the active backend but the dump failed | Backup **`degraded`** + warning toast || `{ status: 'skipped', reason: 'not_configured' }` | The explicit file escape hatch is active — `MEMORY_BACKEND=file` or the backend resolved to `file` (dev/test, unsupported for production) | Backup stays `ok` (benign) |Key behaviors, accurate to the code:@@ -48,6 +48,7 @@ Key behaviors, accurate to the code:- **A skipped dump is still benign** only for the temporary `MEMORY_BACKEND=file` escape hatch (documented as unsupported for production installs). On a normal install where Postgres is active or auto-detected, an unreachable DB returns `failed/pg_unreachable`, not a green "not configured" run.- **`--clean --if-exists`** makes the dump replay cleanly into a live, already-initialized PortOS database — the common restore target — instead of erroring on `relation already exists`.- A `pg_dump` that exits 0 but produces a 0-byte file is treated as `failed/empty_dump`; a non-zero exit deletes the partial file so a later restore can't trust a truncated dump.+- **`version_mismatch`** means no installed `pg_dump` is new enough for the running server (`pg_dump` aborts when older than the server it dumps — the common Homebrew case where an old `postgresql@NN` keg shadows a newer running server in `PATH`). `dumpPostgres()` reads the server's major version (`getServerMajorVersion()` in `lib/db.js`) and auto-selects the closest `pg_dump` whose major is `>=` the server from the installed Homebrew kegs / Postgres.app bundles. Set `PORTOS_PGDUMP=/path/to/pg_dump` to override the auto-discovered binary (e.g. on Linux/Windows where the keg locations don't apply).## How restore worksdiff --git a/server/lib/db.js b/server/lib/db.jsindex ba5fe80feb..a54db70e87 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -39,6 +39,24 @@ export async function query(text, params) {return pool.query(text, params);}+/**+ * Read the connected server's PostgreSQL major version (e.g. 17 for 17.10).+ *+ * `server_version_num` is an integer like 170010 → major = floor(n / 10000).+ * Used by the backup service to select a `pg_dump` whose major version is+ * >= the server's: pg_dump aborts with "server version mismatch" when it is+ * older than the server it dumps, which is the common Homebrew footgun where+ * an older `postgresql@NN` keg shadows the running server in PATH.+ *+ * @returns {Promise<number|null>} major version, or null if unreachable/unparseable+ */+export async function getServerMajorVersion() {+ const result = await query('SHOW server_version_num').catch(() => null);+ const num = parseInt(result?.rows?.[0]?.server_version_num, 10);+ if (!Number.isFinite(num)) return null;+ return Math.floor(num / 10000);+}+/*** Run a function inside a database transaction.* Auto-commits on success, rolls back on error.diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex b39aa92e9f..7aad9d6e69 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -14,7 +14,9 @@ import { fileURLToPath } from 'url';import { homedir } from 'os';import { ServerError } from './errorHandler.js';-const execFileAsync = promisify(execFile);+// Promisified execFile — shared so callers (e.g. backup's pg_dump probing)+// don't each re-wrap it. Returns { stdout, stderr }.+export const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';// Cache __dirname calculation for services importing this modulediff --git a/server/services/backup.js b/server/services/backup.jsindex f06719dc23..da6ee0d7d4 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -10,9 +10,9 @@ import { spawn } from 'child_process';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';+import { PATHS, ensureDir, execFileAsync, readJSONFile, sha256File } from '../lib/fileUtils.js';import { getEvent } from './eventScheduler.js';-import { checkHealth } from '../lib/db.js';+import { checkHealth, getServerMajorVersion } from '../lib/db.js';import { getBackendName } from './memoryBackend.js';import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';import { getIo } from './socket.js';@@ -228,15 +228,96 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablreturn complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult });}+/**+ * Choose which discovered pg_dump binary to run, given the server's major+ * version. pg_dump REFUSES to dump a server newer than itself ("server version+ * mismatch"), but a newer pg_dump dumps an older server fine — so the rule is:+ * pick the closest binary whose major is >= the server's.+ *+ * Pure + exported for unit testing (the IO-bound discovery lives in+ * resolvePgDump, which feeds this the runnable candidates it found).+ *+ * @param {number|null} serverMajor - server's PG major version (null = unknown)+ * @param {Array<{binary: string, major: number}>} candidates - runnable pg_dumps+ * @returns {string|null} chosen binary path, or null if none discovered+ */+export function pickPgDump(serverMajor, candidates) {+ if (!candidates?.length) return null;+ // Unknown server version: keep prior behavior — trust the first (PATH) entry.+ if (!Number.isFinite(serverMajor)) return candidates[0].binary;+ // Prefer the smallest major that still satisfies >= server (closest match,+ // avoids reaching for a wildly newer keg when an exact one is installed).+ const viable = candidates.filter(c => c.major >= serverMajor).sort((a, b) => a.major - b.major);+ if (viable.length) return viable[0].binary;+ // Nothing is new enough. Return the newest we have so the resulting error is a+ // clear "still too old" instead of an arbitrary pick — and so the version+ // detection in dumpPostgres can flag it as version_mismatch.+ return [...candidates].sort((a, b) => b.major - a.major)[0].binary;+}++/**+ * Read a pg_dump binary's major version, or null if it isn't runnable.+ * `pg_dump --version` prints e.g. "pg_dump (PostgreSQL) 17.10 (Homebrew)".+ */+async function pgDumpMajor(binary) {+ const { stdout } = await execFileAsync(binary, ['--version']).catch(() => ({ stdout: '' }));+ const m = stdout.match(/PostgreSQL\)\s+(\d+)/i);+ return m ? parseInt(m[1], 10) : null;+}++/**+ * Enumerate candidate pg_dump locations: an explicit override, the bare PATH+ * binary, then versioned Homebrew kegs and Postgres.app bundles (where multiple+ * majors coexist and PATH order silently picks the wrong one).+ */+async function discoverPgDumpCandidates() {+ const paths = [];+ if (process.env.PORTOS_PGDUMP) paths.push(process.env.PORTOS_PGDUMP);+ paths.push('pg_dump'); // whatever PATH resolves — preserves the old default+ const kegDirs = ['/opt/homebrew/opt', '/usr/local/opt', '/Applications/Postgres.app/Contents/Versions'];+ for (const dir of kegDirs) {+ const entries = await readdir(dir).catch(() => []);+ for (const entry of entries) {+ if (dir.endsWith('Versions') || entry.startsWith('postgresql')) {+ paths.push(join(dir, entry, 'bin', 'pg_dump'));+ }+ }+ }+ // Probe versions concurrently (each `pg_dump --version` is an independent+ // spawn); [...new Set(paths)] de-dups while preserving priority order, which+ // Promise.all keeps — so pickPgDump still sees env > PATH > kegs.+ const probed = await Promise.all(+ [...new Set(paths)].map(async (binary) => ({ binary, major: await pgDumpMajor(binary) }))+ );+ return probed.filter(c => c.major != null);+}++/**+ * Resolve the pg_dump binary to use for a server at `serverMajor`. Returns the+ * chosen path and whether it satisfies the server's version (false ⇒ the dump+ * will fail with a version mismatch and there's nothing newer installed).+ *+ * @param {number|null} serverMajor+ * @returns {Promise<{binary: string, satisfies: boolean}>}+ */+async function resolvePgDump(serverMajor) {+ const candidates = await discoverPgDumpCandidates();+ const binary = pickPgDump(serverMajor, candidates) || 'pg_dump';+ const chosen = candidates.find(c => c.binary === binary);+ const satisfies = !Number.isFinite(serverMajor) || !chosen || chosen.major >= serverMajor;+ return { binary, satisfies };+}+/*** Run pg_dump to create a PostgreSQL backup alongside the rsync snapshot.* Returns an explicit status so the caller can distinguish the benign file* escape hatch from "PG required but dump failed" (data at risk):* { status: 'ok', sizeBytes, tableCount }* { status: 'skipped', reason: 'not_configured' } (explicit file escape hatch only)- * { status: 'failed', reason: 'pg_unreachable'|'pg_dump_missing'|'dump_error'|'empty_dump', error }+ * { status: 'failed', reason: 'pg_unreachable'|'pg_dump_missing'|'version_mismatch'|'dump_error'|'empty_dump', error }* (pg_unreachable fires whenever Postgres is required — i.e. not the file- * escape hatch — but the DB is down at backup time)+ * escape hatch — but the DB is down at backup time; version_mismatch means+ * no installed pg_dump is new enough for the running server)* @param {string} outputPath - Path to write the SQL dump file*/export async function dumpPostgres(outputPath) {@@ -269,12 +350,27 @@ export async function dumpPostgres(outputPath) {console.warn('⚠️ PGPASSWORD not set for pg_dump — using default');}- return new Promise((resolve) => {+ // pg_dump must be >= the server's major version or it aborts on a "server+ // version mismatch". On machines with multiple Postgres installs (the common+ // Homebrew case: an old postgresql@NN keg shadowing a newer running server in+ // PATH) the bare `pg_dump` is often the wrong one, so select a matching binary+ // instead of trusting PATH order.+ const serverMajor = await getServerMajorVersion();+ // Only probe for a matching binary when we actually know the server version;+ // if detection failed, keep the prior behavior (bare `pg_dump` off PATH).+ const { binary: pgDumpBin, satisfies } = Number.isFinite(serverMajor)+ ? await resolvePgDump(serverMajor)+ : { binary: 'pg_dump', satisfies: true };+ if (!satisfies) {+ console.warn(`⚠️ No installed pg_dump satisfies server major ${serverMajor} (using ${pgDumpBin})`);+ }++ return new Promise((resolvePromise) => {// --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', [+ const proc = spawn(pgDumpBin, ['-h', pgHost,'-p', pgPort,'-U', pgUser,@@ -299,14 +395,18 @@ export async function dumpPostgres(outputPath) {// 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() });+ // A version mismatch is a distinct, actionable failure (install a newer+ // pg_dump) — classify it so the UI can point at the fix instead of the+ // generic "is pg_dump installed / is PG reachable" hint.+ const isMismatch = !satisfies || /server version mismatch|aborting because of server version/i.test(stderr);+ resolvePromise({ status: 'failed', reason: isMismatch ? 'version_mismatch' : 'dump_error', error: stderr.trim() });return;}// Verify: a dump that exits 0 but is empty/truncated is still a failure.const info = await stat(outputPath).catch(() => null);if (!info || info.size === 0) {console.warn('⚠️ pg_dump produced an empty dump file');- resolve({ status: 'failed', reason: 'empty_dump', error: 'dump file missing or 0 bytes' });+ resolvePromise({ status: 'failed', reason: 'empty_dump', error: 'dump file missing or 0 bytes' });return;}const sql = await readFile(outputPath, 'utf-8').catch(() => '');@@ -317,14 +417,14 @@ export async function dumpPostgres(outputPath) {// the backup:completed socket event, and the /run response. No client// reads it (restorePostgres recomputes its own sqlPath), so leaking an// internal FS path serves no purpose.- resolve({ status: 'ok', sizeBytes: info.size, tableCount });+ resolvePromise({ status: 'ok', sizeBytes: info.size, tableCount });});proc.on('error', (err) => {// pg_dump not installed — a configured-but-unbacked-up DB is at risk,// so this is a failure, not a silent skip.console.warn(`⚠️ pg_dump not available: ${err.message}`);- resolve({ status: 'failed', reason: 'pg_dump_missing', error: err.message });+ resolvePromise({ status: 'failed', reason: 'pg_dump_missing', error: err.message });});});}diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex d070249e03..4387a1c66f 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -16,6 +16,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// Mock the DB health check and child_process.spawn before importing backup.jsvi.mock('../lib/db.js', () => ({checkHealth: vi.fn(),+ // Default to null (version unknown) so dumpPostgres keeps the bare-`pg_dump`+ // path and the existing status tests don't trigger live binary discovery.+ getServerMajorVersion: vi.fn(() => null),}));// Mock the memory-backend resolver so dumpPostgres can tell whether Postgres is@@ -45,7 +48,7 @@ vi.mock('fs/promises', async (importOriginal) => {import { checkHealth } from '../lib/db.js';import { getBackendName } from './memoryBackend.js';import * as fs from 'fs/promises';-import { DEFAULT_EXCLUDES, computeEffectiveExcludes } from './backup.js';+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, pickPgDump } from './backup.js';// Helper: build a fake child process whose close/error we can drive.function fakeProc() {@@ -155,6 +158,36 @@ describe('computeEffectiveExcludes', () => {});});+describe('pickPgDump', () => {+ const c = (major, binary = `pg_dump@${major}`) => ({ binary, major });++ it('returns null when no candidates were discovered', () => {+ expect(pickPgDump(17, [])).toBeNull();+ expect(pickPgDump(17, undefined)).toBeNull();+ });++ it('picks the exact-major binary when one is installed', () => {+ const chosen = pickPgDump(17, [c(15), c(17), c(16)]);+ expect(chosen).toBe('pg_dump@17');+ });++ it('picks the closest binary that is >= the server (newer is fine, never older)', () => {+ // server 16: 15 is too old, choose 17 (smallest qualifying), not 18.+ expect(pickPgDump(16, [c(15), c(17), c(18)])).toBe('pg_dump@17');+ });++ it('falls back to the newest available when nothing is new enough (forces a clear mismatch error)', () => {+ // This is the reported bug: server 17, only pg_dump 15 installed.+ expect(pickPgDump(17, [c(15)])).toBe('pg_dump@15');+ expect(pickPgDump(17, [c(14), c(15)])).toBe('pg_dump@15');+ });++ it('trusts the first (PATH) candidate when the server version is unknown', () => {+ expect(pickPgDump(null, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');+ expect(pickPgDump(NaN, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');+ });+});+describe('dumpPostgres status classification', () => {let dumpPostgres;beforeEach(async () => {@@ -277,6 +310,26 @@ describe('dumpPostgres status classification', () => {expect(result.error).toContain('auth failed');});+ it('classifies a "server version mismatch" stderr as failed/version_mismatch, not dump_error', async () => {+ // Even with the server version unknown (default mock → bare pg_dump), the+ // stderr regex must reclassify pg_dump's own mismatch error so the UI can+ // point at "install a newer pg_dump" instead of the generic hint.+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const p = dumpPostgres('/tmp/x.sql');+ await flush();+ proc.stderr.emit('data', Buffer.from(+ 'pg_dump: error: aborting because of server version mismatch\n' ++ 'pg_dump: detail: server version: 17.10; pg_dump version: 15.18'+ ));+ proc.emit('close', 1);+ const result = await p;+ expect(result.status).toBe('failed');+ expect(result.reason).toBe('version_mismatch');+ expect(result.error).toContain('server version mismatch');+ });+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();