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

feat: validate database cutover preflight without accepting maintenance (#8849)

[._.]/ Adam Eivy69b105afc356
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 7e40dae036..1501dcb957 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -264,6 +264,14 @@ The Settings switch/migration requests and `scripts/db.sh migrate`,
and strand them on the source; changing `.env` also leaves the running server
connected to its original pool.
+`POST /api/database/maintenance/preflight` accepts explicit `source` and `target`
+backend names through the ordinary instance authentication gate. It checks the
+saved direction against the running pool and requires complete, trusted, idle
+work state. A successful response is `{ source, target, advisory: true, accepted: false }`: it creates no operation, reserves no maintenance window, and does
+not promise that a later request is safe. The future acceptance path must repeat
+these checks under its final admission protocol. Missing/unreadable work state,
+configuration drift, or an existing maintenance fence refuses the check.
+
Keep the existing backend selected and use backups until the coordinated
offline cutover is available (tracked in #8797 / #8805). A safe cutover requires
downtime for **all** PortOS writers, including the CoS runner, and verification
diff --git a/server/lib/README.md b/server/lib/README.md
index 8581a32b3f..92c746be9c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -766,4 +766,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `messageBrowserIdentity.js` | Shared Outlook row extraction and identity-safe browser action scripts; exact unique targets and confirmed row removal. |
-| `databaseMaintenanceJournal.js` | Durable cross-process database admission fence and operation journal with exclusive coordinator ownership and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |
+| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index 5221acb26e..786edc9b28 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -5,7 +5,7 @@ import { z } from 'zod';
import { PATHS } from './paths.js';
import { assertNotRealDataWrite } from './testDataIsolation.js';
-const endpointSchema = z.object({
+export const databaseMaintenanceEndpointSchema = z.object({
mode: z.enum(['native', 'docker']),
host: z.string().min(1).max(255),
port: z.number().int().min(1).max(65535),
@@ -20,8 +20,8 @@ const journalSchema = z.object({
id: z.string().uuid(),
stage: z.enum(stages),
createdAt: z.string().datetime(),
- source: endpointSchema,
- target: endpointSchema,
+ source: databaseMaintenanceEndpointSchema,
+ target: databaseMaintenanceEndpointSchema,
}).strict();
const normalizedHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase())
@@ -184,7 +184,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
// never be automatically stolen on a timeout or an unverified PID guess.
const initial = read();
if (!initial || initial.id !== id) throw new Error('Database maintenance operation does not match.');
- const parsedSource = endpointSchema.parse(source);
+ const parsedSource = databaseMaintenanceEndpointSchema.parse(source);
if (JSON.stringify(initial.source) !== JSON.stringify(parsedSource)) {
throw new Error('Saved database endpoint changed; source-only cancellation refused.');
}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 67df87ad2e..11571604a7 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1636,6 +1636,12 @@ export const databaseSwitchSchema = z.object({
migrate: z.boolean().optional()
});
+// POST /api/database/maintenance/preflight — advisory only; never accepts a cutover.
+export const databaseMaintenancePreflightSchema = z.object({
+ source: z.enum(DB_BACKENDS),
+ target: z.enum(DB_BACKENDS)
+}).strict().refine(value => value.source !== value.target, { message: 'Source and target must differ' });
+
// POST /api/database/{start,stop,destroy} — operate on a named backend.
export const databaseBackendSchema = z.object({
backend: z.enum(DB_BACKENDS)
diff --git a/server/routes/database.js b/server/routes/database.js
index 0bebcb0771..304ff0048b 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -4,7 +4,8 @@ import {
validateRequest,
databaseSwitchSchema,
databaseBackendSchema,
- databaseExportSchema
+ databaseExportSchema,
+ databaseMaintenancePreflightSchema
} from '../lib/validation.js';
import * as dbAdmin from '../services/dbAdmin.js';
@@ -17,6 +18,13 @@ router.get('/maintenance/status', asyncHandler(async (_req, res) => {
res.json(dbAdmin.getMaintenanceStatus());
}));
+// Advisory validation only: acceptance must repeat this under the admission fence.
+router.post('/maintenance/preflight', asyncHandler(async (req, res) => {
+ const direction = validateRequest(databaseMaintenancePreflightSchema, req.body);
+ res.set('Cache-Control', 'no-store');
+ res.json(await dbAdmin.preflightDatabaseMaintenance(direction));
+}));
+
// GET /api/database/status — current mode, connectivity, row counts, resource stats
router.get('/status', asyncHandler(async (_req, res) => {
res.json(await dbAdmin.getStatus());
diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.js
new file mode 100644
index 0000000000..7bb66bb74c
--- /dev/null
+++ b/server/routes/databasePreflight.test.js
@@ -0,0 +1,179 @@
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../lib/paths.js', async importOriginal => {
+ const { makePathsProxy, lazyTempDataRoot } = await import('../lib/mockPathsDataRoot.js');
+ return makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-database-preflight-'),
+ extraOverrides: root => ({ installRoot: root }),
+ });
+});
+vi.mock('../lib/db.js', () => ({
+ POOL_CONFIG: { host: 'localhost', port: 5432, user: 'example_role', database: 'example_test', password: 'example-only' },
+ checkHealth: vi.fn(), query: vi.fn(),
+}));
+vi.mock('../services/activeProcessing.js', () => ({ getSystemActivity: vi.fn() }));
+vi.mock('../services/updatePreflight.js', () => ({
+ countActiveCosAgents: vi.fn(), getPersistentMindImageWorkGuard: vi.fn(),
+}));
+vi.mock('../lib/childProcess.js', async importOriginal => ({
+ ...await importOriginal(), execFile: vi.fn(), spawn: vi.fn(),
+}));
+
+import databaseRoutes from './database.js';
+import { PATHS } from '../lib/paths.js';
+import { POOL_CONFIG, query } from '../lib/db.js';
+import { execFile, spawn } from '../lib/childProcess.js';
+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';
+import { cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+import { getSystemActivity } from '../services/activeProcessing.js';
+import { countActiveCosAgents, getPersistentMindImageWorkGuard } from '../services/updatePreflight.js';
+
+const idle = () => ({
+ jobs: [], extras: { imageTo3d: [] }, agents: { trusted: true, active: 0, queued: 0 },
+ mind: { trusted: true, thinking: false, queued: 0 }, llm: { trusted: true, active: 0 },
+ appOperations: [], update: { inProgress: false }, backup: { inProgress: false },
+});
+const saveMode = mode => writeFileSync(join(PATHS.installRoot, '.env'), `PGMODE=${mode}\n`);
+const app = express();
+app.use(express.json());
+app.use('/api/database', databaseRoutes);
+app.use((err, _req, res, _next) => res.status(err.status ?? 500).json({ error: err.message, code: err.code }));
+const preflight = (body = { source: 'native', target: 'docker' }) => request(app).post('/api/database/maintenance/preflight').send(body);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ for (const [key, value] of Object.entries({ PGHOST: 'localhost', PGPORT: '5432', PORTOS_NATIVE_PGPORT: '5432', PGPORT_DOCKER: '5561', PGUSER: 'example_role', PGDATABASE: 'example_test', PGPASSWORD: 'example-only' })) vi.stubEnv(key, value);
+ Object.assign(POOL_CONFIG, { host: 'localhost', port: 5432, user: 'example_role', database: 'example_test' });
+ copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(PATHS.installRoot, 'ecosystem.config.cjs'));
+ saveMode('native');
+ getSystemActivity.mockResolvedValue(idle());
+ countActiveCosAgents.mockResolvedValue(0);
+ getPersistentMindImageWorkGuard.mockResolvedValue({ trusted: true, safe: true });
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ rmSync(join(PATHS.data, 'database-maintenance'), { recursive: true, force: true });
+ expect(execFile).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+});
+afterAll(cleanupTempDataRoots);
+
+describe('database maintenance preflight HTTP contract', () => {
+ it.each(['native', 'docker'])('returns only non-accepted advice for a trusted idle %s source', async source => {
+ saveMode(source);
+ POOL_CONFIG.port = source === 'native' ? 5432 : 5561;
+ const target = source === 'native' ? 'docker' : 'native';
+ const result = await preflight({ source, target });
+ expect(result.status).toBe(200);
+ expect(result.headers['cache-control']).toBe('no-store');
+ expect(result.body).toEqual({ source, target, advisory: true, accepted: false });
+ expect(createDatabaseMaintenanceJournal(PATHS.data).read()).toBeNull();
+ expect(readFileSync(join(PATHS.installRoot, '.env'), 'utf8')).toBe(`PGMODE=${source}\n`);
+ });
+
+ it.each([
+ {}, { source: 'native', target: 'native' }, { source: 'native', target: 'other' },
+ { source: 'native', target: 'docker', force: true },
+ ])('rejects invalid or bypass-shaped requests before work inspection: %j', async body => {
+ expect((await preflight(body)).status).toBe(400);
+ expect(getSystemActivity).not.toHaveBeenCalled();
+ });
+
+ it.each(['host', 'port', 'user', 'database'])('refuses when saved source differs from the actual pool %s', async key => {
+ POOL_CONFIG[key] = key === 'port' ? 6000 : 'example-mismatch';
+ const result = await preflight();
+ expect(result.status).toBe(409);
+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_STALE');
+ expect(result.body.error).not.toContain('example-mismatch');
+ expect(getSystemActivity).not.toHaveBeenCalled();
+ });
+
+ it('refuses reversed requests and aliased backends', async () => {
+ expect((await preflight({ source: 'docker', target: 'native' })).body.code).toBe('DATABASE_PREFLIGHT_STALE');
+ vi.stubEnv('PGPORT_DOCKER', '5432');
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_STALE');
+ expect(getSystemActivity).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['queued media', s => { s.jobs = [{ status: 'queued', prompt: 'example private prompt' }]; }],
+ ['active agent', s => { s.agents.active = 1; }],
+ ['queued mind', s => { s.mind.queued = 1; }],
+ ['LLM run', s => { s.llm.active = 1; }],
+ ['backup', s => { s.backup.inProgress = true; }],
+ ['update', s => { s.update.inProgress = true; }],
+ ['app operation', s => { s.appOperations = [{ name: 'example-private-app' }]; }],
+ ['image build', s => { s.extras.imageTo3d = [{ name: 'example-private-model' }]; }],
+ ])('refuses %s without exposing activity records', async (_label, mutate) => {
+ const snapshot = idle(); mutate(snapshot); getSystemActivity.mockResolvedValue(snapshot);
+ const result = await preflight();
+ expect(result.status).toBe(409);
+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_BUSY');
+ expect(JSON.stringify(result.body)).not.toContain('example');
+ });
+
+ it.each([
+ ['missing slice', s => { delete s.jobs; }],
+ ['unreadable builds', s => { s.extras.imageTo3d = null; }],
+ ['untrusted agents', s => { s.agents.trusted = false; }],
+ ['untrusted mind', s => { s.mind.trusted = false; }],
+ ['untrusted LLM', s => { s.llm.trusted = false; }],
+ ['malformed count', s => { s.agents.active = -1; }],
+ ])('refuses %s instead of manufacturing an idle snapshot', async (_label, mutate) => {
+ const snapshot = idle(); mutate(snapshot); getSystemActivity.mockResolvedValue(snapshot);
+ const result = await preflight();
+ expect(result.status).toBe(409);
+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_UNTRUSTED');
+ });
+
+ it('includes the spawn window and independent Persistent Mind guard', async () => {
+ countActiveCosAgents.mockResolvedValue(1);
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_BUSY');
+ countActiveCosAgents.mockResolvedValue(0);
+ getPersistentMindImageWorkGuard.mockResolvedValue({ trusted: true, safe: false });
+ const mindBusy = await preflight();
+ expect(mindBusy.body.code, JSON.stringify(mindBusy)).toBe('DATABASE_PREFLIGHT_BUSY');
+ getPersistentMindImageWorkGuard.mockResolvedValue({ trusted: false, safe: false });
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_UNTRUSTED');
+ });
+
+ it('sanitizes failed inspections and unreadable saved configuration', async () => {
+ getSystemActivity.mockRejectedValue(new Error('example private connection detail'));
+ const result = await preflight();
+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_UNTRUSTED');
+ expect(JSON.stringify(result.body)).not.toContain('example');
+ rmSync(join(PATHS.installRoot, '.env'));
+ mkdirSync(join(PATHS.installRoot, '.env'));
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_UNTRUSTED');
+ rmSync(join(PATHS.installRoot, '.env'), { recursive: true });
+ });
+
+ it('re-reads saved settings after asynchronous work inspection', async () => {
+ getSystemActivity.mockImplementation(async () => { saveMode('docker'); return idle(); });
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_STALE');
+ // Same active source, but the target identity changed during the observation.
+ saveMode('native');
+ getSystemActivity.mockImplementation(async () => { vi.stubEnv('PGPORT_DOCKER', '6000'); return idle(); });
+ expect((await preflight()).body.code).toBe('DATABASE_PREFLIGHT_STALE');
+ });
+
+ it('rechecks the persistent fence before returning advice', async () => {
+ const journal = createDatabaseMaintenanceJournal(PATHS.data);
+ getSystemActivity.mockImplementation(async () => {
+ const source = { mode: 'native', host: 'localhost', port: 5432, user: 'example_role', database: 'example_test' };
+ journal.begin({ source, target: { ...source, mode: 'docker', port: 5561 } });
+ return idle();
+ });
+ const result = await preflight();
+ expect(result.status).toBe(503);
+ expect(result.body.code).toBe('DATABASE_MAINTENANCE');
+ getSystemActivity.mockClear();
+ expect((await preflight()).status).toBe(503);
+ expect(getSystemActivity).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/databasePreflight.js b/server/services/databasePreflight.js
new file mode 100644
index 0000000000..d4101d07bc
--- /dev/null
+++ b/server/services/databasePreflight.js
@@ -0,0 +1,87 @@
+import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { z } from 'zod';
+import { PATHS } from '../lib/paths.js';
+import { POOL_CONFIG } from '../lib/db.js';
+import { assertDatabaseAdmission, databaseMaintenanceEndpointSchema } from '../lib/databaseMaintenanceJournal.js';
+import { databaseMaintenancePreflightSchema } from '../lib/validation.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { summarizeSystemActivity } from '../lib/systemIdle.js';
+
+const require = createRequire(import.meta.url);
+const refuse = (code, message) => new ServerError(message, { status: 409, code });
+const unavailable = () => refuse('DATABASE_PREFLIGHT_UNTRUSTED', 'Database configuration or work state could not be verified.');
+const stale = () => refuse('DATABASE_PREFLIGHT_STALE', 'Requested direction does not match the current database configuration and running pool.');
+const busy = () => refuse('DATABASE_PREFLIGHT_BUSY', 'PortOS has active or queued work. Wait for it to finish before database maintenance.');
+const count = z.number().int().nonnegative();
+// The dashboard summarizer intentionally accepts partial snapshots. Maintenance
+// cannot use a missing slice as proof that there are no writers in that domain.
+const activitySchema = z.object({
+ jobs: z.array(z.object({ status: z.enum(['running', 'queued']) })),
+ extras: z.object({ imageTo3d: z.array(z.unknown()) }),
+ agents: z.object({ trusted: z.literal(true), active: count, queued: count }),
+ mind: z.object({ trusted: z.literal(true), thinking: z.boolean(), queued: count }),
+ llm: z.object({ trusted: z.literal(true), active: count }),
+ appOperations: z.array(z.unknown()),
+ update: z.object({ inProgress: z.boolean() }),
+ backup: z.object({ inProgress: z.boolean() }),
+});
+const normalizeHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase()) ? 'loopback' : host.toLowerCase();
+
+function readConfiguration() {
+ // Ecosystem exports are evaluated once by require. Re-evaluate on each read
+ // so an operator's saved mode change cannot validate against cached settings.
+ // Check readability separately: ecosystem's boot defaults deliberately mask
+ // a failed .env read, which cannot be treated as evidence for a cutover.
+ const envPath = join(PATHS.installRoot, '.env');
+ let content;
+ try { content = readFileSync(envPath, 'utf8'); } catch (err) {
+ if (err.code !== 'ENOENT') throw unavailable();
+ content = null;
+ }
+ const configPath = join(PATHS.installRoot, 'ecosystem.config.cjs');
+ let configuration;
+ try {
+ delete require.cache[require.resolve(configPath)];
+ configuration = require(configPath);
+ } catch { throw unavailable(); }
+ const { DATABASE_MODE: mode, DATABASE_ENDPOINTS: endpoints } = configuration ?? {};
+ const source = databaseMaintenanceEndpointSchema.safeParse(endpoints?.[mode]);
+ const target = databaseMaintenanceEndpointSchema.safeParse(endpoints?.[mode === 'native' ? 'docker' : 'native']);
+ if (!source.success || !target.success || source.data.mode !== mode || target.data.mode === mode) throw unavailable();
+ if (normalizeHost(source.data.host) === normalizeHost(target.data.host) && source.data.port === target.data.port) throw stale();
+ return { source: source.data, target: target.data, revision: createHash('sha256').update(JSON.stringify(content)).digest('hex') };
+}
+
+function validateDirection(direction, configuration) {
+ if (direction.source !== configuration.source.mode || direction.target !== configuration.target.mode
+ || ['host', 'port', 'database', 'user'].some(key => configuration.source[key] !== POOL_CONFIG[key])) throw stale();
+}
+
+/** Non-mutating advice only; no operation token, reservation, or writer drain. */
+export async function preflightDatabaseMaintenance(input) {
+ const direction = databaseMaintenancePreflightSchema.parse(input);
+ assertDatabaseAdmission();
+ const initial = readConfiguration();
+ validateDirection(direction, initial);
+ // Keep heavy activity/CoS graphs off ordinary database admin imports. Use the
+ // lifecycle-only reader, not GPU telemetry or external Ollama probes.
+ const [snapshot, activeAgents, mindGuard] = await Promise.all([
+ import('./activeProcessing.js'), import('./updatePreflight.js'),
+ ]).then(([processing, preflight]) => Promise.all([
+ processing.getSystemActivity(), preflight.countActiveCosAgents(), preflight.getPersistentMindImageWorkGuard(),
+ ])).catch(() => { throw unavailable(); });
+ const activity = activitySchema.safeParse(snapshot);
+ if (!activity.success || !Number.isInteger(activeAgents) || activeAgents < 0
+ || mindGuard?.trusted !== true || typeof mindGuard.safe !== 'boolean') throw unavailable();
+ if (!summarizeSystemActivity(activity.data).idle || activeAgents > 0 || !mindGuard.safe) throw busy();
+ // No await between the final fence/configuration checks and the response.
+ // This narrows the observation race, but is deliberately NOT acceptance.
+ assertDatabaseAdmission();
+ const final = readConfiguration();
+ validateDirection(direction, final);
+ if (JSON.stringify(initial) !== JSON.stringify(final)) throw stale();
+ return { source: direction.source, target: direction.target, advisory: true, accepted: false };
+}
diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.js
index 4df88b6e6d..d1a889f57b 100644
--- a/server/services/dbAdmin.js
+++ b/server/services/dbAdmin.js
@@ -10,6 +10,8 @@ import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';
import { resolvePostgresPort } from '../lib/ports.js';
import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';
+export { preflightDatabaseMaintenance } from './databasePreflight.js';
+
const rootDir = PATHS.root;
const dbScript = toBashPath(join(rootDir, 'scripts', 'db.sh'));
// Resolve the interpreter explicitly. A bare `bash` on Windows often resolves