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: keep native database bootstrap on the configured endpoint (#9470)

Adam Eivy437c3f6669c1
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 4f1b06cb1f..328e6dbc60 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -302,12 +302,12 @@ The escape hatch is **guarded from bitrot by the test suite** (tests boot with `
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, 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).
+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 endpoint defaults to `localhost:5432` (`PGHOST`/`PGPORT` override it, from the shell or `.env`). Both the provisioning script and the readiness probes use that same selected endpoint: an unavailable selected endpoint fails without sending SQL to any other cluster on the machine.
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.
**Mode selection does not migrate data.** Native and Docker PostgreSQL are separate databases; setup checks schema readiness, not whether one contains your existing records. Keep an existing install pointed at the database holding its data. Back up before an intentional move between modes (see [Backup & Restore](./BACKUP.md)).
-`PGPASSWORD`/`PGUSER`/`PGDATABASE`/`PGPORT` are resolved from `process.env` first, then `.env`, then the backward-compatible defaults (`portos`/`portos`/`portos`/`5432`). The default `portos` password is an **intentional** local-development fallback (see the Distribution model note in [`AGENTS.md`](../AGENTS.md)); production deployments override it via `PGPASSWORD`.
+`PGPASSWORD`/`PGUSER`/`PGDATABASE`/`PGHOST`/`PGPORT` are resolved from `process.env` first, then `.env`, then the backward-compatible defaults (`portos`/`portos`/`portos`/`5432`). The default `portos` password is an **intentional** local-development fallback (see the Distribution model note in [`AGENTS.md`](../AGENTS.md)); production deployments override it via `PGPASSWORD`.
### Moving between Docker and native
diff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.js
index 3d2045a67b..70e9ee7234 100644
--- a/scripts/db-migrate.test.js
+++ b/scripts/db-migrate.test.js
@@ -56,6 +56,17 @@ case "$DUMP_MODE" in
esac
`;
+// Logs each probe; READY_PORTS (space-separated) limits which ports answer, so a
+// test can stand up "another cluster on the default port" without a real server.
+const PG_ISREADY_STUB = `#!/bin/sh
+echo "pg_isready $*" >> "$STUB_LOG"
+port=""; prev=""
+for arg in "$@"; do [ "$prev" = "-p" ] && port="$arg"; prev="$arg"; done
+[ -z "\${READY_PORTS:-}" ] && exit 0
+case " $READY_PORTS " in *" $port "*) exit 0 ;; esac
+exit 1
+`;
+
function writeStub(binDir, name, body) {
const path = join(binDir, name);
writeFileSync(path, body);
@@ -78,7 +89,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
writeStub(binDir, 'docker', DOCKER_STUB);
writeStub(binDir, 'psql', PSQL_STUB);
writeStub(binDir, 'pg_dump', PG_DUMP_STUB);
- writeStub(binDir, 'pg_isready', '#!/bin/sh\nexit 0\n');
+ writeStub(binDir, 'pg_isready', PG_ISREADY_STUB);
// Not Darwin, so db.sh skips prepending Homebrew's real Postgres to PATH.
writeStub(binDir, 'uname', '#!/bin/sh\necho Linux\n');
writeStub(binDir, 'whoami', '#!/bin/sh\necho example_user\n');
@@ -252,4 +263,32 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
expect(log).not.toMatch(/SOURCE_STOP|docker compose stop/);
expect(result.stdout).toContain('selected mode is unchanged');
});
+
+ const psqlCalls = () => readFileSync(stubLog, 'utf8').split('\n').filter(line => line.startsWith('psql '));
+
+ it('provisions only the selected non-default endpoint while another cluster listens on the default port', () => {
+ const result = run(['setup-native'], 'ok', { PGPORT: '5433', PGHOST: 'db.example.invalid', READY_PORTS: '5432 5433' });
+ expect(result.status).toBe(0);
+ const calls = psqlCalls();
+ // role lookup, role alter, db list, two extensions, schema apply
+ expect(calls.length).toBeGreaterThanOrEqual(6);
+ for (const call of calls) expect(call).toContain('-h db.example.invalid -p 5433 ');
+ expect(calls.some(call => call.includes('--single-transaction'))).toBe(true);
+ expect(readFileSync(stubLog, 'utf8')).not.toMatch(/-p 5432\b/);
+ });
+
+ it('initializes a running non-default endpoint without any server on the default port', () => {
+ const result = run(['setup-native'], 'ok', { PGPORT: '5433', READY_PORTS: '5433' });
+ expect(result.status).toBe(0);
+ expect(psqlCalls().length).toBeGreaterThanOrEqual(6);
+ expect(psqlCalls().every(call => call.includes('-p 5433 '))).toBe(true);
+ });
+
+ it('fails without issuing SQL to another cluster when the selected endpoint is down', () => {
+ const result = run(['setup-native'], 'ok', { PGPORT: '5433', READY_PORTS: '5432' });
+ expect(result.status).not.toBe(0);
+ expect(result.stderr + result.stdout).toContain('127.0.0.1:5433');
+ expect(psqlCalls()).toEqual([]);
+ expect(readFileSync(envFile, 'utf8')).toBe('PGMODE=docker\n');
+ });
});
diff --git a/scripts/db.sh b/scripts/db.sh
index 087cc6567f..d4f06e6312 100755
--- a/scripts/db.sh
+++ b/scripts/db.sh
@@ -15,6 +15,7 @@
# stop Stop the database
# fix Fix common issues (stale pid files, etc.)
# setup-native Install and configure native PostgreSQL via Homebrew
+# (provisions the PGHOST/PGPORT you select; never another cluster)
# use-docker Unavailable pending coordinated offline cutover
# use-native Unavailable pending coordinated offline cutover
# migrate Unavailable pending coordinated offline cutover
@@ -69,6 +70,9 @@ get_port() {
fi
}
+# Whether the caller named a port. setup-native provisions exactly that
+# endpoint; only an unnamed port falls back to local service discovery.
+SELECTED_PGPORT="${PGPORT:-}"
PGPORT=$(get_port)
EXPLICIT_ENDPOINT=false
@@ -462,29 +466,50 @@ cmd_setup_native() {
fi
fi
- # Step 2: Ensure PostgreSQL is running
- local pg_port=""
- if pg_port=$(detect_system_pg); then
- log "System PostgreSQL already running on port $pg_port"
- else
- info "Starting PostgreSQL..."
- if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ # Step 2: Ensure PostgreSQL is running. A caller-selected endpoint
+ # (PGHOST/PGPORT) is provisioned as-is: discovery must never redirect SQL
+ # (role/password changes, schema) to a different cluster than the one chosen.
+ if [ -n "$SELECTED_PGPORT" ]; then
+ PGPORT="$SELECTED_PGPORT"
+ if pg_isready -h "$PGHOST" -p "$PGPORT" >/dev/null 2>&1; then
+ log "PostgreSQL already running at $PGHOST:$PGPORT"
+ elif [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ info "Starting PostgreSQL..."
brew services start postgresql@17
sleep 2
- if pg_port=$(detect_system_pg); then
- log "PostgreSQL started on port $pg_port"
+ if pg_isready -h "$PGHOST" -p "$PGPORT" >/dev/null 2>&1; then
+ log "PostgreSQL started at $PGHOST:$PGPORT"
else
- err "PostgreSQL failed to start. Check: brew services list"
+ err "PostgreSQL is not accepting connections at $PGHOST:$PGPORT. Start the selected cluster and try again."
exit 1
fi
else
- err "PostgreSQL is not running. Start it and try again."
+ err "PostgreSQL is not running at $PGHOST:$PGPORT. Start the selected cluster and try again."
exit 1
fi
+ else
+ local pg_port=""
+ if pg_port=$(detect_system_pg); then
+ log "System PostgreSQL already running on port $pg_port"
+ else
+ info "Starting PostgreSQL..."
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ brew services start postgresql@17
+ sleep 2
+ if pg_port=$(detect_system_pg); then
+ log "PostgreSQL started on port $pg_port"
+ else
+ err "PostgreSQL failed to start. Check: brew services list"
+ exit 1
+ fi
+ else
+ err "PostgreSQL is not running. Start it and try again."
+ exit 1
+ fi
+ fi
+ PGPORT="$pg_port"
fi
- PGPORT="$pg_port"
-
# Step 3: Create portos user if it doesn't exist
# Connect as the current system user (default Homebrew superuser) to create the role
local sys_user
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index e7212e3e9b..e38b912634 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -27,6 +27,9 @@ const envVar = (key, fallback) => process.env[key] ?? envFile[key] ?? fallback;
const PG_USER = envVar('PGUSER', 'portos');
const PG_DATABASE = envVar('PGDATABASE', 'portos');
const PG_PASSWORD = envVar('PGPASSWORD', 'portos');
+// Same env > .env > default rule as PM2 (ecosystem.config.cjs), so a PGHOST set
+// only in .env reaches both db.sh and the readiness probes.
+const PG_HOST = envVar('PGHOST', 'localhost');
// A managed parent exports PGPORT for its active pool (possibly Docker), and
// preserves the native identity separately. Ordinary shells keep legacy PGPORT.
const PG_PORT_NATIVE = parseNativePort(process.env.PORTOS_NATIVE_PGPORT || envVar('PGPORT', 5432));
@@ -46,6 +49,7 @@ const PG_CHILD_ENV = {
PGUSER: PG_USER,
PGDATABASE: PG_DATABASE,
PGPASSWORD: PG_PASSWORD,
+ PGHOST: PG_HOST,
PGPORT: String(PG_PORT_NATIVE)
};
@@ -115,7 +119,7 @@ function isPortOSDbReady(port = PG_PORT_NATIVE) {
'psql',
[
'-X',
- '-h', 'localhost',
+ '-h', PG_HOST,
'-p', String(port),
'-U', PG_USER,
'-d', PG_DATABASE,
diff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.js
index 5e1d613ff7..8ce3f8adf5 100644
--- a/scripts/setup-db.test.js
+++ b/scripts/setup-db.test.js
@@ -64,10 +64,11 @@ describe('native setup inherited endpoint', () => {
// 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' };
+async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady = true, running = true, dotEnv = {} } = {}) {
+ const savedEnv = { PGMODE: mode, EXAMPLE_SETTING: 'preserved', ...dotEnv };
const initialEnv = { ...savedEnv };
const calls = [];
+ const childEnvs = [];
const errors = [];
const exitSignal = {};
let exitCode = 0;
@@ -87,8 +88,9 @@ async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady
exit: (code) => { exitCode = code; throw exitSignal; }
},
console: { log: () => {}, error: (message) => errors.push(message) },
- execFileSync: (command, args) => {
+ execFileSync: (command, args, options) => {
calls.push([command, ...args]);
+ childEnvs.push(options?.env);
const invocation = [command, ...args].join(' ');
if (invocation === unavailable) throw new Error('Synthetic unavailable dependency');
if (command === 'psql') return nativeReady || provisioned ? '1\n' : '';
@@ -107,7 +109,7 @@ async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady
if (error !== exitSignal) throw error;
}
expect(savedEnv).toEqual(initialEnv);
- return { exitCode, calls, errors };
+ return { exitCode, calls, childEnvs, errors };
}
describe('setup preserves the selected database', () => {
@@ -139,4 +141,20 @@ describe('setup preserves the selected database', () => {
expect(result.calls.some(([command]) => command === 'docker')).toBe(false);
expect(result.calls.some((call) => call.includes('setup-native'))).toBe(!nativeReady);
});
+
+ it('probes and provisions the endpoint selected in .env, host and port alike', async () => {
+ const result = await runSetup({
+ mode: 'native', nativeReady: false,
+ dotEnv: { PGHOST: 'db.example.invalid', PGPORT: '5433' },
+ });
+ expect(result.exitCode).toBe(0);
+ const probes = result.calls.filter(([command]) => command === 'psql');
+ expect(probes).toHaveLength(2);
+ for (const probe of probes) {
+ expect(probe.slice(probe.indexOf('-h'), probe.indexOf('-h') + 4))
+ .toEqual(['-h', 'db.example.invalid', '-p', '5433']);
+ }
+ const setupIndex = result.calls.findIndex((call) => call.includes('setup-native'));
+ expect(result.childEnvs[setupIndex]).toMatchObject({ PGHOST: 'db.example.invalid', PGPORT: '5433' });
+ });
});