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: apply Docker database configuration before reporting readiness (#9469)

[._.]/ Adam Eivy41c023d72fc4
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 328e6dbc60..f6295319c1 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -300,7 +300,7 @@ 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.** 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).
+2. **`PGMODE=docker` (default):** reconciles the current `docker-compose.yml` service configuration with `docker compose up -d db` before accepting even an already-running `pgvector/pgvector:pg17` container. Compose applies changed loopback bindings and `PGPORT_DOCKER` mappings while preserving the named data volume, and reuses unchanged containers. Setup 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 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.
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index e38b912634..02891ed146 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -87,19 +87,6 @@ function hasCompose() {
}
}
-// Check if the container is already running
-function isContainerRunning() {
- try {
- const output = execFileSync('docker', ['compose', 'ps', '--format', 'json', 'db'], {
- stdio: 'pipe',
- cwd: rootDir
- }).toString();
- return output.includes('"running"') || output.includes('"Running"');
- } catch {
- return false;
- }
-}
-
// Domain-level readiness check: the configured PG_USER role can authenticate
// to PG_DATABASE AND the `memories` table from init-db.sql exists in the
// public schema. This is what `db.sh setup-native` produces. The probe
@@ -300,29 +287,17 @@ if (!hasCompose()) {
handleDockerUnavailable('docker compose not available — database setup failed', 'not_installed');
}
-if (isContainerRunning()) {
- // "running" is the container state, not DB readiness — Postgres inside it may
- // still be initializing. Now that PG is mandatory and boot fail-fasts, confirm
- // it actually accepts connections before reporting success, or `npm start`
- // proceeds into PM2 against a not-yet-ready DB and crash-loops.
- if (waitForHealth()) {
- console.log('✅ PostgreSQL already running');
- process.exit(0);
- }
- console.error('❌ PostgreSQL container is running but not accepting connections');
- console.error(' Check status: docker compose logs db');
- process.exit(1);
-}
-
-// Start the container
-console.log('🐳 Starting PostgreSQL container...');
+// Compose reconciles changed bindings/ports for existing containers while
+// preserving the named data volume, and reuses unchanged running containers.
+// Readiness inside a container cannot prove its host publication is current.
+console.log('🐳 Reconciling PostgreSQL container configuration...');
try {
execFileSync('docker', ['compose', 'up', '-d', 'db'], {
stdio: 'inherit',
cwd: rootDir
});
} catch (err) {
- console.error(`❌ Failed to start PostgreSQL container: ${err.message}`);
+ console.error(`❌ Failed to reconcile PostgreSQL container: ${err.message}`);
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 8ce3f8adf5..12f0ded323 100644
--- a/scripts/setup-db.test.js
+++ b/scripts/setup-db.test.js
@@ -64,13 +64,17 @@ 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, dotEnv = {} } = {}) {
+async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady = true, running = true, hostBinding = '127.0.0.1', hostPort = 5561, dotEnv = {} } = {}) {
const savedEnv = { PGMODE: mode, EXAMPLE_SETTING: 'preserved', ...dotEnv };
const initialEnv = { ...savedEnv };
const calls = [];
const childEnvs = [];
const errors = [];
const exitSignal = {};
+ const volumeRecords = ['example persisted record'];
+ const container = { running, hostBinding, hostPort, volumeRecords };
+ let recreations = 0;
+ const configuredHostBinding = dockerPortBindings[0].match(/"([^:]+):/)[1];
let exitCode = 0;
let provisioned = false;
const source = setupDbSrc.replace(/^#!.*\n/, '').replace(/^import .*;\n/gm, '')
@@ -98,10 +102,16 @@ async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady
provisioned = true;
return '';
}
- if (invocation === 'docker compose ps --format json db') return running ? '{"State":"running"}' : '';
+ if (invocation === 'docker compose ps --format json db') return container.running ? '{"State":"running"}' : '';
+ if (invocation === 'docker compose up -d db') {
+ const configuredHostPort = parseDockerPort(savedEnv.PGPORT_DOCKER);
+ if (container.hostBinding !== configuredHostBinding || container.hostPort !== configuredHostPort) recreations++;
+ Object.assign(container, { running: true, hostBinding: configuredHostBinding, hostPort: configuredHostPort });
+ return '';
+ }
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 '';
+ 'docker compose exec -T db pg_isready -h 127.0.0.1 -U portos'].includes(invocation)) return '';
throw new Error(`Unexpected synthetic subprocess: ${invocation}`);
}
});
@@ -109,7 +119,7 @@ async function runSetup({ mode = 'docker', unavailable, tty = false, nativeReady
if (error !== exitSignal) throw error;
}
expect(savedEnv).toEqual(initialEnv);
- return { exitCode, calls, childEnvs, errors };
+ return { exitCode, calls, childEnvs, errors, container, volumeRecords, recreations };
}
describe('setup preserves the selected database', () => {
@@ -130,11 +140,38 @@ describe('setup preserves the selected database', () => {
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);
+ const upIndex = result.calls.findIndex((call) => call.includes('up'));
+ expect(result.calls[upIndex]).toEqual(['docker', 'compose', 'up', '-d', 'db']);
+ expect(upIndex).toBeLessThan(result.calls.findIndex((call) => call.includes('pg_isready')));
+ expect(result.recreations).toBe(0);
expect(result.calls.some((call) => call.includes('pg_isready'))).toBe(true);
expect(result.calls.some((call) => call.includes('psql'))).toBe(true);
});
+ it.each([
+ { hostBinding: '0.0.0.0', hostPort: 5561, dotEnv: {} },
+ { hostBinding: '127.0.0.1', hostPort: 5561, dotEnv: { PGPORT_DOCKER: '5599' } },
+ ])('reconciles a running container mapping without losing its volume ($hostBinding:$hostPort)', async (configuration) => {
+ const result = await runSetup(configuration);
+ expect(result.exitCode).toBe(0);
+ expect(result.container).toMatchObject({
+ running: true, hostBinding: '127.0.0.1',
+ hostPort: parseDockerPort(configuration.dotEnv.PGPORT_DOCKER),
+ volumeRecords: ['example persisted record'],
+ });
+ expect(result.container.volumeRecords).toBe(result.volumeRecords);
+ expect(result.recreations).toBe(1);
+ });
+
+ it.each([true, false])('fails before readiness when reconciliation fails (running: %s)', async (running) => {
+ const result = await runSetup({ running, unavailable: 'docker compose up -d db' });
+ expect(result.exitCode).toBe(1);
+ expect(result.calls.every(([command]) => command === 'docker')).toBe(true);
+ expect(result.calls.some((call) => call.includes('pg_isready') || call.includes('psql'))).toBe(false);
+ expect(result.container.volumeRecords).toEqual(['example persisted record']);
+ expect(result.errors.join('\n')).toContain('Failed to reconcile');
+ });
+
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);