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: persist database maintenance admission across processes (#8809)
[._.]/ Adam Eivybc2b12be8251
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 6f2f93a265..406e8e8c7c 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -209,3 +209,28 @@ failure. Subsequent partial settings saves preserve restored fields. Transfererrors still report that files may have been overwritten; a cache-reload failurerequires restarting PortOS before using CoS. Dry runs and selective restoresoutside the CoS state/config scope do not acquire this boundary.++## Database maintenance admission++The persistent maintenance boundary is a prerequisite for coordinated offline migration (#8805). It does **not** migrate data, change saved mode, stop existing writer processes, or prove a target cutover. In particular, entering maintenance is not permission to invoke an uncoordinated SQL import or backend migration.++From the install root, inspect or establish the fence:++```sh+node scripts/database-maintenance.mjs status+node scripts/database-maintenance.mjs begin native docker+# Or, when the saved source mode is Docker:+node scripts/database-maintenance.mjs begin docker native+```++The command returns the operation ID and direction. Plan for downtime: new pooled database operations and CoS spawn admission are refused immediately, and both managed server and runner refuse normal boot while fenced. Already-admitted transactions may finish; this boundary alone is **not a drained snapshot boundary**. The offline coordinator must still stop/drain all owned writers and validate live/spawning work before export. A process-local restore callback cannot bypass this persistent fence.++If no transfer has started and saved source configuration is unchanged, cancel using that exact ID:++```sh+node scripts/database-maintenance.mjs cancel <operation-id>+```++Cancellation supports only the initial accepted stage, preserves the journal in the machine-local cancelled archive, and never switches mode or reverses direction. Restart managed processes through the existing PM2 ecosystem workflow after cancellation if their normal boot was refused. CLI configuration follows the ecosystem's environment precedence; run from the same configured operator environment. Changed source configuration, a different operation ID, an unknown stage/version, and a competing operation are refused.++An incomplete publication or interrupted cancellation remains fenced. Do not remove the active directory, steal its cancellation claim, or guess a backend from `.env`: retain the journal for recovery. This first boundary deliberately supplies no transfer-stage resume/rollback command; the detached coordinator and verified restart protocol are tracked in #8810, and Settings recovery feedback in #8811. Normal startup and migration must not be re-enabled by treating this preparatory operation as a completed cutover.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 2d6e33fb80..06867a2349 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -96,6 +96,12 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](---+### Database maintenance journal++`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, accepted 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.++A cancelled 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.+## `asset-file-db-indexed` — bytes on disk, metadata in DB**Definition.** Large binary payloads (images, video, audio, model weights) stay on disk as bytes, while their **searchable metadata** — provenance, gen params, favorites, notes, lineage, collection membership — lives in PostgreSQL as asset rows that reference the file by a stable key.diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjsnew file mode 100644index 0000000000..aa418cbedd--- /dev/null+++ b/scripts/database-maintenance.mjs@@ -0,0 +1,63 @@+#!/usr/bin/env node+// Operator interface for the admission boundary. This does NOT transfer data,+// stop existing writers, change mode, or authorize invoking db.sh migrate.+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { join } from 'node:path';+import { PATHS } from '../server/lib/paths.js';+import { createDatabaseMaintenanceJournal } from '../server/lib/databaseMaintenanceJournal.js';++const journal = createDatabaseMaintenanceJournal();+const require = createRequire(import.meta.url);++function configuredSource() {+ const text = (() => {+ try { return readFileSync(join(PATHS.installRoot, '.env'), 'utf8'); }+ catch (err) { if (err.code === 'ENOENT') return ''; throw err; }+ })();+ const mode = text.match(/^PGMODE=(\S+)/m)?.[1] || 'docker';+ const config = require(join(PATHS.installRoot, 'ecosystem.config.cjs'));+ const env = config.apps.find(app => app.name === 'portos-server')?.env;+ if (!env || !['native', 'docker'].includes(mode)) throw new Error('Database configuration is not a supported backend.');+ return { mode, host: env.PGHOST, port: Number(env.PGPORT), database: env.PGDATABASE, user: env.PGUSER };+}++function main() {+ const [command, ...args] = process.argv.slice(2);+ 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 (command === 'begin' && args.length === 2) {+ const [sourceMode, targetMode] = args;+ const source = configuredSource();+ if (source.mode !== sourceMode || !['native', 'docker'].includes(targetMode) || targetMode === sourceMode) {+ throw new Error('Explicit source/target must match saved mode and name different backends.');+ }+ // Target ports are resolved from the saved mode-specific override, never+ // from the current process PGPORT (which belongs to the SOURCE).+ const text = (() => {+ try { return readFileSync(join(PATHS.installRoot, '.env'), 'utf8'); }+ catch (err) { if (err.code === 'ENOENT') return ''; throw err; }+ })();+ const key = targetMode === 'native' ? 'PGPORT' : 'PGPORT_DOCKER';+ const port = Number(text.match(new RegExp('^' + key + '=(\\S+)', 'm'))?.[1] || (targetMode === 'native' ? 5432 : 5561));+ const record = journal.begin({ source, target: { ...source, mode: targetMode, port } });+ return { id: record.id, stage: record.stage, source: sourceMode, target: targetMode };+ }+ if (command === 'cancel' && args.length === 1) {+ return journal.cancel(args[0], configuredSource());+ }+ throw new Error('Usage: node scripts/database-maintenance.mjs status | begin <native|docker> <native|docker> | cancel <operation-id>');+}++try {+ console.log(JSON.stringify(main()));+} catch (err) {+ // No filesystem paths, connection details, or raw parser inputs in output.+ console.error(err.code === 'DATABASE_MAINTENANCE'+ ? 'Database maintenance is fenced; journal recovery is required.'+ : 'Database maintenance command refused. Check arguments, saved configuration, and operation identity; an existing or interrupted operation is never overwritten.');+ process.exitCode = 1;+}diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 060c7e9fc5..29e7a545d9 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -1,3 +1,4 @@+import '../services/databaseBootFence.js';/*** CoS Agent Runner - Standalone PM2 Process*@@ -9,6 +10,7 @@*/import express from 'express';+import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';import { spawn } from '../lib/childProcess.js';import * as pty from 'node-pty';import { join, basename } from 'path';@@ -200,6 +202,7 @@ app.get('/agents', async (req, res) => {* restarts before the TUI exits.*/app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {+ assertDatabaseAdmission();const {agentId,taskId,@@ -284,6 +287,7 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {// the actual fault instead, and let the caller block on the unrecoverable ones.let tuiProcess;try {+ assertDatabaseAdmission();tuiProcess = pty.spawn(ptyCommand, ptyArgs, {name: 'xterm-256color',cols,@@ -406,6 +410,7 @@ app.get('/agents/:agentId/stats', async (req, res) => {* Spawn a new agent*/app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {+ assertDatabaseAdmission();const {agentId,taskId,@@ -499,6 +504,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {}// Spawn the CLI process+ assertDatabaseAdmission();const claudeProcess = spawn(spawnCommand, finalSpawnArgs, {cwd,shell: false,diff --git a/server/index.js b/server/index.jsindex b1cd4b92d6..9540b01864 100644--- a/server/index.js+++ b/server/index.js@@ -1,3 +1,4 @@+import './services/databaseBootFence.js';import express from 'express';import { Server } from 'socket.io';import { fileURLToPath } from 'url';diff --git a/server/lib/README.md b/server/lib/README.mdindex 4ff5de8696..d12fd3f34c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -765,3 +765,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `launchVideoValidation.js` | `validateLaunchVideoAssets` checks frozen launch composition text, storyboard reading time, duration, and poster position before rendering. || `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 immutable accepted-operation journal; source-only cancellation archives the operation. |diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsnew file mode 100644index 0000000000..cd9a123159--- /dev/null+++ b/server/lib/databaseMaintenanceJournal.js@@ -0,0 +1,134 @@+import { existsSync, lstatSync, mkdirSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { z } from 'zod';+import { PATHS } from './paths.js';++const endpointSchema = z.object({+ mode: z.enum(['native', 'docker']),+ host: z.string().min(1).max(255),+ port: z.number().int().min(1).max(65535),+ database: z.string().min(1).max(63),+ user: z.string().min(1).max(63),+}).strict();++const journalSchema = z.object({+ version: z.literal(1),+ id: z.string().uuid(),+ stage: z.literal('accepted'),+ createdAt: z.string().datetime(),+ source: endpointSchema,+ target: endpointSchema,+}).strict();++const normalizedHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase())+ ? 'loopback' : host.toLowerCase();++const databaseMaintenanceError = () => Object.assign(+ new Error('Persistent database maintenance is active or requires recovery. Inspect scripts/database-maintenance.mjs status.'),+ { status: 503, code: 'DATABASE_MAINTENANCE' },+);++function syncDirectory(path) {+ // Windows does not expose directory fsync through Node. The fence still+ // exists before journal publication; unreadable/incomplete state fails shut.+ if (process.platform === 'win32') return;+ const fd = openSync(path, 'r');+ try { fsyncSync(fd); } finally { closeSync(fd); }+}++function writeDurableExclusive(path, value) {+ const fd = openSync(path, 'wx', 0o600);+ try {+ writeFileSync(fd, JSON.stringify(value, null, 2) + '\n');+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+}++/**+ * The DIRECTORY is the fence, not a successfully parsed journal. In particular,+ * a crash between mkdir and journal publication must never reopen admission.+ * Synchronous checks keep admission before the first pool checkout/await.+ */+export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {+ const activeDir = join(dataDir, 'database-maintenance');+ const recordPath = join(activeDir, 'operation.json');++ const isFenced = () => {+ try {+ // Unlike existsSync, lstat distinguishes missing from unreadable and+ // treats a dangling symlink as a fence, not a missing operation.+ lstatSync(activeDir);+ return true;+ } catch (err) {+ return err.code !== 'ENOENT';+ }+ };++ const assertAdmission = () => {+ if (isFenced()) throw databaseMaintenanceError();+ };++ const read = () => {+ if (!isFenced()) return null;+ try {+ return journalSchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));+ } catch {+ throw databaseMaintenanceError();+ }+ };++ const begin = ({ source, target }) => {+ const record = journalSchema.parse({+ version: 1, id: randomUUID(), stage: 'accepted',+ createdAt: new Date().toISOString(), source, target,+ });+ if (source.mode === target.mode ||+ (normalizedHost(source.host) === normalizedHost(target.host) && source.port === target.port)) {+ throw new Error('Database maintenance requires distinct source and target backends.');+ }+ mkdirSync(dataDir, { recursive: true });+ // Exclusive mkdir is also the cross-process begin lock. No rollback on a+ // failed publication: leaving the fence closed is the recoverable outcome.+ mkdirSync(activeDir, { mode: 0o700 });+ syncDirectory(dataDir);+ const temporary = join(activeDir, 'operation.pending');+ writeDurableExclusive(temporary, record);+ renameSync(temporary, recordPath);+ syncDirectory(activeDir);+ return record;+ };++ const cancel = (id, source) => {+ // A per-operation exclusive cancellation claim prevents two cancellations+ // from renaming a later operation after the first has released this one.+ // An interrupted cancellation leaves this marker and fails closed; it must+ // 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);+ if (JSON.stringify(initial.source) !== JSON.stringify(parsedSource)) {+ throw new Error('Saved database endpoint changed; source-only cancellation refused.');+ }+ writeDurableExclusive(join(activeDir, 'cancel-' + id + '.claim'), { id });+ const current = read();+ if (current.id !== id || current.stage !== 'accepted') throw databaseMaintenanceError();+ const archiveDir = join(dataDir, 'database-maintenance-cancelled');+ mkdirSync(archiveDir, { recursive: true, mode: 0o700 });+ // Archive before reopening admission; retain the operation's direction as+ // local recovery evidence. Never remove/overwrite an existing archive.+ const destination = join(archiveDir, id);+ if (existsSync(destination)) throw databaseMaintenanceError();+ renameSync(activeDir, destination);+ syncDirectory(archiveDir);+ syncDirectory(dataDir);+ return { id, stage: 'cancelled' };+ };++ return { isFenced, assertAdmission, read, begin, cancel };+}++const journal = createDatabaseMaintenanceJournal();+export const assertDatabaseAdmission = journal.assertAdmission;diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.jsnew file mode 100644index 0000000000..4c19da784d--- /dev/null+++ b/server/lib/databaseMaintenanceJournal.test.js@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { spawn, spawnSync } from 'node:child_process';+import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';++const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };+const target = { ...source, mode: 'docker', port: 5561 };+const moduleUrl = new URL('./databaseMaintenanceJournal.js', import.meta.url).href;+let root;+let data;+let journal;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'portos-maintenance-'));+ data = join(root, 'data');+ writeFileSync(join(root, '.portos-disposable-root'), '');+ journal = createDatabaseMaintenanceJournal(data);+});+afterEach(() => rmSync(root, { recursive: true, force: true }));++function node(code, args = []) {+ return spawnSync(process.execPath, [...args, '--input-type=module', '-e', code], {+ encoding: 'utf8',+ env: { ...process.env, PORTOS_DATA_ROOT: root, PGDATABASE: 'example_test', PGPASSWORD: 'example-only' },+ timeout: 10_000,+ });+}++describe('persistent database maintenance boundary', () => {+ it('publishes once across competing processes and preserves the winning direction', async () => {+ const code = `import { createDatabaseMaintenanceJournal } from ${JSON.stringify(moduleUrl)};+ const j = createDatabaseMaintenanceJournal(${JSON.stringify(data)});+ try { console.log(JSON.stringify(j.begin(${JSON.stringify({ source, target })}))); }+ catch { process.exitCode = 1; }`;+ const run = () => new Promise(resolve => {+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: ['ignore', 'pipe', 'pipe'] });+ child.once('close', code => resolve(code));+ });+ expect((await Promise.all([run(), run()])).sort()).toEqual([0, 1]);+ const record = journal.read();+ expect(record).toMatchObject({ stage: 'accepted', source, target });+ expect(() => journal.begin({ source: target, target: source })).toThrow();+ expect(journal.read()).toEqual(record);+ });++ it('blocks a fresh database process, boot graphs, and agent admission while preserving journal identity', () => {+ const operation = journal.begin({ source, target });+ // No real pg connection is possible, even if an admission regression occurs.+ const loader = join(root, 'pg-loader.mjs');+ const stub = `export default {types:{setTypeParser(){}},Pool:class {+ on(){} query(){throw Error('POOL_REACHED')} connect(){throw Error('POOL_REACHED')}+ }};`;+ writeFileSync(loader, `export async function resolve(specifier, context, next) {+ if (specifier === 'pg') return {url: ${JSON.stringify('data:text/javascript,' + encodeURIComponent(stub))}, shortCircuit:true};+ return next(specifier, context);+ }`);+ const dbUrl = new URL('./db.js', import.meta.url).href;+ const guardsUrl = new URL('../services/agentGuards.js', import.meta.url).href;+ const code = `import {query, withTransaction, withDatabaseMaintenance, ensureSchema} from ${JSON.stringify(dbUrl)};+ import {withSpawnDedupGuard} from ${JSON.stringify(guardsUrl)};+ const outcomes = [];+ for (const call of [+ () => query('INSERT INTO example_record VALUES (1)'),+ () => withTransaction(() => {throw Error('CALLER_REACHED')}),+ () => withDatabaseMaintenance(() => query('SELECT 1')),+ () => ensureSchema(),+ () => withSpawnDedupGuard(new Set(), 'example', () => {throw Error('SPAWN_REACHED')})+ ]) { try { await call(); outcomes.push('unexpected'); } catch(e) {outcomes.push(e.code || e.message);} }+ console.log(JSON.stringify(outcomes));`;+ // A second invocation is a restarted process, not a module-cache reset.+ for (let attempt = 0; attempt < 2; attempt++) {+ const result = node(code, ['--loader', pathToFileURL(loader).href]);+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout.trim())).toEqual(Array(5).fill('DATABASE_MAINTENANCE'));+ }+ const bootUrl = new URL('../services/databaseBootFence.js', import.meta.url).href;+ const boot = node(`try {await import(${JSON.stringify(bootUrl)}); process.exitCode=2;}+ catch(e) {console.log(e.code);}`);+ expect(boot.status, boot.stderr).toBe(0);+ expect(boot.stdout.trim()).toBe('DATABASE_MAINTENANCE');+ expect(journal.read().id).toBe(operation.id);+ });++ it('lets an admitted transaction finish but refuses new work after another process fences it', () => {+ const loader = join(root, 'transaction-loader.mjs');+ const stub = `const log=[]; globalThis.sqlLog=log; export default {+ types:{setTypeParser(){}},Pool:class {+ on(){} async connect(){return {query:async sql=>{log.push(sql); return {rows:[]}},release(){}}}+ query(){throw Error('NEW_QUERY_REACHED')}+ }};`;+ writeFileSync(loader, `export async function resolve(s,c,n) {+ return s==='pg'?{url:${JSON.stringify('data:text/javascript,'+encodeURIComponent(stub))},shortCircuit:true}:n(s,c);+ }`);+ const code = `import {spawnSync} from 'node:child_process';+ import {withTransaction,query} from ${JSON.stringify(new URL('./db.js', import.meta.url).href)};+ await withTransaction(async client=>{+ const result=spawnSync(process.execPath,['--input-type=module','-e',+ ${JSON.stringify('import {createDatabaseMaintenanceJournal} from '+JSON.stringify(moduleUrl)+'; createDatabaseMaintenanceJournal('+JSON.stringify(data)+').begin('+JSON.stringify({source,target})+');')}]);+ if(result.status!==0) throw Error('FENCE_FAILED');+ await client.query('INSERT INTO example_record VALUES (1)');+ try {await query('INSERT INTO example_record VALUES (2)'); throw Error('NEW_WRITE_ACCEPTED')}+ catch(e){if(e.code!=='DATABASE_MAINTENANCE') throw e}+ });+ console.log(JSON.stringify(globalThis.sqlLog));`;+ const result = node(code, ['--loader', pathToFileURL(loader).href]);+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout.trim())).toEqual(['BEGIN', 'INSERT INTO example_record VALUES (1)', 'COMMIT']);+ expect(journal.isFenced()).toBe(true);+ });++ it('fails closed across interrupted publication and damaged or future journals', () => {+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();+ mkdirSync(join(data, 'database-maintenance'), { recursive: true });+ expect(() => journal.assertAdmission()).toThrowError(expect.objectContaining({ code: 'DATABASE_MAINTENANCE' }));+ expect(() => journal.read()).toThrow();+ for (const body of ['{', JSON.stringify({ version: 2 }), JSON.stringify({ stage: 'verified' })]) {+ writeFileSync(join(data, 'database-maintenance', 'operation.json'), body);+ expect(() => journal.read()).toThrow();+ expect(() => journal.assertAdmission()).toThrow();+ expect(() => journal.cancel('unknown', source)).toThrow();+ }+ });++ it('cancels only an accepted matching source and retains the immutable operation as local evidence', () => {+ const operation = journal.begin({ source, target });+ expect(() => journal.cancel('00000000-0000-4000-8000-000000000000', source)).toThrow();+ expect(() => journal.cancel(operation.id, target)).toThrow();+ expect(() => journal.cancel(operation.id, { ...source, port: 6000 })).toThrow();+ expect(journal.read()).toEqual(operation);+ expect(journal.cancel(operation.id, source)).toEqual({ id: operation.id, stage: 'cancelled' });+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();+ const archived = join(data, 'database-maintenance-cancelled', operation.id, 'operation.json');+ expect(JSON.parse(readFileSync(archived, 'utf8'))).toEqual(operation);+ const next = journal.begin({ source: target, target: source });+ expect(next.id).not.toBe(operation.id);+ expect(() => journal.cancel(operation.id, source)).toThrow();+ expect(journal.read()).toEqual(next);+ });++ it('does not reopen admission after an interrupted cancellation or an unknown transfer stage', () => {+ const operation = journal.begin({ source, target });+ const active = join(data, 'database-maintenance');+ writeFileSync(join(active, 'cancel-' + operation.id + '.claim'), '{}');+ expect(() => journal.cancel(operation.id, source)).toThrow();+ expect(journal.isFenced()).toBe(true);+ writeFileSync(join(active, 'operation.json'), JSON.stringify({ ...operation, stage: 'importing' }));+ expect(() => journal.cancel(operation.id, source)).toThrow();+ expect(readdirSync(data)).toEqual(['database-maintenance']);+ });++ it('drives the operator CLI against disposable saved configuration without touching PostgreSQL', () => {+ copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));+ const config = 'PGMODE=native\nPGPORT=6543\nPGPORT_DOCKER=6544\n';+ writeFileSync(join(root, '.env'), config);+ const cli = new URL('../../scripts/database-maintenance.mjs', import.meta.url);+ const run = (...args) => spawnSync(process.execPath, [fileURLToPath(cli), ...args], {+ encoding: 'utf8', timeout: 10_000,+ env: { ...process.env, PORTOS_DATA_ROOT: root, PGPORT: '', PGPORT_DOCKER: '',+ PGHOST: 'localhost', PGUSER: 'example', PGDATABASE: 'example_test', PGPASSWORD: 'example-only' },+ });+ expect(JSON.parse(run('status').stdout)).toEqual({ stage: 'idle' });+ expect(run('begin', 'docker', 'native').status).toBe(1);+ const started = run('begin', 'native', 'docker');+ expect(started.status, started.stderr).toBe(0);+ const operation = JSON.parse(started.stdout);+ expect(journal.read()).toMatchObject({ source: { port: 6543 }, target: { port: 6544 } });+ expect(JSON.parse(run('status').stdout)).toEqual(operation);+ expect(run('begin', 'docker', 'native').status).toBe(1);+ writeFileSync(join(root, '.env'), config.replace('6543', '6545'));+ expect(run('cancel', operation.id).status).toBe(1);+ expect(journal.isFenced()).toBe(true);+ writeFileSync(join(root, '.env'), config);+ expect(JSON.parse(run('cancel', operation.id).stdout)).toEqual({ id: operation.id, stage: 'cancelled' });+ expect(JSON.parse(run('status').stdout)).toEqual({ stage: 'idle' });+ });++ it('refuses same-endpoint and credential-bearing journals before fencing', () => {+ expect(() => journal.begin({ source, target: { ...target, host: '127.0.0.1', port: source.port } })).toThrow();+ expect(() => journal.begin({ source: { ...source, password: 'example-secret' }, target })).toThrow();+ expect(journal.isFenced()).toBe(false);+ });+});diff --git a/server/lib/db.js b/server/lib/db.jsindex 4e71c7bd69..3e9041e02d 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -8,6 +8,7 @@import pg from 'pg';import { AsyncLocalStorage } from 'node:async_hooks';import { isTestRunner } from './runtimeEnv.js';+import { assertDatabaseAdmission } from './databaseMaintenanceJournal.js';const { Pool } = pg;@@ -213,6 +214,8 @@ function maintenanceError() {}async function databaseOperation(fn) {+ // A process-local restore context cannot bypass a durable cutover fence.+ assertDatabaseAdmission();if (maintenanceActive && !databaseContext.getStore()?.active) throw maintenanceError();const context = { active: true };const pending = databaseContext.run(context, async () => fn());@@ -227,6 +230,7 @@ async function databaseOperation(fn) {/** Drain admitted database work and reject new work until restore completes. */export async function withDatabaseMaintenance(fn) {+ assertDatabaseAdmission();if (maintenanceActive || databaseContext.getStore()?.active) throw maintenanceError();maintenanceActive = true;const context = { active: true };diff --git a/server/lib/index.js b/server/lib/index.jsindex 29a9136d87..6dfea5ac19 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -747,3 +747,5 @@ export * from './launchVideoValidation.js';export * from './styleSourcePrompt.js';export * from './messageBrowserIdentity.js';++export * from './databaseMaintenanceJournal.js';diff --git a/server/services/agentGuards.js b/server/services/agentGuards.jsindex 44c1e6c295..e37c7a1313 100644--- a/server/services/agentGuards.js+++ b/server/services/agentGuards.js@@ -1,3 +1,4 @@+import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';/*** Agent lifecycle guard primitives.*@@ -5,9 +6,8 @@* ~470-LOC `spawnAgentForTask` and `handleAgentCompletion` orchestrators* (agentLifecycle.js) so the concurrency contracts they enforce are unit-* testable against the REAL code path instead of a hand-copied replica- * (issue #2548). All of them operate purely on the collection/predicate passed- * in — no module state, no I/O — so a test can drive them with a throwaway- * collection or a stub predicate.+ * (issue #2548). Spawn admission also consults the persistent database fence+ * before registering work; the other guards use the supplied predicates.*//**@@ -40,6 +40,7 @@ export const SPAWN_DEDUP_SKIP = Symbol('spawn-dedup-skip');* @returns {Promise<any|typeof SPAWN_DEDUP_SKIP>}*/export async function withSpawnDedupGuard(spawningTasks, taskId, fn) {+ assertDatabaseAdmission();if (spawningTasks.has(taskId)) return SPAWN_DEDUP_SKIP;spawningTasks.add(taskId);try {diff --git a/server/services/databaseBootFence.js b/server/services/databaseBootFence.jsnew file mode 100644index 0000000000..1e2a9a13da--- /dev/null+++ b/server/services/databaseBootFence.js@@ -0,0 +1,5 @@+// Evaluate before importing either managed process's application graph.+// A pending or damaged journal must not allow boot-time writers/schedulers.+import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';++assertDatabaseAdmission();