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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: pin cutover config probe and PM2 restart to the recorded endpoints (#8851)
[._.]/ Adam Eivydc617bfb52be
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.jsindex 72bd6db256..aa9d1b110c 100644--- a/server/lib/databaseMaintenanceWorker.test.js+++ b/server/lib/databaseMaintenanceWorker.test.js@@ -20,7 +20,7 @@ const cutoverFixtureUrl = new URL('../test/fixtures/databaseCutoverStubs.js', imconst detachedUrl = new URL('./detachedSpawn.js', import.meta.url).href;const source = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };-const target = { ...source, mode: 'docker', host: 'docker.example.invalid', port: 5561 };+const target = { ...source, mode: 'docker', port: 5561 };let root;let journal;let env;diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.jsindex 7a76a600a5..44c8302a2c 100644--- a/server/routes/databasePreflight.test.js+++ b/server/routes/databasePreflight.test.js@@ -228,24 +228,36 @@ describe('database cutover acceptance HTTP contract', () => {expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();});- it.each([- ['work admitted before the fence', () => busy()],- ['a saved-mode change', () => { saveMode('docker'); return idle(); }],- ])('cancels the unowned operation when the final fenced check sees %s', async (_label, observe) => {- getSystemActivity.mockResolvedValueOnce(idle()).mockImplementationOnce(async () => {- // This observation runs AFTER publication: admission is already closed.- expect(createDatabaseMaintenanceJournal(PATHS.data).isFenced()).toBe(true);- return observe();- });+ // The second activity observation runs AFTER publication: admission is closed.+ const raceFinalCheck = observe => getSystemActivity.mockResolvedValueOnce(idle()).mockImplementationOnce(async () => {+ expect(createDatabaseMaintenanceJournal(PATHS.data).isFenced()).toBe(true);+ return observe();+ });++ it('cancels the unowned operation when work admitted before the fence is still running', async () => {+ raceFinalCheck(busy);const result = await accept();expect(result.status).toBe(409);- expect(['DATABASE_PREFLIGHT_BUSY', 'DATABASE_PREFLIGHT_STALE']).toContain(result.body.code);+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_BUSY');const journal = createDatabaseMaintenanceJournal(PATHS.data);expect(journal.read()).toBeNull();expect(() => journal.assertAdmission()).not.toThrow();expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();});+ it('keeps the fence when the saved source changed during acceptance', async () => {+ raceFinalCheck(() => { saveMode('docker'); return idle(); });+ const result = await accept();+ expect(result.status).toBe(409);+ expect(result.body.code).toBe('DATABASE_PREFLIGHT_STALE');+ // Reopening now would let a restart select the unimported backend.+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ expect(journal.read()).toMatchObject({ stage: 'accepted', source: { mode: 'native' } });+ expect(() => journal.assertAdmission()).toThrow();+ expect(journal.coordinatorStatus(journal.read().id)).toEqual({ state: 'unclaimed' });+ expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();+ });+it('requires host-control authority before accepting or recovering', async () => {const gated = express();gated.use((req, _res, next) => { req.portosAuthContext = { enabled: true, authenticated: false }; next(); });diff --git a/server/services/databaseMaintenanceCutover.js b/server/services/databaseMaintenanceCutover.jsindex 1eb85a17eb..5c109ed442 100644--- a/server/services/databaseMaintenanceCutover.js+++ b/server/services/databaseMaintenanceCutover.js@@ -26,16 +26,34 @@ function syncPath(path) {try { fsyncSync(fd); } finally { closeSync(fd); }}+const ROUTING_VARIABLES = ['PGHOST', 'PGHOSTADDR', 'PGPORT', 'PGUSER', 'PGDATABASE', 'PGSERVICE', 'PGSERVICEFILE',+ 'PGOPTIONS', 'PGMODE', 'PORTOS_NATIVE_PGPORT', 'PGPORT_DOCKER'];++/**+ * The environment every ecosystem evaluation of this operation runs in. The+ * worker inherits its launcher's variables — the pre-cutover server's active+ * PGPORT, or an operator shell's overrides — and the ecosystem lets the+ * environment outrank .env. Pin both backends' identities to the RECORDED+ * endpoints so only the committed PGMODE decides which one is active.+ */+function recordedEndpointEnv(operation) {+ const env = { ...process.env };+ for (const key of ROUTING_VARIABLES) delete env[key];+ const byMode = { [operation.source.mode]: operation.source, [operation.target.mode]: operation.target };+ return { ...env, PGHOST: operation.target.host, PGUSER: operation.target.user, PGDATABASE: operation.target.database,+ PORTOS_NATIVE_PGPORT: String(byMode.native.port), PGPORT_DOCKER: String(byMode.docker.port) };+}+/*** The endpoint the SAVED configuration resolves to, evaluated in a fresh* process exactly as the next `pm2 restart ecosystem.config.cjs` will. This- * process's own require cache and environment captured the pre-cutover mode.+ * process's own require cache captured the pre-cutover mode.*/-function readSavedEndpoint() {+function readSavedEndpoint(env) {const config = join(PATHS.installRoot, 'ecosystem.config.cjs');const code = `const c=require(${JSON.stringify(config)});process.stdout.write(JSON.stringify(c.DATABASE_ENDPOINTS?.[c.DATABASE_MODE]??null))`;return new Promise((resolve) => {- const child = spawn(process.execPath, ['-e', code], { cwd: PATHS.installRoot, stdio: ['ignore', 'pipe', 'ignore'] });+ const child = spawn(process.execPath, ['-e', code], { cwd: PATHS.installRoot, env, stdio: ['ignore', 'pipe', 'ignore'] });let stdout = '';child.stdout.on('data', chunk => { if (stdout.length < 4096) stdout += chunk; });child.once('error', () => resolve(null));@@ -45,8 +63,8 @@ function readSavedEndpoint() {});}-async function assertSavedTarget(target) {- if (JSON.stringify(await readSavedEndpoint()) !== JSON.stringify(target)) {+async function assertSavedTarget(operation) {+ if (JSON.stringify(await readSavedEndpoint(recordedEndpointEnv(operation))) !== JSON.stringify(operation.target)) {throw refused('the saved configuration does not resolve to the recorded target');}}@@ -57,7 +75,8 @@ async function assertSavedTarget(target) {* guesses from the file's current contents or restores the source mode.* Every other line is preserved byte for byte.*/-async function commitSavedMode(target) {+async function commitSavedMode(operation) {+ const { target } = operation;const envPath = join(PATHS.installRoot, '.env');// .env lives beside data/, outside the data-root write guard: a test run// must never rewrite a real install's configuration.@@ -88,7 +107,7 @@ async function commitSavedMode(target) {renameSync(pending, envPath);syncPath(PATHS.installRoot);}- await assertSavedTarget(target);+ await assertSavedTarget(operation);}/**@@ -98,7 +117,8 @@ async function commitSavedMode(target) {* proof from an earlier pid is not success. The server is restarted at most* once per attempt; a crash-looping or wrong-pool server times out fenced.*/-async function awaitRestartedTarget(journal, id, token, saved, { proofTimeoutMs = PROOF_TIMEOUT_MS, pollMs = POLL_MS }) {+async function awaitRestartedTarget(journal, operation, token, saved, { proofTimeoutMs = PROOF_TIMEOUT_MS, pollMs = POLL_MS }) {+ const { id } = operation;const deadline = Date.now() + proofTimeoutMs;let restarted = false;while (true) {@@ -107,7 +127,7 @@ async function awaitRestartedTarget(journal, id, token, saved, { proofTimeoutMsif (server.status === 'online' && server.pid > 0 && journal.readTargetProof(id, server.pid)) return server.pid;if (server.status !== 'online' && !restarted) {journal.assertEnteredCoordinatorWorker(id, token);- const result = await restartMaintenanceProducer('portos-server').catch(() => null);+ const result = await restartMaintenanceProducer('portos-server', recordedEndpointEnv(operation)).catch(() => null);if (result?.success !== true) throw refused('the server could not be restarted');restarted = true;}@@ -145,23 +165,23 @@ export async function runDatabaseCutover(id, token, options = {}) {operation = journal.transition(id, token, 'importing', 'committing');}if (operation.stage === 'committing') {- await commitSavedMode(operation.target);+ await commitSavedMode(operation);journal.assertEnteredCoordinatorWorker(id, token);operation = journal.transition(id, token, 'committing', 'verifying');}if (operation.stage === 'verifying') {- await awaitRestartedTarget(journal, id, token, saved, options);+ await awaitRestartedTarget(journal, operation, token, saved, options);operation = journal.transition(id, token, 'verifying', 'verified');}if (operation.stage !== 'verified') throw refused(`stage ${operation.stage} cannot be released`);// A hand edit while fenced must never release admission onto another backend.- await assertSavedTarget(operation.target);+ await assertSavedTarget(operation);journal.releaseAdmission(id, token);// Admission is open; CoS boots through its own fence and authority check.let cosRestarted = false;if (saved.find(row => row.name === 'portos-cos')?.status === 'online') {- cosRestarted = (await restartMaintenanceProducer('portos-cos').catch(() => null))?.success === true;+ cosRestarted = (await restartMaintenanceProducer('portos-cos', recordedEndpointEnv(operation)).catch(() => null))?.success === true;if (!cosRestarted) console.error('❌ Database cutover released, but portos-cos did not restart; start it with pm2');}return { id, stage: 'released', source: operation.source.mode, target: operation.target.mode,diff --git a/server/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.jsindex 10fa182c1a..3323431a54 100644--- a/server/services/databaseMaintenanceCutover.test.js+++ b/server/services/databaseMaintenanceCutover.test.js@@ -32,8 +32,8 @@ const { createDatabaseAuthority } = await import('../lib/databaseAuthority.js');const { runDatabaseTransfer } = await import('./databaseMaintenanceTransfer.js');const { runDatabaseCutover } = await import('./databaseMaintenanceCutover.js');-const native = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };-const docker = { mode: 'docker', host: 'docker.example.invalid', port: 5561, database: 'example_test', user: 'example' };+const native = { mode: 'native', host: 'db.example.invalid', port: 5432, database: 'example_test', user: 'example' };+const docker = { mode: 'docker', host: 'db.example.invalid', port: 5561, database: 'example_test', user: 'example' };const fast = { graceMs: 1500, pollMs: 20, proofTimeoutMs: 4000 };const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };const savedEnv = { ...process.env };@@ -78,7 +78,11 @@ beforeEach(() => {row.status = 'online';return { success: true };});- Object.assign(process.env, { PATH: `${stubs.bin}:${savedEnv.PATH}`, PGPASSWORD: 'example-password' });+ // The worker inherits its launcher's pre-cutover routing variables; they+ // must not redirect the saved-configuration probe or the PM2 restart.+ Object.assign(process.env, { PATH: `${stubs.bin}:${savedEnv.PATH}`, PGPASSWORD: 'example-password',+ PGHOST: 'inherited.example.invalid', PGPORT: '1', PGUSER: 'inherited', PGDATABASE: 'inherited',+ PORTOS_NATIVE_PGPORT: '2', PGPORT_DOCKER: '3' });});afterEach(() => {for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key];@@ -121,6 +125,11 @@ describe.skipIf(process.platform === 'win32')('offline database cutover', () =>expect(stubs.events().slice(0, 6)).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none','import-start', 'import-commit', 'restart portos-server']);expect(stubs.events().indexOf('restart portos-cos')).toBeGreaterThan(stubs.events().indexOf('restart portos-server'));+ // PM2 re-evaluates the ecosystem with the RECORDED endpoints, not inherited overrides.+ const [, restartEnv] = context.restart.mock.calls.find(([name]) => name === 'portos-server');+ expect(restartEnv).toMatchObject({ PGHOST: target.host, PGUSER: target.user, PGDATABASE: target.database,+ PORTOS_NATIVE_PGPORT: String(native.port), PGPORT_DOCKER: String(docker.port) });+ expect(restartEnv.PGPORT).toBeUndefined();expect(readFileSync(join(root, '.env'), 'utf8')).toBe(`PGPASSWORD=example-password\nPGMODE=${target.mode}\nPORTOS_EXAMPLE=kept\n`);// Admission is open; the authority record retires the source endpoint.diff --git a/server/services/databasePreflight.js b/server/services/databasePreflight.jsindex c2a3f9d9af..5eb700cd5d 100644--- a/server/services/databasePreflight.js+++ b/server/services/databasePreflight.js@@ -95,7 +95,8 @@ export async function preflightDatabaseMaintenance(input) {* configuration checks UNDER the fence: work admitted just before publication* must already be finished, and nothing new can be admitted. Only then does a* coordinator take ownership and the detached worker launch. A failed final- * check cancels the still-unowned operation, reopening admission unchanged.+ * check cancels the still-unowned operation — but only while the saved source+ * still equals the recorded one; otherwise the fence stays for the operator.*/export async function acceptDatabaseMaintenance(input) {const direction = databaseMaintenancePreflightSchema.parse(input);@@ -115,7 +116,13 @@ export async function acceptDatabaseMaintenance(input) {validateDirection(direction, final);if (final.revision !== configuration.revision) throw stale();} catch (err) {- journal.cancel(operation.id, configuration.source);+ // cancel() itself refuses when the saved source no longer matches the+ // record; a changed or unreadable configuration keeps the fence closed.+ let current = null;+ try { current = readConfiguration().source; } catch { /* keep the fence */ }+ if (current) {+ try { journal.cancel(operation.id, current); } catch { /* keep the fence */ }+ }throw err;}const token = journal.acquireCoordinator(operation.id);diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 0e8576a6de..ceae971c02 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -566,13 +566,14 @@ export async function listMaintenanceProcesses() {* Internal maintenance restart of one PortOS producer. Re-evaluates the* install's ecosystem file with --update-env so the app receives the saved* database configuration a cutover just committed, never PM2's cached env.+ * `env` is the environment the ecosystem file is evaluated in.* PM2 success is not proof of the backend: the restarted process must still* prove its own pool (services/databaseCutoverHandshake.js).*/-export async function restartMaintenanceProducer(name) {+export async function restartMaintenanceProducer(name, env = process.env) {if (!['portos-server', 'portos-cos'].includes(name)) throw new Error('Unknown maintenance producer.');await execPm2(['restart', join(PATHS.installRoot, 'ecosystem.config.cjs'), '--only', name, '--update-env'],- { cwd: PATHS.installRoot });+ { cwd: PATHS.installRoot, env });return { success: true };}diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.jsindex f5290de5a3..08ef1faf5d 100644--- a/server/test/fixtures/databaseCutoverStubs.js+++ b/server/test/fixtures/databaseCutoverStubs.js@@ -1,15 +1,16 @@// Disposable stand-ins for the restart half of a database cutover. Nothing// here reaches a real database, PM2 daemon or install configuration://-// - `ecosystem.config.cjs` in the disposable root resolves DATABASE_MODE from-// that root's `.env` exactly like the real file, over fixed test endpoints.+// - the REAL `ecosystem.config.cjs` is copied into the disposable root, so the+// cutover's saved-configuration probe resolves endpoints exactly as PM2 will+// (both test endpoints therefore share one host/user/database, as real ones do).// - a `pg` stub (loaded through a module hook) answers the read-only target// verification: `pg-health` = healthy | unhealthy switches the outcome, and// the reported database/user are the pool's own configuration.// - `launchServer(endpoint)` starts a surrogate ordinary server: the REAL// databaseCutoverHandshake + databaseBootFence against a pool configured// from its environment, then records `server booted` (or `server refused`).-import { appendFileSync, chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+import { appendFileSync, chmodSync, copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';import { spawn } from 'node:child_process';import { join } from 'node:path';import { pathToFileURL } from 'node:url';@@ -19,13 +20,7 @@ const bootFenceUrl = new URL('../../services/databaseBootFence.js', import.meta.export function installCutoverStubs(root, dir, { source, target }) {writeFileSync(join(dir, 'endpoints.json'), JSON.stringify({ [source.mode]: source, [target.mode]: target }));- writeFileSync(join(root, 'ecosystem.config.cjs'), `const fs = require('fs');-const path = require('path');-const endpoints = JSON.parse(fs.readFileSync(${JSON.stringify(join(dir, 'endpoints.json'))}, 'utf8'));-let mode = ${JSON.stringify(source.mode)};-try { mode = /^PGMODE=(\\S+)/m.exec(fs.readFileSync(path.join(__dirname, '.env'), 'utf8'))?.[1] ?? mode; } catch {}-module.exports = { DATABASE_MODE: mode, DATABASE_ENDPOINTS: endpoints };-`);+ copyFileSync(new URL('../../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));const pgStub = join(dir, 'pg-stub.mjs');writeFileSync(pgStub, `import { existsSync, readFileSync } from 'node:fs';