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
feat: stop owned database producers with durable identity readback (#8869)
[._.]/ Adam Eivybd0e14d89b81
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 9329a8850a..dc42d7dcfa 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -283,6 +283,26 @@ not promise that a later request is safe. The future acceptance path must repeatthese checks under its final admission protocol. Missing/unreadable work state,configuration drift, or an existing maintenance fence refuses the check.+The internal `stopOwnedDatabaseProducers` coordinator stage retains the original+PM2 CoS/server identities in the operation's local `producers.json`, stops CoS+before the server by numeric PM2 id, and verifies a fresh daemon read after each+stop. Missing/duplicate/foreign identities, changed live PIDs, unknown lifecycle+states, failed stops, or failed readback keep the operation fenced. Recovery+uses the same recorded operation and original identities; it never changes the+saved backend. Producer shutdown alone does **not** prove child/spawn quiescence+or authorize a dump. Public migration and the inspection-only worker remain+disabled for transfer until descendant reconciliation (#8870), transfer (#8871),+and verified restart (#8851) are integrated.++For stage diagnostics, run `node scripts/database-maintenance.mjs status` and+`node scripts/database-maintenance.mjs writers`. `accepted` means no transfer+has begun; `quiescing` requires retained producer and child reconciliation+evidence. Do not remove the fence, erase `producers.json`, probe a PID to infer+ownership, or reverse source/target. There is no user-callable resume or bypass+for the unfinished transfer stages. A same-operation internal successor requires+the prior detached supervisor's durable exit receipt and must repeat shutdown+readback before any subsequent transfer stage.+Keep the existing backend selected and use backups until the coordinatedoffline cutover is available (tracked in #8797 / #8805). A safe cutover requiresdowntime for **all** PortOS writers, including the CoS runner, and verificationdiff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex b58ede40ef..23744ae071 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -29,6 +29,15 @@ const coordinatorSchema = z.object({token: z.string().uuid(),}).strict();const successorSchema = coordinatorSchema.extend({ previousToken: z.string().uuid() });+const producerSnapshotSchema = z.object({+ id: z.string().uuid(),+ producers: z.array(z.object({+ name: z.enum(['portos-cos', 'portos-server']),+ pmId: z.number().int().nonnegative(), pid: z.number().int().nonnegative(),+ cwd: z.string().min(1), script: z.string().min(1),+ status: z.enum(['online', 'stopped']),+ }).strict()).length(2),+}).strict();const decisionSchema = coordinatorSchema.extend({stage: z.enum(stages),action: z.discriminatedUnion('kind', [@@ -259,6 +268,33 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return current;};+ // Retain the pre-stop producer identities across same-operation recovery.+ // Partial publication is never interpreted as an empty producer set.+ const readProducerSnapshot = (id, token) => {+ assertCoordinatorWorker(id, token);+ const path = join(activeDir, 'producers.json');+ try {+ if (!lstatSync(path).isFile()) throw databaseMaintenanceError();+ const snapshot = producerSnapshotSchema.parse(JSON.parse(readFileSync(path, 'utf8')));+ if (snapshot.id !== id || new Set(snapshot.producers.map(p => p.name)).size !== 2+ || new Set(snapshot.producers.map(p => p.pmId)).size !== 2) throw databaseMaintenanceError();+ return snapshot.producers;+ } catch (err) {+ if (err.code === 'ENOENT' && read().stage === 'accepted') return null;+ throw databaseMaintenanceError();+ }+ };++ const recordProducerSnapshot = (id, token, producers) => {+ assertNotRealDataWrite(activeDir, 'database maintenance producer inventory');+ assertCoordinatorWorker(id, token);+ if (read().stage !== 'accepted' || readProducerSnapshot(id, token)) throw databaseMaintenanceError();+ const snapshot = producerSnapshotSchema.parse({ id, producers });+ writeDurableExclusive(join(activeDir, 'producers.json'), snapshot);+ syncDirectory(activeDir);+ return readProducerSnapshot(id, token);+ };+// A durable CAS for EACH outgoing (owner, stage) state. Transition and// recovery compete on the SAME file, so a predecessor paused after checking// its token cannot publish a new stage after losing ownership. Interrupted@@ -400,7 +436,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {};return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition,- reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator, assertCoordinatorWorker, enterCoordinatorWorker };+ reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator, assertCoordinatorWorker, enterCoordinatorWorker,+ readProducerSnapshot, recordProducerSnapshot };}const journal = createDatabaseMaintenanceJournal();diff --git a/server/services/README.md b/server/services/README.mdindex e818a2bd42..d88ebbda25 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -6,6 +6,7 @@ image-generation paths below are useful entry points when tracing render jobs.| Module | Responsibility || --- | --- |+| `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. || `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. || `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. || `universeBuilderRender.js` | Universe Builder batch render jobs. |diff --git a/server/services/databaseMaintenanceProducers.js b/server/services/databaseMaintenanceProducers.jsnew file mode 100644index 0000000000..a976ed22eb--- /dev/null+++ b/server/services/databaseMaintenanceProducers.js@@ -0,0 +1,81 @@+import { realpathSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { z } from 'zod';+import { PATHS } from '../lib/paths.js';+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { listMaintenanceProcesses, stopApp } from './pm2.js';++const names = ['portos-cos', 'portos-server'];+const scripts = { 'portos-cos': 'server/cos-runner/index.js', 'portos-server': 'server/start.js' };+const producerSchema = z.object({+ name: z.enum(names), pmId: z.number().int().nonnegative(),+ pid: z.number().int().nonnegative(), status: z.enum(['online', 'stopped']),+ cwd: z.string().min(1), script: z.string().min(1),+}).strict();+const refused = () => new Error('Database producer shutdown refused: ownership or PM2 identity is unverified.');++function validateInventory(rows) {+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row.name !== 'string')) throw refused();+ const root = realpathSync(PATHS.installRoot);+ const producers = names.map(name => {+ const matches = rows.filter(row => row.name === name);+ if (matches.length !== 1) throw refused();+ const row = producerSchema.parse(matches[0]);+ if ((row.status === 'online' ? row.pid <= 0 : row.pid !== 0)+ || realpathSync(row.cwd) !== root+ || realpathSync(resolve(row.cwd, row.script)) !== realpathSync(join(root, scripts[name]))) throw refused();+ return { ...row, cwd: root, script: realpathSync(join(root, scripts[name])) };+ });+ if (new Set(producers.map(row => row.pmId)).size !== names.length) throw refused();+ return producers;+}++function sameIdentities(current, saved) {+ for (const row of current) {+ const original = saved.find(value => value.name === row.name);+ if (!original || row.pmId !== original.pmId || row.cwd !== original.cwd || row.script !== original.script+ || (row.status === 'online' && (original.status !== 'online' || row.pid !== original.pid))) throw refused();+ }+}++/**+ * Internal one-use coordinator worker stage. Stops producers only; descendants+ * and pre-fence admitted spawns still require reconciliation before any dump.+ * No public entrypoint invokes this workflow until the transfer stages ship.+ */+export async function stopOwnedDatabaseProducers(id, token) {+ const journal = createDatabaseMaintenanceJournal();+ const operation = journal.enterCoordinatorWorker(id, token);+ if (!['accepted', 'quiescing'].includes(operation.stage)) throw refused();+ const inventory = async () => {+ journal.assertCoordinatorWorker(id, token);+ const rows = await listMaintenanceProcesses();+ journal.assertCoordinatorWorker(id, token);+ return validateInventory(rows);+ };+ let saved = journal.readProducerSnapshot(id, token);+ const initial = await inventory();+ if (!saved) saved = journal.recordProducerSnapshot(id, token, initial);+ sameIdentities(initial, saved);+ if (operation.stage === 'accepted') journal.transition(id, token, 'accepted', 'quiescing');++ // Stop CoS first so its producer cannot keep submitting work while the server+ // shuts down. Fresh readback of BOTH identities precedes every mutation.+ for (const name of names) {+ const current = await inventory();+ sameIdentities(current, saved);+ const producer = current.find(row => row.name === name);+ if (producer.status === 'stopped') continue;+ journal.assertCoordinatorWorker(id, token);+ const result = await stopApp(producer.pmId);+ journal.assertCoordinatorWorker(id, token);+ if (result?.success !== true) throw refused();+ const stopped = await inventory();+ sameIdentities(stopped, saved);+ if (stopped.find(row => row.name === name).status !== 'stopped') throw refused();+ }+ const final = await inventory();+ sameIdentities(final, saved);+ if (final.some(row => row.status !== 'stopped')) throw refused();+ return { id, stage: 'quiescing', producersStopped: true, quiescenceVerified: false, transferReady: false };+}diff --git a/server/services/databaseMaintenanceProducers.test.js b/server/services/databaseMaintenanceProducers.test.jsnew file mode 100644index 0000000000..fb511bcd99--- /dev/null+++ b/server/services/databaseMaintenanceProducers.test.js@@ -0,0 +1,145 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';++const mocks = vi.hoisted(() => ({ root: '/tmp/example-install', list: vi.fn(), stop: vi.fn() }));+vi.mock('../lib/paths.js', () => ({ PATHS: {+ get installRoot() { return mocks.root; }, get data() { return mocks.root + '/data'; },+} }));+vi.mock('./pm2.js', () => ({ listMaintenanceProcesses: mocks.list, stopApp: mocks.stop }));+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { stopOwnedDatabaseProducers } from './databaseMaintenanceProducers.js';++const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };+const target = { ...source, mode: 'docker', port: 5561 };+let journal;+let operation;+let token;+let rows;++beforeEach(() => {+ mocks.root = mkdtempSync(join(tmpdir(), 'maintenance-producers-'));+ mkdirSync(join(mocks.root, 'server', 'cos-runner'), { recursive: true });+ writeFileSync(join(mocks.root, 'server', 'start.js'), '');+ writeFileSync(join(mocks.root, 'server', 'cos-runner', 'index.js'), '');+ writeFileSync(join(mocks.root, '.portos-disposable-root'), '');+ journal = createDatabaseMaintenanceJournal(join(mocks.root, 'data'));+ rows = [+ { name: 'portos-cos', pmId: 12, pid: 1012, status: 'online', cwd: mocks.root, script: 'server/cos-runner/index.js' },+ { name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: mocks.root, script: 'server/start.js' },+ ];+ mocks.list.mockReset().mockImplementation(async () => rows.map(row => ({ ...row })));+ mocks.stop.mockReset().mockImplementation(async id => {+ expect(journal.read().stage).toBe('quiescing');+ expect(journal.readProducerSnapshot(operation.id, token)).toHaveLength(2);+ expect(() => journal.assertAdmission()).toThrow();+ const row = rows.find(value => value.pmId === id);+ row.status = 'stopped'; row.pid = 0;+ return { success: true };+ });+});+afterEach(() => rmSync(mocks.root, { recursive: true, force: true }));++function begin(from = source, to = target) {+ operation = journal.begin({ source: from, target: to });+ token = journal.acquireCoordinator(operation.id);+ return journal.reserveCoordinatorWorker(operation.id, token);+}++function successor() {+ const oldToken = token;+ writeFileSync(join(mocks.root, 'data', 'database-maintenance', 'worker-' + oldToken, 'exit'), '17\n');+ token = journal.recoverCoordinator(operation.id, oldToken, randomUUID());+ journal.reserveCoordinatorWorker(operation.id, token);+ return oldToken;+}++describe('owned database producer shutdown', () => {+ it.each([[source, target], [target, source]])('stops CoS before server with retained original identities and closed admission', async (from, to) => {+ begin(from, to);+ const result = await stopOwnedDatabaseProducers(operation.id, token);+ expect(result).toEqual({ id: operation.id, stage: 'quiescing', producersStopped: true,+ quiescenceVerified: false, transferReady: false });+ expect(mocks.stop.mock.calls).toEqual([[12], [13]]);+ expect(mocks.list).toHaveBeenCalledTimes(6);+ expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });+ expect(journal.readProducerSnapshot(operation.id, token).map(row => row.pid)).toEqual([1012, 1013]);+ expect(() => journal.assertAdmission()).toThrow();+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ });++ it.each(['unavailable', 'missing', 'duplicate', 'foreign-root', 'foreign-script', 'unknown-status', 'shared-id'])('refuses %s inventory before any stop', async fault => {+ begin();+ if (fault === 'unavailable') mocks.list.mockResolvedValue(null);+ if (fault === 'missing') rows.pop();+ if (fault === 'duplicate') rows.push({ ...rows[0] });+ if (fault === 'foreign-root') rows[0].cwd = tmpdir();+ if (fault === 'foreign-script') rows[0].script = 'server/start.js';+ if (fault === 'unknown-status') rows[0].status = 'launching';+ if (fault === 'shared-id') rows[1].pmId = rows[0].pmId;+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ expect(mocks.stop).not.toHaveBeenCalled();+ expect(journal.read().stage).toBe('accepted');+ expect(() => journal.assertAdmission()).toThrow();+ });++ it.each(['throws', 'false-success', 'unchanged', 'read-failed'])('refuses stop failure %s without transfer', async fault => {+ begin();+ if (fault === 'throws') mocks.stop.mockRejectedValue(new Error('stop refused'));+ if (fault === 'false-success') mocks.stop.mockResolvedValue({ success: false });+ if (fault === 'unchanged') mocks.stop.mockResolvedValue({ success: true });+ if (fault === 'read-failed') mocks.stop.mockImplementation(async () => {+ mocks.list.mockRejectedValue(new Error('daemon unavailable')); return { success: true };+ });+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ expect(mocks.stop).toHaveBeenCalledTimes(1);+ expect(journal.read().stage).toBe('quiescing');+ expect(() => journal.assertAdmission()).toThrow();+ });++ it('resumes only the original operation and retained producer identity after an interrupted stop', async () => {+ begin();+ const stop = mocks.stop.getMockImplementation();+ mocks.stop.mockImplementation(async id => {+ if (id === 13) throw new Error('interrupted');+ return stop(id);+ });+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ const originalSnapshot = readFileSync(join(mocks.root, 'data', 'database-maintenance', 'producers.json'), 'utf8');+ const retired = successor();+ mocks.stop.mockImplementation(stop);+ await expect(stopOwnedDatabaseProducers(operation.id, retired)).rejects.toThrow();+ mocks.stop.mockClear();+ expect(await stopOwnedDatabaseProducers(operation.id, token)).toMatchObject({ producersStopped: true, transferReady: false });+ expect(mocks.stop.mock.calls).toEqual([[13]]);+ expect(readFileSync(join(mocks.root, 'data', 'database-maintenance', 'producers.json'), 'utf8')).toBe(originalSnapshot);+ expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });+ });++ it.each(['pid', 'pmId', 'corrupt-snapshot'])('refuses changed %s on same-operation recovery', async fault => {+ begin();+ mocks.stop.mockRejectedValue(new Error('interrupted'));+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ successor();+ if (fault === 'corrupt-snapshot') writeFileSync(join(mocks.root, 'data', 'database-maintenance', 'producers.json'), '{}');+ else rows[0][fault] += 1;+ mocks.stop.mockClear();+ await expect(stopOwnedDatabaseProducers(operation.id, token)).rejects.toThrow();+ expect(mocks.stop).not.toHaveBeenCalled();+ expect(() => journal.assertAdmission()).toThrow();+ });++ it('rechecks coordinator authority after an in-flight daemon read', async () => {+ begin();+ mocks.list.mockImplementationOnce(async () => {+ successor();+ return rows.map(row => ({ ...row }));+ });+ const retired = token;+ await expect(stopOwnedDatabaseProducers(operation.id, retired)).rejects.toThrow();+ expect(mocks.stop).not.toHaveBeenCalled();+ expect(journal.read().stage).toBe('accepted');+ });+});diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 8979dae0a9..24c3eb427a 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -544,6 +544,23 @@ export async function listProcessesStrict(pm2Home = null) {return list.map(mapProcess);}+/** Internal maintenance inventory: fresh daemon read, no UI cache or env dump. */+export async function listMaintenanceProcesses() {+ return connectAndRun(pm2 => new Promise((resolve, reject) => {+ pm2.list((err, list) => {+ if (err || !Array.isArray(list)) {+ reject(new Error('PM2 maintenance inventory unavailable.'));+ return;+ }+ resolve(list.map(proc => ({+ name: proc?.name, pmId: proc?.pm_id, pid: proc?.pid,+ status: proc?.pm2_env?.status,+ cwd: proc?.pm2_env?.pm_cwd, script: proc?.pm2_env?.pm_exec_path,+ })));+ });+ }));+}+// Shared shaping for listProcesses / listProcessesStrict so the two never drift.function mapProcess(proc) {return {diff --git a/server/services/pm2.maintenanceInventory.test.js b/server/services/pm2.maintenanceInventory.test.jsnew file mode 100644index 0000000000..f19cab29e9--- /dev/null+++ b/server/services/pm2.maintenanceInventory.test.js@@ -0,0 +1,27 @@+import { afterEach, expect, it, vi } from 'vitest';+const mocks = vi.hoisted(() => ({ connect: vi.fn(), list: vi.fn(), disconnect: vi.fn() }));+vi.mock('pm2', () => ({ default: mocks }));+import { clearJlistCache, listMaintenanceProcesses, listProcessesStrict } from './pm2.js';++afterEach(() => { vi.clearAllMocks(); clearJlistCache(); });++it('reads fresh maintenance identities even while the display inventory remains cached', async () => {+ mocks.connect.mockImplementation(cb => setImmediate(() => cb(null)));+ const original = { name: 'portos-server', pm_id: 13, pid: 1013,+ pm2_env: { status: 'online', pm_cwd: '/tmp/example-install', pm_exec_path: '/tmp/example-install/server/start.js', secret: 'not-projected' } };+ mocks.list.mockImplementation(cb => setImmediate(() => cb(null, [original])));+ expect((await listProcessesStrict())[0].status).toBe('online');+ mocks.list.mockImplementation(cb => setImmediate(() => cb(null, [{ ...original, pid: 0, pm2_env: { ...original.pm2_env, status: 'stopped' } }])));+ expect(await listMaintenanceProcesses()).toEqual([{ name: 'portos-server', pmId: 13, pid: 0,+ status: 'stopped', cwd: '/tmp/example-install', script: '/tmp/example-install/server/start.js' }]);+ expect(mocks.list).toHaveBeenCalledTimes(2);+});++it('rejects malformed or failed daemon reads instead of declaring an empty producer set', async () => {+ mocks.connect.mockImplementation(cb => setImmediate(() => cb(null)));+ mocks.list.mockImplementation(cb => setImmediate(() => cb(null, null)));+ await expect(listMaintenanceProcesses()).rejects.toThrow('unavailable');+ mocks.list.mockImplementation(cb => setImmediate(() => cb(new Error('failed'))));+ await expect(listMaintenanceProcesses()).rejects.toThrow('unavailable');+ expect(mocks.disconnect).toHaveBeenCalledTimes(2);+});