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

fix: preserve selected database when Docker is unavailable (#8951)

[._.]/ Adam Eivy89853d6332dc
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index fbef33a592..51d1577e7f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -262,13 +262,13 @@ PortOS treats **PostgreSQL as a mandatory install/runtime dependency** for every
- **System (native) PostgreSQL on `:5432`** — `PGMODE=native`, or
- **Docker PostgreSQL on `:5561`** — `PGMODE=docker` (the default).
-Provision either path with **`npm run setup:db`** (also run automatically by `npm run setup` and `npm start`). It follows `PGMODE` (shell environment → `.env` → `docker`), so an available Docker installation takes precedence over a healthy native database unless you explicitly select `native`. Native auto-detection is a fallback only when Docker or Compose is unavailable, or the Docker daemon is stopped. See [Setup path](#setup-path-npm-run-setupdb) below.
+Provision either path with **`npm run setup:db`** (also run automatically by `npm run setup` and `npm start`). It follows `PGMODE` (shell environment → `.env` → `docker`), and provisions only that selected backend. An unavailable Docker installation fails setup without probing native PostgreSQL or changing the saved mode. See [Setup path](#setup-path-npm-run-setupdb) below.
### `MEMORY_BACKEND=file` is a development/test-only escape hatch — NOT a deployment mode
The file backend (`server/services/memory.js`, JSON under `./data/`) is **unsupported for production and for federated peers.** It exists only so the test suite (and ad-hoc local development) can boot without a database. It is **not** a fallback, a "lite" mode, or a way to run PortOS without Postgres:
-- It is reached **only** via the explicit `MEMORY_BACKEND=file` env var (set from `PGMODE=file` in `.env`, mapped by the launcher) **or** automatically under `NODE_ENV=test`. There is no menu choice for it (`scripts/setup-db.js` offers only Docker and Native), and `npm run setup:db` with `PGMODE=file` prints an "unsupported" notice and refuses to provision it.
+- It is reached **only** via the explicit `MEMORY_BACKEND=file` env var (set from `PGMODE=file` in `.env`, mapped by the launcher) **or** automatically under `NODE_ENV=test`. Setup has no interactive backend menu, and `npm run setup:db` with `PGMODE=file` prints an "unsupported" notice and refuses to provision it.
- When `MEMORY_BACKEND` is unset, PortOS **requires** a healthy database and **does NOT silently fall back to file storage** — an unreachable/unmigrated DB is an error condition. `server/services/memoryBackend.js` fails fast with an actionable message (`run npm run setup:db`) rather than serving a half-broken install. This no-silent-fallback behavior is intentional; do not "fix" it.
**Why file storage cannot be a supported mode:**
@@ -283,9 +283,9 @@ The escape hatch is **guarded from bitrot by the test suite** (tests boot with `
`npm run setup:db` → `scripts/setup-db.js` is the single command that makes PostgreSQL ready, and is wired into `npm run setup` and `npm start` so a normal install never has to think about it. Its happy path:
-1. **Select the mode first.** Set `PGMODE=native` in the repository-root `.env` before running setup to reuse a native PortOS database, even when Docker is running. An exported `PGMODE` overrides `.env` for this script; unset a conflicting shell value before retrying.
+1. **Select the mode first.** For a fresh native install, set `PGMODE=native` in the repository-root `.env` before running setup. For an existing install, retain its authoritative backend; changing backends requires coordinated maintenance cutover, not a setup-time selection. An exported `PGMODE` overrides `.env` for this script; unset a conflicting shell value before retrying.
2. **`PGMODE=docker` (default):** starts or reuses the `pgvector/pgvector:pg17` container (`docker-compose.yml`), waits for TCP connections **and** the base `memories` table, then reports ready. It does not probe native PostgreSQL first. The host port defaults to `:5561` (`PGPORT_DOCKER` overrides it).
-3. **Docker unavailable:** if Docker or Compose is missing, or the daemon is stopped, a healthy native PortOS database triggers an automatic switch: setup writes `PGMODE=native` to `.env` and exits successfully. Otherwise an interactive terminal offers native bootstrap or instructions to install/start Docker; a non-interactive run exits non-zero.
+3. **Docker unavailable:** if Docker or Compose is missing, or the daemon is stopped, setup exits non-zero with restoration instructions, even when native PostgreSQL is healthy. Both interactive and unattended runs preserve `.env` and never offer a backend switch.
4. **`PGMODE=native`:** first checks whether the configured role can authenticate to the configured database and its base `memories` table exists. A healthy database exits immediately without re-provisioning. Otherwise it runs `scripts/db.sh setup-native` (Homebrew install, role, database, extensions, schema) and verifies readiness again. The port defaults to `:5432` (`PGPORT` overrides it).
5. **Failure is non-zero exit.** A started-but-unresponsive container or a failed native bootstrap exits non-zero with an actionable message — so the `&&`-chained `npm start` halts here instead of crash-looping under PM2 against an unready database.
diff --git a/scripts/lib/setupDbChoice.js b/scripts/lib/setupDbChoice.js
index 6e888677a9..1a8bcaadff 100644
--- a/scripts/lib/setupDbChoice.js
+++ b/scripts/lib/setupDbChoice.js
@@ -1,6 +1,6 @@
/**
* Pure setup-db helpers. setup-db.js is a CLI entrypoint that runs on import,
- * so the menu/port resolvers live here and are imported by both the script and
+ * so the port resolvers live here and are imported by both the script and
* its tests.
*/
@@ -17,8 +17,3 @@ export function parseNativePort(value) {
export function parseDockerPort(value) {
return parsePort(value, 5561);
}
-
-/** Menu choice 2 = native Postgres; anything else (incl. 1 / empty) = docker. */
-export function resolveStorageMenuChoice(answer) {
- return String(answer).trim() === '2' ? 'native' : 'exit';
-}
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 9c93c040b6..e7212e3e9b 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -10,11 +10,10 @@
*/
import { execFileSync } from 'child_process';
-import { createInterface } from 'readline';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { parseEnvFile, upsertEnvKey } from './lib/envFile.js';
-import { parseDockerPort, parseNativePort, resolveStorageMenuChoice } from './lib/setupDbChoice.js';
+import { parseEnvFile } from './lib/envFile.js';
+import { parseDockerPort, parseNativePort } from './lib/setupDbChoice.js';
import { resolveBashBinary } from '../server/lib/bashResolver.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -204,48 +203,6 @@ function getDockerHints(issue) {
return issue === 'not_installed' ? hints.install : hints.start;
}
-// Write PGMODE to .env (create or update)
-function setPgMode(mode) {
- upsertEnvKey(join(rootDir, '.env'), 'PGMODE', mode);
-}
-
-// Prompt user to choose storage mode (TTY only)
-function promptStorageChoice(message, hint) {
- // Non-interactive (stdout/stdin redirected, e.g. `npm start` under PM2): we
- // can't prompt. By the time we reach here, handleDockerUnavailable() has
- // already ruled out a healthy native PostgreSQL, so there is no usable DB and
- // no file fallback anymore — setup genuinely failed. Exit NON-ZERO so the
- // `&&`-chained `npm start` / `npm run setup` halts here instead of launching
- // a server that would immediately fail-fast and crash-loop under PM2.
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
- console.error(`❌ ${message}`);
- console.error(` ${hint}`);
- console.error(' PostgreSQL is required. Start Docker (or set up native PostgreSQL) then run: npm run setup');
- process.exit(1);
- }
-
- return new Promise((resolve) => {
- console.log(`⚠️ ${message}`);
- console.log(` ${hint}`);
- console.log('');
- console.log(' Choose a PostgreSQL hosting mode:');
- console.log('');
- console.log(' 1) Docker PostgreSQL (recommended — containerized, no system install)');
- console.log(' 2) Native PostgreSQL (use system-installed PostgreSQL on port 5432)');
- console.log('');
- // NOTE: File-based JSON storage is intentionally NOT offered here. PostgreSQL
- // is a mandatory dependency (the creative catalog has no file-backed
- // equivalent). `PGMODE=file` survives only as an advanced/unsupported dev
- // escape hatch honored when already present in .env — never a menu choice.
-
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- rl.question(' Enter choice [1/2]: ', (answer) => {
- rl.close();
- resolve(resolveStorageMenuChoice(answer));
- });
- });
-}
-
// Attempt full native PostgreSQL setup via db.sh setup-native. Idempotent:
// db.sh setup-native re-checks each step (brew install, role, db, extensions,
// schema). Verifies success at the *domain* level — the role can auth and the
@@ -284,42 +241,13 @@ function exitNativeSetupFailed() {
process.exit(1);
}
-async function handleDockerUnavailable(message, issue) {
- // Default to native when a healthy local PortOS PostgreSQL is already
- // reachable — no need to prompt or fall back to Docker. The schema-ready
- // probe (role can auth + memories table present) is the proof that a usable
- // native PostgreSQL 17 + pgvector install is in place.
- if (isPortOSDbReady()) {
- console.log(' Healthy native PostgreSQL detected — using native mode.');
- setPgMode('native');
- console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);
- process.exit(0);
- }
-
- const hint = getDockerHints(issue);
- const choice = await promptStorageChoice(message, hint);
-
- if (choice === 'native') {
- console.log(' Switching to native PostgreSQL mode...');
- setPgMode('native');
- // Fast path: portos role can already authenticate to portos db and the
- // schema is in place. Skip setup-native to avoid re-ALTERing credentials
- // and the brew/psql startup-time hit on every `npm start`.
- if (isPortOSDbReady()) {
- console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);
- process.exit(0);
- }
- // Otherwise (fresh checkout, missing role, missing schema, wrong password)
- // run the full bootstrap.
- if (setupNativePostgres()) {
- process.exit(0);
- }
- exitNativeSetupFailed();
- }
-
- // choice === 'exit' — user wants Docker, tell them to install/start it
- console.log(` ${hint}`);
- console.log(' Install/start Docker and re-run setup');
+function handleDockerUnavailable(message, issue) {
+ console.error(`❌ ${message}`);
+ console.error(` ${getDockerHints(issue)}`);
+ console.error(' Restore Docker and re-run: npm run setup:db');
+ console.error(' Keeping the selected database unchanged. Setup never switches backends.');
+ console.error(' For a fresh native install, select PGMODE=native in .env before setup.');
+ console.error(' Existing installs require coordinated maintenance cutover; see docs/STORAGE.md.');
process.exit(1);
}
@@ -357,15 +285,15 @@ if (mode === 'native') {
// Docker mode
if (!hasDocker()) {
- await handleDockerUnavailable('Docker not found — skipping database setup', 'not_installed');
+ handleDockerUnavailable('Docker not found — database setup failed', 'not_installed');
}
if (!isDockerRunning()) {
- await handleDockerUnavailable('Docker daemon not running — skipping database setup', 'not_running');
+ handleDockerUnavailable('Docker daemon not running — database setup failed', 'not_running');
}
if (!hasCompose()) {
- await handleDockerUnavailable('docker compose not available — skipping database setup', 'not_installed');
+ handleDockerUnavailable('docker compose not available — database setup failed', 'not_installed');
}
if (isContainerRunning()) {
@@ -391,8 +319,7 @@ try {
});
} catch (err) {
console.error(`❌ Failed to start PostgreSQL container: ${err.message}`);
- console.error(' PostgreSQL is required — try native mode instead:');
- console.error(' scripts/db.sh set-mode native && npm run setup');
+ console.error(' Keep the selected backend; check Docker and run: docker compose logs db');
process.exit(1);
}
diff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.js
index c042871367..328631d65d 100644
--- a/scripts/setup-db.test.js
+++ b/scripts/setup-db.test.js
@@ -6,7 +6,6 @@ import { fileURLToPath } from 'url';
import {
parseDockerPort,
parseNativePort,
- resolveStorageMenuChoice,
} from './lib/setupDbChoice.js';
const here = dirname(fileURLToPath(import.meta.url));
@@ -23,31 +22,6 @@ describe('Docker PostgreSQL host binding', () => {
});
});
-describe('setup-db menu choice resolver (Phase 1: Postgres mandatory)', () => {
- it('maps "2" to native', () => {
- expect(resolveStorageMenuChoice('2')).toBe('native');
- expect(resolveStorageMenuChoice(' 2 ')).toBe('native');
- });
-
- it('maps "1" (and default/empty) to docker exit', () => {
- expect(resolveStorageMenuChoice('1')).toBe('exit');
- expect(resolveStorageMenuChoice('')).toBe('exit');
- expect(resolveStorageMenuChoice(' ')).toBe('exit');
- });
-
- it('no longer offers file storage as a numbered choice — "3" is not "file"', () => {
- expect(resolveStorageMenuChoice('3')).not.toBe('file');
- expect(resolveStorageMenuChoice('3')).toBe('exit');
- expect(resolveStorageMenuChoice('file')).toBe('exit');
- });
-
- it('setup-db.js prompts [1/2] and never resolves "file"', () => {
- expect(setupDbSrc).toContain('Enter choice [1/2]:');
- expect(setupDbSrc).toContain('resolveStorageMenuChoice');
- expect(setupDbSrc).not.toMatch(/resolve\('file'\)/);
- });
-});
-
describe('setup-db docker-port resolver (success log accuracy)', () => {
it('defaults to 5561 when unset / non-numeric', () => {
expect(parseDockerPort(undefined)).toBe(5561);
@@ -87,3 +61,82 @@ describe('native setup inherited endpoint', () => {
expect(configure({ PGPORT: '5434' }).PGPORT).toBe('5434');
});
});
+
+// Run the actual CLI body with synthetic configuration and subprocesses. No
+// imports execute, no install .env is read, and no database can be contacted.
+async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady = true, running = true } = {}) {
+ const savedEnv = { PGMODE: mode, EXAMPLE_SETTING: 'preserved' };
+ const initialEnv = { ...savedEnv };
+ const calls = [];
+ const errors = [];
+ const exitSignal = {};
+ let exitCode = 0;
+ let provisioned = false;
+ const source = setupDbSrc.replace(/^#!.*\n/, '').replace(/^import .*;\n/gm, '')
+ .replace('import.meta.url', 'scriptUrl');
+ try {
+ await runInNewContext(`(async () => {${source}\n})()`, {
+ scriptUrl: 'file:///example/scripts/setup-db.js', dirname, join, fileURLToPath,
+ parseNativePort, parseDockerPort,
+ parseEnvFile: () => savedEnv,
+ upsertEnvKey: (_path, key, value) => { savedEnv[key] = value; },
+ createInterface: () => { throw new Error('Setup must not prompt to switch backends'); },
+ resolveBashBinary: () => 'bash',
+ process: {
+ env: {}, platform: 'linux', stdin: { isTTY: tty }, stdout: { isTTY: tty },
+ exit: (code) => { exitCode = code; throw exitSignal; }
+ },
+ console: { log: () => {}, error: (message) => errors.push(message) },
+ execFileSync: (command, args) => {
+ calls.push([command, ...args]);
+ const invocation = [command, ...args].join(' ');
+ if (invocation === unavailable) throw new Error('Synthetic unavailable dependency');
+ if (command === 'psql') return nativeReady || provisioned ? '1\n' : '';
+ if (command === 'bash' && args[1] === 'setup-native') {
+ provisioned = true;
+ return '';
+ }
+ if (invocation === 'docker compose ps --format json db') return running ? '{"State":"running"}' : '';
+ if (invocation.startsWith('docker compose exec -T db psql')) return '1\n';
+ if (['docker --version', 'docker info', 'docker compose version',
+ 'docker compose up -d db', 'docker compose exec -T db pg_isready -h 127.0.0.1 -U portos'].includes(invocation)) return '';
+ throw new Error(`Unexpected synthetic subprocess: ${invocation}`);
+ }
+ });
+ } catch (error) {
+ if (error !== exitSignal) throw error;
+ }
+ expect(savedEnv).toEqual(initialEnv);
+ return { exitCode, calls, errors };
+}
+
+describe('setup preserves the selected database', () => {
+ it.each(['docker --version', 'docker info', 'docker compose version'])(
+ 'fails safely when %s is unavailable despite a healthy native database', async (unavailable) => {
+ for (const tty of [false, true]) {
+ const result = await runSetup({ unavailable, tty });
+ expect(result.exitCode).toBe(1);
+ expect(result.calls.every(([command]) => command === 'docker')).toBe(true);
+ expect(result.calls.some((call) => call.includes('up'))).toBe(false);
+ expect(result.errors.join('\n')).toContain('Restore Docker');
+ expect(result.errors.join('\n')).toContain('coordinated maintenance cutover');
+ }
+ }
+ );
+
+ it.each([true, false])('succeeds with selected Docker (container running: %s)', async (running) => {
+ const result = await runSetup({ running });
+ expect(result.exitCode).toBe(0);
+ expect(result.calls.every(([command]) => command === 'docker')).toBe(true);
+ expect(result.calls.some((call) => call.includes('up'))).toBe(!running);
+ expect(result.calls.some((call) => call.includes('pg_isready'))).toBe(true);
+ expect(result.calls.some((call) => call.includes('psql'))).toBe(true);
+ });
+
+ it.each([true, false])('succeeds with explicitly selected native (already ready: %s)', async (nativeReady) => {
+ const result = await runSetup({ mode: 'native', nativeReady });
+ expect(result.exitCode).toBe(0);
+ expect(result.calls.some(([command]) => command === 'docker')).toBe(false);
+ expect(result.calls.some((call) => call.includes('setup-native'))).toBe(!nativeReady);
+ });
+});