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: forward .env PostgreSQL settings to PM2-managed processes (#8447)

[._.]/ Adam Eivyd6578774db34
diff --git a/docker-compose.yml b/docker-compose.yml
index a4172332ce..12211ac1cf 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -14,14 +14,18 @@ services:
ports:
- "127.0.0.1:${PGPORT_DOCKER:-5561}:5432"
environment:
- POSTGRES_DB: portos
- POSTGRES_USER: portos
+ POSTGRES_DB: ${PGDATABASE:-portos}
+ POSTGRES_USER: ${PGUSER:-portos}
POSTGRES_PASSWORD: ${PGPASSWORD:-portos}
volumes:
- portos-pgdata:/var/lib/postgresql/data
- ./server/scripts/init-db.sql:/docker-entrypoint-initdb.d/01-init.sql
healthcheck:
- test: ["CMD-SHELL", "pg_isready -U portos"]
+ # $$ escapes Compose's own ${...} interpolation so the shell inside the
+ # container substitutes it from POSTGRES_USER (set above, in the
+ # container's own env) instead — keeping the probe's user in sync with
+ # whatever POSTGRES_USER actually provisioned.
+ test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-portos}"]
interval: 5s
timeout: 3s
retries: 5
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index cc2675175f..3d3bea9e21 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -13,19 +13,43 @@ const BASE_ENV = {
// Read a couple of machine-local settings from .env (pm2 doesn't auto-load it
// here): PGMODE → PostgreSQL port; PORTOS_SERVER_MAX_MEMORY → the server restart
-// ceiling below. An explicit process.env wins over the .env file so a one-off
-// shell override still works.
+// ceiling below; PGPASSWORD/PGUSER/PGDATABASE/PGHOST/PGPORT/PGPORT_DOCKER → the
+// same DB connection settings scripts/setup-db.js already reads from .env, so a
+// value set only in .env (not exported into the shell) still reaches the
+// running server instead of silently falling back to the `portos` defaults
+// while setup provisioned something else (#8447). An explicit process.env wins
+// over the .env file so a one-off shell override still works.
const fs = require('fs');
const envFile = path.join(__dirname, '.env');
const readEnvValue = (content, key) => content.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? null;
let pgMode = 'docker';
let envServerMaxMemory = null;
+let envPgPassword = null;
+let envPgUser = null;
+let envPgDatabase = null;
+let envPgHost = null;
+let envPgPort = null;
+let envPgPortDocker = null;
try {
const envContent = fs.readFileSync(envFile, 'utf8');
pgMode = readEnvValue(envContent, 'PGMODE') || pgMode;
envServerMaxMemory = readEnvValue(envContent, 'PORTOS_SERVER_MAX_MEMORY');
+ envPgPassword = readEnvValue(envContent, 'PGPASSWORD');
+ envPgUser = readEnvValue(envContent, 'PGUSER');
+ envPgDatabase = readEnvValue(envContent, 'PGDATABASE');
+ envPgHost = readEnvValue(envContent, 'PGHOST');
+ envPgPort = readEnvValue(envContent, 'PGPORT');
+ envPgPortDocker = readEnvValue(envContent, 'PGPORT_DOCKER');
} catch { /* no .env file — default to docker */ }
+// Same precedence as scripts/setup-db.js: process.env → .env → default. Keep the
+// 'portos' password fallback (AGENTS.md: intentional backward-compatible
+// default) — this only changes WHERE a user-set value can come from.
+const PG_USER = process.env.PGUSER || envPgUser || 'portos';
+const PG_DATABASE = process.env.PGDATABASE || envPgDatabase || 'portos';
+const PG_PASSWORD = process.env.PGPASSWORD || envPgPassword || 'portos';
+const PG_HOST = process.env.PGHOST || envPgHost || 'localhost';
+
// pm2 restarts portos-server when its RSS crosses this — originally a memory-leak
// safety valve. The committed default stays modest so the guard still fires on a
// small install (a fork on an 8 GB box), but it's overridable per-machine via
@@ -136,6 +160,14 @@ const PORTS = {
POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)
};
+// The override var differs per mode (native dials PGPORT, Docker dials the host
+// 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.
+const PG_PORT = Number(
+ (pgMode === 'native' ? (process.env.PGPORT || envPgPort) : (process.env.PGPORT_DOCKER || envPgPortDocker)) || PORTS.POSTGRES
+);
+
module.exports = {
PORTS, // Export for other configs to reference
@@ -169,8 +201,11 @@ module.exports = {
PORT: PORTS.API,
PORTOS_HTTP_PORT: PORTS.API_LOCAL, // Loopback HTTP mirror when HTTPS is active
HOST: '0.0.0.0',
- PGPORT: PORTS.POSTGRES,
- PGPASSWORD: process.env.PGPASSWORD || 'portos',
+ PGHOST: PG_HOST,
+ PGPORT: PG_PORT,
+ PGUSER: PG_USER,
+ PGDATABASE: PG_DATABASE,
+ PGPASSWORD: PG_PASSWORD,
...(pgMode === 'file' ? { MEMORY_BACKEND: 'file' } : {}),
PATH: process.env.PATH // Inherit PATH for git/node access in child processes
},
@@ -228,7 +263,15 @@ module.exports = {
env: {
...BASE_ENV,
PORT: PORTS.COS,
- HOST: '127.0.0.1'
+ HOST: '127.0.0.1',
+ // CoS agents shell out to db.sh / backup.js for DB admin and backup
+ // work — give them the same connection settings as portos-server so
+ // they agree with what setup actually provisioned (#8447).
+ PGHOST: PG_HOST,
+ PGPORT: PG_PORT,
+ PGUSER: PG_USER,
+ PGDATABASE: PG_DATABASE,
+ PGPASSWORD: PG_PASSWORD
},
watch: false,
autorestart: true,
diff --git a/scripts/ecosystemEnv.test.js b/scripts/ecosystemEnv.test.js
new file mode 100644
index 0000000000..ff3e238477
--- /dev/null
+++ b/scripts/ecosystemEnv.test.js
@@ -0,0 +1,126 @@
+/**
+ * Pins PM2's PostgreSQL connection env against a temporary `.env` (#8447).
+ *
+ * Setup (`scripts/setup-db.js`) already resolves PGUSER/PGDATABASE/PGPASSWORD/
+ * PGPORT/PGPORT_DOCKER via `process.env → .env → default`, but `ecosystem.config.cjs`
+ * only ever read PGMODE and PORTOS_SERVER_MAX_MEMORY out of `.env` — every other
+ * PG setting fell back straight to its hardcoded default, so a password set only
+ * in `.env` (not exported into the shell) never reached `portos-server`. This
+ * test loads the real ecosystem config against a controlled `.env` (never the
+ * repo's own, which may hold real machine-local values) and pins the resolved
+ * env for `portos-server` and `portos-cos`.
+ *
+ * The config reads its `.env` from `path.join(__dirname, '.env')`, so each case
+ * copies the real `ecosystem.config.cjs` source into a fresh temp directory next
+ * to a synthetic `.env`, then `require()`s the copy — never the checked-out one.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { createRequire } from 'module';
+import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const require = createRequire(import.meta.url);
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const CONFIG_SOURCE = readFileSync(join(REPO_ROOT, 'ecosystem.config.cjs'), 'utf8');
+
+let tmpDirs = [];
+
+afterEach(() => {
+ for (const dir of tmpDirs) {
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
+ tmpDirs = [];
+});
+
+/**
+ * Load a fresh copy of ecosystem.config.cjs against a synthetic `.env`
+ * (`envContent`, or none), with `overrideEnv` merged into `process.env` for the
+ * duration of the load only.
+ */
+function loadConfig(envContent, overrideEnv = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-ecosystem-env-'));
+ tmpDirs.push(dir);
+ const configPath = join(dir, 'ecosystem.config.cjs');
+ writeFileSync(configPath, CONFIG_SOURCE);
+ if (envContent !== null) writeFileSync(join(dir, '.env'), envContent);
+
+ const savedEnv = {};
+ for (const key of Object.keys(overrideEnv)) {
+ savedEnv[key] = process.env[key];
+ if (overrideEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = overrideEnv[key];
+ }
+ try {
+ delete require.cache[configPath];
+ return require(configPath);
+ } finally {
+ for (const key of Object.keys(savedEnv)) {
+ if (savedEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = savedEnv[key];
+ }
+ }
+}
+
+// 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 clearedPgEnv = Object.fromEntries(PG_KEYS.map((k) => [k, undefined]));
+
+describe('ecosystem.config.cjs PostgreSQL env', () => {
+ it('picks up a PGPASSWORD set only in .env (not exported to the shell)', () => {
+ const { apps } = loadConfig('PGPASSWORD=example-secret\n', clearedPgEnv);
+ const server = apps.find((a) => a.name === 'portos-server');
+ const cos = apps.find((a) => a.name === 'portos-cos');
+ expect(server.env.PGPASSWORD).toBe('example-secret');
+ expect(cos.env.PGPASSWORD).toBe('example-secret');
+ });
+
+ it('lets an exported PGPASSWORD win over .env', () => {
+ const { apps } = loadConfig('PGPASSWORD=from-dotenv\n', { ...clearedPgEnv, PGPASSWORD: 'from-shell' });
+ const server = apps.find((a) => a.name === 'portos-server');
+ expect(server.env.PGPASSWORD).toBe('from-shell');
+ });
+
+ it('resolves the Docker host port from PGPORT_DOCKER in .env under PGMODE=docker', () => {
+ const { apps } = loadConfig('PGMODE=docker\nPGPORT_DOCKER=5570\n', clearedPgEnv);
+ const server = apps.find((a) => a.name === 'portos-server');
+ expect(server.env.PGPORT).toBe(5570);
+ });
+
+ it('resolves the native port from PGPORT in .env under PGMODE=native', () => {
+ const { apps } = loadConfig('PGMODE=native\nPGPORT=5433\n', clearedPgEnv);
+ const server = apps.find((a) => a.name === 'portos-server');
+ expect(server.env.PGPORT).toBe(5433);
+ });
+
+ it('falls back to the per-mode default port when neither override is set', () => {
+ const docker = loadConfig('PGMODE=docker\n', clearedPgEnv);
+ const native = loadConfig('PGMODE=native\n', clearedPgEnv);
+ expect(docker.apps.find((a) => a.name === 'portos-server').env.PGPORT).toBe(5561);
+ expect(native.apps.find((a) => a.name === 'portos-server').env.PGPORT).toBe(5432);
+ });
+
+ 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');
+ expect(server.env.PGUSER).toBe('example-user');
+ expect(server.env.PGDATABASE).toBe('example-db');
+
+ const defaults = loadConfig(null, clearedPgEnv);
+ const defaultServer = defaults.apps.find((a) => a.name === 'portos-server');
+ expect(defaultServer.env.PGUSER).toBe('portos');
+ expect(defaultServer.env.PGDATABASE).toBe('portos');
+ expect(defaultServer.env.PGPASSWORD).toBe('portos');
+ });
+
+ it('keeps PGPASSWORD out of the non-DB apps (portos-ui, autofixer, browser)', () => {
+ const { apps } = loadConfig('PGPASSWORD=example-secret\n', clearedPgEnv);
+ for (const name of ['portos-ui', 'portos-autofixer', 'portos-autofixer-ui', 'portos-browser']) {
+ const app = apps.find((a) => a.name === name);
+ expect(app, `expected an app named ${name}`).toBeTruthy();
+ expect(app.env.PGPASSWORD).toBeUndefined();
+ }
+ });
+});
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 135c00414e..e3186ecaf9 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -145,7 +145,7 @@ function isDockerSchemaReady() {
try {
const output = execFileSync(
'docker',
- ['compose', 'exec', '-T', 'db', 'psql', '-X', '-U', 'portos', '-d', 'portos', '-tAc',
+ ['compose', 'exec', '-T', 'db', 'psql', '-X', '-U', PG_USER, '-d', PG_DATABASE, '-tAc',
"SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'memories' LIMIT 1"],
{ stdio: 'pipe', cwd: rootDir }
).toString();
@@ -168,7 +168,7 @@ function isDockerSchemaReady() {
function waitForHealth(maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
try {
- execFileSync('docker', ['compose', 'exec', '-T', 'db', 'pg_isready', '-h', '127.0.0.1', '-U', 'portos'], {
+ execFileSync('docker', ['compose', 'exec', '-T', 'db', 'pg_isready', '-h', '127.0.0.1', '-U', PG_USER], {
stdio: 'pipe',
cwd: rootDir
});