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: preserve exclusive maintenance ownership across recovery (#8850)
[._.]/ Adam Eivyb9da7b15880f
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 1501dcb957..7adfc2d068 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -115,7 +115,13 @@ recorded endpoints, and the running pool before cutover.`data/database-maintenance/operation.json` is `file-primary`, machine-local recovery state: it must be readable before PostgreSQL, including while either backend is unavailable. Its enclosing directory is the admission fence. The versioned record contains an operation UUID, lifecycle stage, timestamp, and explicit source/target connection identities; it contains no password, token, or application records. It is never federated and has no reference seed. Missing state is idle; an incomplete, malformed, unreadable, or newer-version operation stays fenced. No install migration is needed for an initially absent operation.-Coordinator ownership and cancellation share one exclusive durable claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, ownership token, and expected previous stage. Per-stage claims serialize even concurrent calls with the same token. Interrupted claims are never stolen on a timer or inferred PID death, and every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. No lifecycle coordinator or ownership-recovery command is exposed yet. Verification-only server startup can read the recorded target through its actual pool at the `verifying` or `verified` stage; its bounded result is transient, creates no new store, and never advances the journal or reopens admission.+Coordinator ownership and cancellation share one exclusive durable initial claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, current ownership token, and expected previous stage. Immutable stage publications tolerate a retry of the same transition. Every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. Verification-only server startup can read the recorded target through its actual pool at the `verifying` or `verified` stage; its bounded result is transient, creates no new store, and never advances the journal or reopens admission.++The journal also supplies an **internal ownership-recovery foundation**, not a callable transfer workflow. `reserveCoordinatorWorker(id, token)` reserves a one-use `worker-<token>/` directory bound to that operation and owner. A future coordinator launches its worker through `spawnDetached` with this directory and `cleanup: false`. `recoverCoordinator(id, previousToken)` accepts only the recorded operation and current token, at `accepted`, `quiescing`, `exporting`, or `importing`, after the detached supervisor has published a complete numeric `exit` receipt. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success or advance to committing.++There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped: before any export or import, the future execution coordinator must inventory and stop/drain PM2 server and CoS processes, admitted spawns, and owned detached writers, refusing unknown state. It must retain the complete source dump and re-establish quiescence before retrying the same target transaction. Those execution and transfer steps remain tracked by #8850; verified target restart, saved-mode commit, and admission release remain #8851.++For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. An owned operation adds a bounded `coordinator` result: `unregistered` means no worker reservation; `awaiting-exit` means no supervisor completion proof (either running or interrupted); `exited` includes the supervisor exit code. Neither is a transfer-success verdict. Malformed ownership, binding, or exit records fail closed. Only an **unowned accepted** operation can use `node scripts/database-maintenance.mjs cancel <operation-id>` after checking saved source configuration. There is no operator recovery command for an owned/interrupted operation yet: preserve its journal, worker records, source, and any dump; do not delete markers or call `scripts/db.sh migrate` (still refused). No public lifecycle coordinator or ownership-recovery command is exposed by this foundation.A cancelled unowned accepted operation moves to `data/database-maintenance-cancelled/<operation-id>/` as local recovery evidence. These records remain filesystem-backed and included in backups; they are not a growing application collection. Restoring an active journal deliberately restores its fence: do not delete it merely to make startup succeed. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjsindex 9e5fe04b9d..d465494461 100644--- a/scripts/database-maintenance.mjs+++ b/scripts/database-maintenance.mjs@@ -22,7 +22,10 @@ function main() {if (command === 'status' && args.length === 0) {const record = journal.read();// Endpoints are local-only; the operator-facing status needs only direction.- return record ? { id: record.id, stage: record.stage, source: record.source.mode, target: record.target.mode } : { stage: 'idle' };+ if (!record) return { stage: 'idle' };+ const coordinator = journal.coordinatorStatus(record.id);+ return { id: record.id, stage: record.stage, source: record.source.mode, target: record.target.mode,+ ...(coordinator.state === 'unclaimed' ? {} : { coordinator }) };}if (command === 'begin' && args.length === 2) {const [sourceMode, targetMode] = args;diff --git a/server/lib/README.md b/server/lib/README.mdindex 92c746be9c..c0ec88c515 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` | 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. |+| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex 786edc9b28..78e3171734 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -24,6 +24,12 @@ const journalSchema = z.object({target: databaseMaintenanceEndpointSchema,}).strict();+const coordinatorSchema = z.object({+ id: z.string().uuid(),+ token: z.string().uuid(),+}).strict();+const successorSchema = coordinatorSchema.extend({ previousToken: z.string().uuid() });+const normalizedHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase())? 'loopback' : host.toLowerCase();@@ -125,9 +131,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return record;};- // One durable owner for the operation's entire lifetime. Never infer that an- // owner is dead from a PID or elapsed time; interrupted ownership needs an- // explicit recovery protocol before another process may advance the journal.+ // Initial durable owner. Successors require explicit same-operation recovery+ // backed by the detached supervisor's exit receipt, never PID/elapsed time.const acquireCoordinator = (id) => {assertNotRealDataWrite(activeDir, 'database maintenance ownership');const current = read();@@ -140,15 +145,119 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return token;};+ // Recovery appends an immutable successor instead of overwriting ownership.+ // Each predecessor admits exactly one successor, even across processes. A+ // missing/partial worker receipt never authorizes reclaiming an owner.+ const readCoordinator = (id) => {+ const current = read();+ if (!current || current.id !== id) throw databaseMaintenanceError();+ const ownerPath = join(activeDir, 'cancel-' + id + '.claim');+ try { lstatSync(ownerPath); } catch (err) {+ if (err.code === 'ENOENT') return null;+ throw databaseMaintenanceError();+ }+ if (!lstatSync(ownerPath).isFile()) throw databaseMaintenanceError();+ let owner = coordinatorSchema.parse(JSON.parse(readFileSync(ownerPath, 'utf8')));+ if (owner.id !== id) throw databaseMaintenanceError();+ const visited = new Set();+ while (true) {+ if (visited.has(owner.token)) throw databaseMaintenanceError();+ visited.add(owner.token);+ const nextPath = join(activeDir, 'coordinator-after-' + owner.token + '.json');+ try { lstatSync(nextPath); } catch (err) {+ if (err.code === 'ENOENT') return owner;+ throw databaseMaintenanceError();+ }+ if (!lstatSync(nextPath).isFile()) throw databaseMaintenanceError();+ const next = successorSchema.parse(JSON.parse(readFileSync(nextPath, 'utf8')));+ if (next.id !== id || next.previousToken !== owner.token) throw databaseMaintenanceError();+ owner = { id, token: next.token };+ }+ };++ const assertCoordinator = (id, token) => {+ const owner = readCoordinator(id);+ if (!owner || typeof token !== 'string' || owner.token !== token) throw databaseMaintenanceError();+ return owner;+ };++ const workerDirectory = token => join(activeDir, 'worker-' + token);++ // Reserve once, BEFORE spawnDetached. Never reuse this directory: resetting+ // its exit sentinel could let an old supervisor acknowledge a later worker.+ // The caller must use cleanup:false and launch only the coordinator here.+ const reserveCoordinatorWorker = (id, token) => {+ assertNotRealDataWrite(activeDir, 'database maintenance worker reservation');+ const owner = assertCoordinator(id, token);+ const directory = workerDirectory(token);+ mkdirSync(directory, { mode: 0o700 });+ syncDirectory(activeDir);+ writeDurableExclusive(join(directory, 'owner.json'), owner);+ syncDirectory(directory);+ return directory;+ };++ const coordinatorStatus = (id) => {+ const owner = readCoordinator(id);+ if (!owner) return { state: 'unclaimed' };+ const directory = workerDirectory(owner.token);+ try { lstatSync(directory); } catch (err) {+ if (err.code === 'ENOENT') return { state: 'unregistered' };+ throw databaseMaintenanceError();+ }+ if (!lstatSync(directory).isDirectory()) throw databaseMaintenanceError();+ const bindingPath = join(directory, 'owner.json');+ if (!lstatSync(bindingPath).isFile()) throw databaseMaintenanceError();+ const binding = coordinatorSchema.parse(JSON.parse(readFileSync(bindingPath, 'utf8')));+ if (binding.id !== id || binding.token !== owner.token) throw databaseMaintenanceError();+ const exitPath = join(directory, 'exit');+ try { lstatSync(exitPath); } catch (err) {+ if (err.code === 'ENOENT') return { state: 'awaiting-exit' };+ throw databaseMaintenanceError();+ }+ if (!lstatSync(exitPath).isFile()) throw databaseMaintenanceError();+ const raw = readFileSync(exitPath, 'utf8');+ if (!/^-?\d{1,10}\r?\n?$/.test(raw)) throw databaseMaintenanceError();+ const exitCode = Number(raw.trim());+ if (!Number.isSafeInteger(exitCode) || exitCode < -2147483648 || exitCode > 4294967295) throw databaseMaintenanceError();+ return { state: 'exited', exitCode };+ };++ // This transfers journal ownership only, NEVER database authority. Before+ // export/import a successor must re-establish writer/child quiescence: the+ // worker's exit says nothing about descendants it might have left behind.+ // No PID probe, clock, reverse operation, or source-success inference occurs.+ const recoverCoordinator = (id, previousToken) => {+ assertNotRealDataWrite(activeDir, 'database maintenance coordinator recovery');+ assertCoordinator(id, previousToken);+ const current = read();+ if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(current.stage)+ || coordinatorStatus(id).state !== 'exited') throw databaseMaintenanceError();+ const directory = workerDirectory(previousToken);+ const fd = openSync(join(directory, 'exit'), 'r+');+ try { fsyncSync(fd); } finally { closeSync(fd); }+ syncDirectory(directory);+ const next = { id, token: randomUUID(), previousToken };+ const pending = join(activeDir, 'coordinator-' + next.token + '.pending');+ writeDurableExclusive(pending, next);+ try {+ // EEXIST is a LOST recovery race, unlike an idempotent stage publication:+ // the winner owns a different token and this caller must not execute.+ linkSync(pending, join(activeDir, 'coordinator-after-' + previousToken + '.json'));+ } finally {+ unlinkSync(pending);+ }+ syncDirectory(activeDir);+ assertCoordinator(id, next.token);+ return next.token;+ };+const transition = (id, token, expectedStage, nextStage) => {assertNotRealDataWrite(activeDir, 'database maintenance transition');const current = read();if (!current || current.id !== id || !stages.includes(expectedStage)|| stages.indexOf(nextStage) !== stages.indexOf(expectedStage) + 1) throw databaseMaintenanceError();- const ownerPath = join(activeDir, 'cancel-' + id + '.claim');- if (!lstatSync(ownerPath).isFile()) throw databaseMaintenanceError();- const owner = JSON.parse(readFileSync(ownerPath, 'utf8'));- if (typeof token !== 'string' || owner.id !== id || owner.token !== token) throw databaseMaintenanceError();+ assertCoordinator(id, token);// An acknowledged publication may have crashed before returning to its// caller. Only that exact owned transition is idempotent, never a reversal.if (current.stage === nextStage) {@@ -203,7 +312,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return { id, stage: 'cancelled' };};- return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition };+ return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition,+ reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator };}const journal = createDatabaseMaintenanceJournal();diff --git a/server/lib/databaseMaintenanceRecovery.test.js b/server/lib/databaseMaintenanceRecovery.test.jsnew file mode 100644index 0000000000..f826e62974--- /dev/null+++ b/server/lib/databaseMaintenanceRecovery.test.js@@ -0,0 +1,154 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { spawn } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';+import { spawnDetached } from './detachedSpawn.js';++const moduleUrl = new URL('./databaseMaintenanceJournal.js', import.meta.url).href;+const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };+const target = { ...source, mode: 'docker', port: 5561 };+let root;+let data;+let journal;+let children;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'portos-coordinator-'));+ data = join(root, 'data');+ writeFileSync(join(root, '.portos-disposable-root'), '');+ journal = createDatabaseMaintenanceJournal(data);+ children = [];+});+afterEach(async () => {+ for (const child of children) {+ if (!child.finished) child.handle.kill('SIGKILL');+ await child.done;+ }+ rmSync(root, { recursive: true, force: true });+});++async function launchWorker(operation, token, stage = 'importing') {+ const controlDir = journal.reserveCoordinatorWorker(operation.id, token);+ const script = join(root, `worker-${token}.mjs`);+ writeFileSync(script, `import {writeFileSync, existsSync} from 'node:fs';+ import {setTimeout} from 'node:timers/promises';+ import {createDatabaseMaintenanceJournal} from ${JSON.stringify(moduleUrl)};+ const journal=createDatabaseMaintenanceJournal(${JSON.stringify(data)});+ const stages=['accepted','quiescing','exporting','importing'];+ while(journal.read().stage!==${JSON.stringify(stage)}) {+ const current=journal.read().stage;+ journal.transition(${JSON.stringify(operation.id)},${JSON.stringify(token)},current,stages[stages.indexOf(current)+1]);+ }+ writeFileSync(${JSON.stringify(join(controlDir, 'ready'))},'ready');+ while(!existsSync(${JSON.stringify(join(controlDir, 'finish'))})) await setTimeout(20);+ process.exitCode=17;+ `);+ const env = { ...process.env, PORTOS_DATA_ROOT: root, NODE_ENV: 'test' };+ delete env.VITEST;+ const handle = await spawnDetached(process.execPath, [script], { env, controlDir, cleanup: false, pollMs: 25 });+ const child = { handle, finished: false };+ child.done = new Promise((resolve, reject) => {+ handle.once('close', (code, signal) => { child.finished = true; resolve({ code, signal }); });+ handle.once('error', err => { child.finished = true; reject(err); });+ });+ // Attach a rejection observer immediately; teardown still awaits the result.+ child.done.catch(() => {});+ children.push(child);+ await vi.waitFor(() => expect(readFileSync(join(controlDir, 'ready'), 'utf8')).toBe('ready'), { timeout: 20_000 });+ return { ...child, controlDir };+}++function recoveryProcess(operation, token) {+ const code = `import {createDatabaseMaintenanceJournal} from ${JSON.stringify(moduleUrl)};+ try {console.log(createDatabaseMaintenanceJournal(${JSON.stringify(data)}).recoverCoordinator(${JSON.stringify(operation.id)},${JSON.stringify(token)}));}+ catch {process.exitCode=1;}`;+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ child.stdout.on('data', chunk => { stdout += chunk; });+ child.once('error', reject);+ child.once('close', status => resolve({ status, token: stdout.trim() }));+ });+}++describe('same-operation coordinator recovery', () => {+ it.each([[source, target], [target, source]])('recovers an exited detached worker without changing direction, stage, or admission', async (from, to) => {+ const operation = journal.begin({ source: from, target: to });+ const token = journal.acquireCoordinator(operation.id);+ const worker = await launchWorker(operation, token);+ // A paused import is not a recoverable dead owner, however old its PID or+ // timestamps appear. Only the supervisor's completed exit receipt counts.+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.reserveCoordinatorWorker(operation.id, token)).toThrow();+ expect(() => journal.assertAdmission()).toThrow();+ writeFileSync(join(worker.controlDir, 'finish'), '');+ expect(await worker.done).toEqual({ code: 17, signal: null });+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'exited', exitCode: 17 });++ const outcomes = await Promise.all([recoveryProcess(operation, token), recoveryProcess(operation, token)]);+ expect(outcomes.map(item => item.status).sort()).toEqual([0, 1]);+ const successor = outcomes.find(item => item.status === 0).token;+ expect(successor).not.toBe(token);+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });+ expect(() => journal.transition(operation.id, token, 'importing', 'committing')).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.begin({ source: to, target: from })).toThrow();+ expect(() => journal.cancel(operation.id, from)).toThrow();+ expect(() => journal.assertAdmission()).toThrow();+ // Original supervisor evidence is retained, never truncated for a retry.+ expect(readFileSync(join(worker.controlDir, 'exit'), 'utf8').trim()).toBe('17');+ const nextDirectory = journal.reserveCoordinatorWorker(operation.id, successor);+ expect(nextDirectory).not.toBe(worker.controlDir);+ // No worker was launched into the new reservation; recovery cannot invent+ // success from a missing/dead PID, even on repeated attempts.+ writeFileSync(join(nextDirectory, 'pid'), '2147483647');+ expect(() => journal.recoverCoordinator(operation.id, successor)).toThrow();+ }, 40_000);++ it('recovers a killed worker only after its supervisor acknowledges exit', async () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ const worker = await launchWorker(operation, token, 'exporting');+ worker.handle.kill('SIGKILL');+ await worker.done;+ const next = journal.recoverCoordinator(operation.id, token);+ expect(next).not.toBe(token);+ expect(journal.read()).toEqual({ ...operation, stage: 'exporting' });+ expect(() => journal.assertAdmission()).toThrow();+ }, 40_000);++ it('refuses absent, partial, foreign, or damaged completion evidence and preserves the fence', () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ const controlDir = journal.reserveCoordinatorWorker(operation.id, token);+ for (const value of ['', 'success', '0 trailing', '99999999999', '1\n0']) {+ writeFileSync(join(controlDir, 'exit'), value);+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ }+ writeFileSync(join(controlDir, 'exit'), '0\n');+ writeFileSync(join(controlDir, 'owner.json'), JSON.stringify({ id: operation.id, token: '00000000-0000-4000-8000-000000000000' }));+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(journal.read()).toEqual(operation);+ expect(() => journal.assertAdmission()).toThrow();+ });++ it('does not let a stale predecessor or later-stage recovery reopen an operation', () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ const directory = journal.reserveCoordinatorWorker(operation.id, token);+ writeFileSync(join(directory, 'exit'), '0');+ let current = 'accepted';+ for (const next of ['quiescing', 'exporting', 'importing', 'committing']) {+ journal.transition(operation.id, token, current, next);+ current = next;+ }+ expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(journal.read().stage).toBe('committing');+ expect(() => journal.assertAdmission()).toThrow();+ });+});