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: bind native database start/stop to the native backend (#10888)

Adam Eivy6681b3e34dd0
diff --git a/scripts/db-lifecycle-dispatch.test.js b/scripts/db-lifecycle-dispatch.test.js
new file mode 100644
index 0000000000..8c2cfd0367
--- /dev/null
+++ b/scripts/db-lifecycle-dispatch.test.js
@@ -0,0 +1,104 @@
+// Runs the real scripts/db.sh start/stop dispatch against stubbed executables in
+// a temporary root (#10888). The server pins a native lifecycle request with a
+// child-only PGMODE=native + canonical native endpoint; these cases prove db.sh
+// then selects only native operations even though the saved/inherited active
+// backend is Docker, and that the saved configuration is never rewritten. No
+// real database or container is touched: docker, psql, pg_isready and uname
+// are stubs placed ahead of the system directories on PATH.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+const LOGGING_STUB = (name) => `#!/bin/sh
+echo "${name} $*" >> "$STUB_LOG"
+exit 0
+`;
+
+function writeStub(binDir, name, body) {
+ const path = join(binDir, name);
+ writeFileSync(path, body);
+ chmodSync(path, 0o755);
+}
+
+describe.skipIf(process.platform === 'win32')('scripts/db.sh start/stop backend dispatch', () => {
+ let root;
+ let stubLog;
+ let envFile;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'portos-db-lifecycle-'));
+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });
+ copyFileSync(join(here, 'lib', 'envFile.cjs'), join(root, 'scripts', 'lib', 'envFile.cjs'));
+ copyFileSync(join(here, 'db.sh'), join(root, 'scripts', 'db.sh'));
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}');
+ const binDir = join(root, 'bin');
+ mkdirSync(binDir);
+ symlinkSync(process.execPath, join(binDir, 'node'));
+ for (const name of ['docker', 'psql', 'pg_isready']) writeStub(binDir, name, LOGGING_STUB(name));
+ // Not Darwin, so db.sh skips prepending a real Homebrew Postgres to PATH.
+ writeStub(binDir, 'uname', '#!/bin/sh\necho Linux\n');
+ stubLog = join(root, 'stub.log');
+ envFile = join(root, '.env');
+ writeFileSync(envFile, 'PGMODE=docker\n');
+ writeFileSync(stubLog, '');
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const run = (action, overrides) => spawnSync('bash', [join(root, 'scripts', 'db.sh'), action], {
+ cwd: root,
+ encoding: 'utf8',
+ env: {
+ PATH: `${join(root, 'bin')}:/usr/bin:/bin`,
+ HOME: root,
+ STUB_LOG: stubLog,
+ // The active backend as the running server process sees it.
+ PGMODE: 'docker',
+ PGPORT: '5561',
+ PGHOST: 'localhost',
+ PGPASSWORD: 'test-only',
+ ...overrides,
+ },
+ });
+
+ // The child environment dbAdmin builds for a native request.
+ const NATIVE_CHILD = { PGMODE: 'native', PGHOST: 'localhost', PGPORT: '5432' };
+
+ it('starts only native, probing the native port, when Docker is the active backend', () => {
+ const result = run('start', NATIVE_CHILD);
+
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Starting native PostgreSQL');
+ const log = readFileSync(stubLog, 'utf8');
+ expect(log).not.toMatch(/^docker /m);
+ expect(log).toMatch(/^pg_isready .*-p 5432\b/m);
+ expect(log).not.toMatch(/-p 5561\b/);
+ expect(readFileSync(envFile, 'utf8')).toBe('PGMODE=docker\n');
+ });
+
+ it('stops only native when Docker is the active backend', () => {
+ const result = run('stop', NATIVE_CHILD);
+
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Stopping native PostgreSQL');
+ expect(readFileSync(stubLog, 'utf8')).not.toMatch(/^docker /m);
+ expect(readFileSync(envFile, 'utf8')).toBe('PGMODE=docker\n');
+ });
+
+ // Negative control: the unpinned child (the pre-fix call) follows the active
+ // Docker backend, which is exactly the wrong-resource stop the pin prevents.
+ it('without the pin, stop follows the active Docker backend', () => {
+ const result = run('stop');
+
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Stopping Docker PostgreSQL');
+ expect(readFileSync(stubLog, 'utf8')).toMatch(/^docker compose stop db$/m);
+ });
+});
diff --git a/server/routes/database.test.js b/server/routes/database.test.js
index 3e576d70ad..45663df1e5 100644
--- a/server/routes/database.test.js
+++ b/server/routes/database.test.js
@@ -168,6 +168,70 @@ describe('database admin maintenance admission', () => {
});
});
+// #10888: db.sh picks start/stop from the mode it loads, which is the ACTIVE
+// backend (inherited env / saved .env). A native request must pin the child to
+// native, and must never touch Docker or the process's own environment.
+describe('native lifecycle targeting', () => {
+ const saved = { PGMODE: process.env.PGMODE, PGPORT: process.env.PGPORT, PGHOST: process.env.PGHOST };
+ afterEach(() => {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
+ }
+ });
+
+ it.each(['start', 'stop'])('binds native %s to the native endpoint while Docker is the active mode', async (action) => {
+ process.env.PGMODE = 'docker';
+ process.env.PGPORT = '5561';
+ process.env.PGHOST = 'docker-host.example.com';
+ mockExecFile([{ exitCode: 0, stdout: `native ${action}` }]);
+
+ const res = await request(makeApp()).post(`/api/database/${action}`).send({ backend: 'native' });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ success: true, output: `native ${action}` });
+ expect(execFile).toHaveBeenCalledTimes(1);
+ const [cmd, args, opts] = execFile.mock.calls[0];
+ expect(cmd).toBe('bash');
+ expect(args.at(-1)).toBe(action);
+ expect(opts.env).toMatchObject({ PGMODE: 'native', PGHOST: 'localhost', PGPORT: '5432' });
+ // Child-only: the server's own active-backend environment is unchanged.
+ expect(process.env).toMatchObject({ PGMODE: 'docker', PGPORT: '5561', PGHOST: 'docker-host.example.com' });
+ });
+
+ it.each([
+ ['start', ['compose', 'up', '-d', 'db']],
+ ['stop', ['compose', 'stop', 'db']],
+ ])('keeps Docker %s on Docker and away from db.sh', async (action, composeArgs) => {
+ process.env.PGMODE = 'native';
+ mockExecFile([{ exitCode: 0, stdout: '' }]);
+
+ const res = await request(makeApp()).post(`/api/database/${action}`).send({ backend: 'docker' });
+
+ expect(res.status).toBe(200);
+ expect(execFile).toHaveBeenCalledTimes(1);
+ expect(execFile.mock.calls[0][0]).toBe('docker');
+ expect(execFile.mock.calls[0][1]).toEqual(composeArgs);
+ });
+
+ it('refuses native lifecycle before any child process when the native endpoint aliases Docker', async () => {
+ vi.resetModules();
+ vi.doMock('../lib/ports.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ resolvePostgresPort: () => 5561,
+ }));
+ try {
+ const { startDatabase, stopDatabase } = await import('../services/dbAdmin.js');
+ for (const lifecycle of [startDatabase, stopDatabase]) {
+ await expect(lifecycle('native')).rejects.toThrow(/distinct native database endpoint/);
+ }
+ expect(execFile).not.toHaveBeenCalled();
+ } finally {
+ vi.doUnmock('../lib/ports.js');
+ vi.resetModules();
+ }
+ });
+});
+
// A fenced operation must remain inspectable without pool/shell admission,
// while endpoint identities and damaged on-disk bytes never reach the API.
describe('database maintenance status', () => {
diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.js
index 0c0bfe1d72..98d8b3fd0f 100644
--- a/server/services/dbAdmin.js
+++ b/server/services/dbAdmin.js
@@ -622,6 +622,24 @@ async function syncDatabaseImpl(io) {
return { success: true, dumpFile };
}
+/**
+ * Child environment that pins db.sh to the native backend for one lifecycle
+ * command. db.sh chooses start/stop from PGMODE and the endpoint from PGPORT, and
+ * both normally describe the ACTIVE backend (inherited from this process or the
+ * saved .env), so a native request under Docker would otherwise start/stop Docker.
+ * The override is child-only: saved configuration and the running pool are
+ * untouched. Refuses to run when the canonical native endpoint is unusable or
+ * collides with the Docker endpoint, before any lifecycle effect.
+ */
+function nativeLifecycleEnv() {
+ const port = Number(NATIVE_PORT);
+ if (!Number.isInteger(port) || port < 1 || port > 65535
+ || endpointsAlias('localhost', NATIVE_PORT, 'localhost', DOCKER_PORT)) {
+ throw new ServerError('Cannot resolve a distinct native database endpoint. Nothing was started or stopped.', { status: 500 });
+ }
+ return { ...pgEnv(NATIVE_PORT), PGMODE: 'native' };
+}
+
/** Start a specific database backend. */
async function startDatabaseImpl(backend) {
if (backend === 'docker') {
@@ -629,8 +647,9 @@ async function startDatabaseImpl(backend) {
return { success: result.exitCode === 0, output: result.stdout };
}
- // Native: use db.sh which handles brew services / pg_ctl
- const result = await runCmd(bashBinary, [dbScript, 'start'], 30_000);
+ // Native: db.sh handles brew services / pg_ctl, but picks its operation from
+ // the mode it loads. Bind the child to the native backend explicitly.
+ const result = await runCmd(bashBinary, [dbScript, 'start'], 30_000, nativeLifecycleEnv());
return { success: result.exitCode === 0, output: result.stdout };
}
@@ -641,8 +660,8 @@ async function stopDatabaseImpl(backend) {
return { success: result.exitCode === 0, output: result.stdout };
}
- // Native stop
- const result = await runCmd(bashBinary, [dbScript, 'stop'], 15_000);
+ // Native stop: never let the active (possibly Docker) mode choose the target.
+ const result = await runCmd(bashBinary, [dbScript, 'stop'], 15_000, nativeLifecycleEnv());
return { success: result.exitCode === 0, output: result.stdout };
}