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 database endpoints across managed process inheritance (#8815)

[._.]/ Adam Eivy5fb24b150f7f
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 06867a2349..20df96d64c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -96,6 +96,21 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
---
+### Database endpoints in managed processes
+
+The ecosystem resolves native `PGPORT` and Docker `PGPORT_DOCKER` from the
+launching environment, then `.env`, then their defaults. It passes `PGPORT`
+to the server and CoS runner as the **active pool port**. It also passes the
+resolved native port as internal `PORTOS_NATIVE_PGPORT` and the resolved Docker
+port as `PGPORT_DOCKER`. Child maintenance/configuration processes preserve
+those backend identities when reloading the ecosystem or preparing native
+setup, even when the parent's active pool is Docker. Do not put the internal
+variable in `.env`; configure the native port with `PGPORT` in the ordinary
+launching shell or `.env`. Inherited endpoint identity takes precedence over
+a later file edit: restart from the intended launch environment to apply changed
+connection settings. A coordinator must still compare saved configuration,
+recorded endpoints, and the running pool before cutover.
+
### Database maintenance journal
`data/database-maintenance/operation.json` is `file-primary`, machine-local recovery state: it must be readable before PostgreSQL, including while either backend is unavailable. Its enclosing directory is the admission fence. The versioned record contains an operation UUID, accepted stage, timestamp, and explicit source/target connection identities; it contains no password, token, or application records. It is never federated and has no reference seed. Missing state is idle; an incomplete, malformed, unreadable, or newer-version operation stays fenced. No install migration is needed for an initially absent operation.
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 2780785a06..3a5531966f 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -164,13 +164,17 @@ const PORTS = {
// mapping PGPORT_DOCKER — see docker-compose.yml), so resolve whichever one
// applies to the active pgMode; PORTS.POSTGRES (above) is already the correct
// per-mode default when neither is set.
+// PGPORT becomes the ACTIVE port in each managed process below. Preserve the
+// original native port separately so a child reloading this config cannot
+// reinterpret an inherited Docker PGPORT as the native endpoint (#8815).
+// PORTOS_NATIVE_PGPORT is internal inherited identity, not a .env setting.
// Expose the exact, credential-free endpoint identities to offline maintenance
// tools. Both modes must use the same precedence as managed-process startup.
const databaseEndpoint = (mode, port) => ({
mode, host: PG_HOST, port: Number(port), database: PG_DATABASE, user: PG_USER
});
const DATABASE_ENDPOINTS = {
- native: databaseEndpoint('native', process.env.PGPORT || envPgPort || 5432),
+ native: databaseEndpoint('native', process.env.PORTOS_NATIVE_PGPORT || process.env.PGPORT || envPgPort || 5432),
docker: databaseEndpoint('docker', process.env.PGPORT_DOCKER || envPgPortDocker || PORTS.POSTGRES_DOCKER)
};
const PG_PORT = DATABASE_ENDPOINTS[pgMode === 'native' ? 'native' : 'docker'].port;
@@ -212,6 +216,8 @@ module.exports = {
HOST: '0.0.0.0',
PGHOST: PG_HOST,
PGPORT: PG_PORT,
+ PORTOS_NATIVE_PGPORT: DATABASE_ENDPOINTS.native.port,
+ PGPORT_DOCKER: DATABASE_ENDPOINTS.docker.port,
PGUSER: PG_USER,
PGDATABASE: PG_DATABASE,
PGPASSWORD: PG_PASSWORD,
@@ -285,6 +291,8 @@ module.exports = {
// they agree with what setup actually provisioned (#8447).
PGHOST: PG_HOST,
PGPORT: PG_PORT,
+ PORTOS_NATIVE_PGPORT: DATABASE_ENDPOINTS.native.port,
+ PGPORT_DOCKER: DATABASE_ENDPOINTS.docker.port,
PGUSER: PG_USER,
PGDATABASE: PG_DATABASE,
PGPASSWORD: PG_PASSWORD
diff --git a/scripts/ecosystemEnv.test.js b/scripts/ecosystemEnv.test.js
index ff3e238477..3653c2df17 100644
--- a/scripts/ecosystemEnv.test.js
+++ b/scripts/ecosystemEnv.test.js
@@ -65,7 +65,7 @@ function loadConfig(envContent, overrideEnv = {}) {
// Clear any real PG* vars the host shell/CI runner might have exported, so
// the "neither set" cases actually exercise the default branch.
-const PG_KEYS = ['PGPASSWORD', 'PGUSER', 'PGDATABASE', 'PGHOST', 'PGPORT', 'PGPORT_DOCKER', 'PGMODE'];
+const PG_KEYS = ['PGPASSWORD', 'PGUSER', 'PGDATABASE', 'PGHOST', 'PGPORT', 'PGPORT_DOCKER', 'PGMODE', 'PORTOS_NATIVE_PGPORT'];
const clearedPgEnv = Object.fromEntries(PG_KEYS.map((k) => [k, undefined]));
describe('ecosystem.config.cjs PostgreSQL env', () => {
@@ -102,6 +102,23 @@ describe('ecosystem.config.cjs PostgreSQL env', () => {
expect(native.apps.find((a) => a.name === 'portos-server').env.PGPORT).toBe(5432);
});
+ it.each(['portos-server', 'portos-cos'])('preserves both endpoints when reloaded from %s across a mode change', (name) => {
+ const saved = 'PGMODE=docker\nPGPORT=5433\nPGPORT_DOCKER=5570\n';
+ const initial = loadConfig(saved, clearedPgEnv);
+ const inherited = { ...clearedPgEnv, ...initial.apps.find(app => app.name === name).env };
+ expect(inherited.PGPORT).toBe(5570);
+ const reloaded = loadConfig(saved, inherited);
+ expect(reloaded.DATABASE_ENDPOINTS).toEqual(initial.DATABASE_ENDPOINTS);
+ const switched = loadConfig(saved.replace('docker', 'native'), inherited);
+ expect(switched.DATABASE_ENDPOINTS).toEqual(initial.DATABASE_ENDPOINTS);
+ expect(switched.apps.find(app => app.name === name).env.PGPORT).toBe(5433);
+ const returned = loadConfig(saved, {
+ ...clearedPgEnv, ...switched.apps.find(app => app.name === name).env,
+ });
+ expect(returned.DATABASE_ENDPOINTS).toEqual(initial.DATABASE_ENDPOINTS);
+ expect(returned.apps.find(app => app.name === name).env.PGPORT).toBe(5570);
+ });
+
it('forwards PGUSER/PGDATABASE from .env to portos-server, keeping the portos default otherwise', () => {
const { apps } = loadConfig('PGUSER=example-user\nPGDATABASE=example-db\n', clearedPgEnv);
const server = apps.find((a) => a.name === 'portos-server');
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index e3186ecaf9..9c93c040b6 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -28,7 +28,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');
-const PG_PORT_NATIVE = parseNativePort(envVar('PGPORT', 5432));
+// 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));
// Docker host-port mapping (docker-compose.yml maps `${PGPORT_DOCKER:-5561}:5432`).
// Resolve it the same tolerant way so the "ready on port N" log can't lie when a
// user overrides PGPORT_DOCKER — a misleading success port is exactly the kind of
diff --git a/scripts/setup-db.test.js b/scripts/setup-db.test.js
index d162e92f75..c042871367 100644
--- a/scripts/setup-db.test.js
+++ b/scripts/setup-db.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
+import { runInNewContext } from 'node:vm';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import {
@@ -69,3 +70,20 @@ describe('setup-db docker-port resolver (success log accuracy)', () => {
expect(setupDbSrc).not.toContain("'✅ PostgreSQL ready on port 5561'");
});
});
+
+describe('native setup inherited endpoint', () => {
+ it('builds native subprocess settings from native identity, not the active Docker port', () => {
+ // Execute the real setup configuration boundary without starting its menu,
+ // probing PostgreSQL, or loading the install's .env.
+ const start = setupDbSrc.indexOf('const envVar =');
+ const end = setupDbSrc.indexOf('function getMode()');
+ expect(start).toBeGreaterThan(0);
+ expect(end).toBeGreaterThan(start);
+ const configure = (env) => runInNewContext(
+ setupDbSrc.slice(start, end) + '\nPG_CHILD_ENV',
+ { process: { env }, envFile: {}, parseNativePort, parseDockerPort },
+ );
+ expect(configure({ PGPORT: '5570', PORTOS_NATIVE_PGPORT: '5433' }).PGPORT).toBe('5433');
+ expect(configure({ PGPORT: '5434' }).PGPORT).toBe('5434');
+ });
+});
diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.js
index 9afdf1323b..cd6a7e6109 100644
--- a/server/lib/databaseMaintenanceJournal.test.js
+++ b/server/lib/databaseMaintenanceJournal.test.js
@@ -173,7 +173,7 @@ describe('persistent database maintenance boundary', () => {
const run = (...args) => spawnSync(process.execPath, [fileURLToPath(cli), ...args], {
encoding: 'utf8', timeout: 10_000,
env: { ...childEnv, PORTOS_DATA_ROOT: root, PGPORT: '', PGPORT_DOCKER: '',
- PGHOST: 'localhost', PGUSER: 'example', PGDATABASE: 'example_test', PGPASSWORD: 'example-only', ...overrides },
+ PORTOS_NATIVE_PGPORT: '', PGHOST: 'localhost', PGUSER: 'example', PGDATABASE: 'example_test', PGPASSWORD: 'example-only', ...overrides },
});
expect(JSON.parse(run('status').stdout)).toEqual({ stage: 'idle' });
expect(run('begin', 'docker', 'native').status).toBe(1);
@@ -205,6 +205,27 @@ describe('persistent database maintenance boundary', () => {
expect(run('cancel', overrideId).status).toBe(0);
});
+ it('keeps maintenance direction when invoked by a Docker-managed process', () => {
+ copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));
+ writeFileSync(join(root, '.env'), 'PGMODE=docker\nPGPORT=6543\nPGPORT_DOCKER=6544\n');
+ const cli = fileURLToPath(new URL('../../scripts/database-maintenance.mjs', import.meta.url));
+ const env = { ...childEnv, PORTOS_DATA_ROOT: root, PGPORT: '6544',
+ PORTOS_NATIVE_PGPORT: '6543', PGPORT_DOCKER: '6544',
+ PGHOST: 'localhost', PGUSER: 'example', PGDATABASE: 'example_test', PGPASSWORD: 'example-only' };
+ const run = (...args) => spawnSync(process.execPath, [cli, ...args], {
+ env, encoding: 'utf8', timeout: 10_000,
+ });
+ const result = run('begin', 'docker', 'native');
+ expect(result.status, result.stderr).toBe(0);
+ const operation = JSON.parse(result.stdout);
+ expect(journal.read()).toMatchObject({
+ source: { mode: 'docker', port: 6544 }, target: { mode: 'native', port: 6543 },
+ });
+ expect(JSON.parse(run('status').stdout)).toEqual(operation);
+ expect(run('begin', 'native', 'docker').status).toBe(1);
+ expect(run('cancel', operation.id).status).toBe(0);
+ });
+
it.skipIf(process.platform === 'win32')('never releases a symlinked active directory or journal', () => {
const operation = journal.begin({ source, target });
const active = join(data, 'database-maintenance');