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: add fenced target database startup verification (#8816)
[._.]/ Adam Eivydcb29941f737
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex cfe20058f1..4eccd59af7 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -261,3 +261,36 @@ Cancellation supports only the initial accepted stage, preserves the journal inAn 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.Coordinator stage publication uses immutable, atomically linked records. A same-operation retry with the existing owner token can confirm its last transition after a lost response; abandoned temporary files do not advance the stage, and a delayed retry cannot overwrite later progress. Interrupted claims from the older publication protocol still fail closed. This does not permit replacing a coordinator, reopening admission, or retrying SQL import: those require the offline recovery protocol.++### Verification-only server startup++The managed server entrypoint is `server/start.js`. Normal startup checks the+persistent fence before importing the application graph, so routes, migrations,+schedulers, and writer modules cannot initialize while maintenance is active.+The CoS runner retains its separate boot fence.++For an operation already at `verifying` or `verified`, a recovery operator can+run a read-only target diagnostic from the intended target launch environment:++```sh+node server/start.js --verify-database <operation-id>+```++Supply the recorded target's `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE` through+that environment, and credentials through `PGPASSWORD`. This direct Node command+does not load `.env`; use the same resolved values the PM2 ecosystem would pass+to the server. It checks the actual pool's captured connection settings against+the recorded target before checkout, then checks database/user identity and the+required memory/catalog schema in one read-only transaction. A stale source+port, wrong operation, earlier stage, unavailable database, incomplete schema,+or changed/damaged journal refuses the diagnostic. Raw connection errors and+credentials are omitted from its response.++Success returns `targetHealthy: true` and `fenced: true`, then closes the pool+and exits. Repeating the command repeats the probe without changing any journal+stage. It never imports the application, clears the fence, rewrites saved mode,+or resumes writers. This is **not completed cutover or proof of a later ordinary+restart**. The offline coordinator still must own shutdown/drain, transfer,+interruption recovery, and a verified admission-release handshake (#8816).+Do not advance journal stages manually to make this diagnostic run; unsupported+or damaged operations must stay fenced with both database copies preserved.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 4a93990779..7e40dae036 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -115,7 +115,7 @@ 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.+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.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/ecosystem.config.cjs b/ecosystem.config.cjsindex 3a5531966f..d0fd70997b 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -187,7 +187,7 @@ module.exports = {apps: [{name: 'portos-server',- script: 'server/index.js',+ script: 'server/start.js',cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,diff --git a/scripts/smoke-boot.js b/scripts/smoke-boot.jsindex 1244d949e1..dc27ad5bf0 100644--- a/scripts/smoke-boot.js+++ b/scripts/smoke-boot.js@@ -1,5 +1,5 @@#!/usr/bin/env node-// Server boot smoke test — imports server/index.js in a child process and+// Server boot smoke test — imports server/start.js in a child process and// waits for readiness, verifies it stays alive for SMOKE_WINDOW_MS, and// requires a clean shutdown. Catches the// class of bug where top-level initialization code throws (e.g. chaining@@ -37,7 +37,7 @@ import { rewriteAppsPortosRoot } from './lib/rewriteAppsPortosRoot.js';const __dirname = dirname(fileURLToPath(import.meta.url));const CODE_ROOT = join(__dirname, '..');-const SERVER_ENTRY = join(CODE_ROOT, 'server', 'index.js');+const SERVER_ENTRY = join(CODE_ROOT, 'server', 'start.js');/** Ends in `_test`, so `server/lib/db.js` treats it as a test database. */export const SMOKE_DATABASE = 'portos_smoke_test';diff --git a/server/lib/db.js b/server/lib/db.jsindex 62a7ad187a..5258f3377a 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -8,7 +8,7 @@import pg from 'pg';import { AsyncLocalStorage } from 'node:async_hooks';import { isTestRunner } from './runtimeEnv.js';-import { assertDatabaseAdmission } from './databaseMaintenanceJournal.js';+import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';const { Pool } = pg;@@ -28,13 +28,13 @@ if (!process.env.PGPASSWORD) {// need a SECOND, independent connection to the same database (a raw `pg`// client outside the pool) don't have to re-derive these defaults and risk// drifting from them — see server/lib/db.test.js.-export const POOL_CONFIG = {+export const POOL_CONFIG = Object.freeze({host: process.env.PGHOST || 'localhost',port: parseInt(process.env.PGPORT || '5432', 10),database: process.env.PGDATABASE || 'portos',user: process.env.PGUSER || 'portos',password: process.env.PGPASSWORD || 'portos',-};+});const pool = new Pool({...POOL_CONFIG,@@ -363,6 +363,53 @@ export async function checkHealth() {}}+/**+ * Fixed, read-only startup diagnostic through THIS process's actual pool.+ * This does not lift admission, execute caller SQL, advance the journal, or+ * establish that a later ordinary restart used this connection. Only the+ * verification-only entrypoint calls it; all ordinary operations stay fenced.+ */+export async function verifyDatabaseMaintenanceTarget(id) {+ const journal = createDatabaseMaintenanceJournal();+ const refuse = () => Object.assign(new Error('Database target verification refused.'), {+ code: 'DATABASE_TARGET_UNVERIFIED',+ });+ const readTarget = () => {+ const operation = journal.read();+ if (!operation || operation.id !== id || !['verifying', 'verified'].includes(operation.stage)) throw refuse();+ const target = operation.target;+ // Exact saved identity, including the pool's captured host/port; do not+ // infer an endpoint from current mode, mutable env, or a reachable peer.+ if (['host', 'port', 'database', 'user'].some(key => target[key] !== POOL_CONFIG[key])) throw refuse();+ return operation;+ };+ const operation = readTarget();+ if (isTestRunner() && !/_test$/.test(POOL_CONFIG.database) && process.env.TEST_DB_OK !== '1') throw refuse();+ const client = await pool.connect();+ let discard = false;+ try {+ await client.query({ text: 'BEGIN READ ONLY', query_timeout: 10_000 });+ const { rows } = await client.query({ text: `+ SELECT current_database() AS database, current_user AS "user",+ EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'memories') AS has_memories,+ EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'memory_links') AS has_links,+ EXISTS(SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'memories' AND column_name = 'sync_sequence') AS has_sync,+ EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'catalog_ingredients') AS has_catalog,+ EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'catalog_scraps') AS has_catalog_scraps+ `, query_timeout: 10_000 });+ const health = rows?.[0];+ if (health?.database !== operation.target.database || health?.user !== operation.target.user+ || !['has_memories', 'has_links', 'has_sync', 'has_catalog', 'has_catalog_scraps'].every(key => health[key] === true)) throw refuse();+ // A query completing after journal damage/removal/replacement is not proof+ // for that new state. Preserve exactly the operation and stage we read.+ if (JSON.stringify(readTarget()) !== JSON.stringify(operation)) throw refuse();+ return { id, stage: operation.stage, target: operation.target.mode, targetHealthy: true, fenced: true };+ } finally {+ await client.query({ text: 'ROLLBACK', query_timeout: 10_000 }).catch(() => { discard = true; });+ client.release(discard);+ }+}+// In-flight dedup for ensureSchema(). At boot, two independent fire-and-forget// callers can race: the Creative Director recovery scan (which lazily selects// the PG backend and calls ensureSchema) and the boot DB gate. Running thediff --git a/server/package.json b/server/package.jsonindex 0c9b163293..e32606d81b 100644--- a/server/package.json+++ b/server/package.json@@ -8,8 +8,8 @@"npm": ">=11.11.0"},"scripts": {- "dev": "node --watch index.js",- "start": "node index.js",+ "dev": "node --watch start.js",+ "start": "node start.js","test": "vitest run","test:fast": "vitest run","test:watch": "vitest",diff --git a/server/start.js b/server/start.jsnew file mode 100644index 0000000000..030819c629--- /dev/null+++ b/server/start.js@@ -0,0 +1,23 @@+// Keep the application graph behind a dynamic import: top-level await in a+// sibling static import would allow other dependencies to evaluate meanwhile.+const args = process.argv.slice(2);+if (args.length === 0) {+ await import('./services/databaseBootFence.js');+ await import('./index.js');+} else if (args.length === 2 && args[0] === '--verify-database') {+ // This mode never imports routes, migrations, schedulers, or the CoS graph.+ // Even success exits with the persistent admission fence still closed.+ const { verifyDatabaseMaintenanceTarget, close } = await import('./lib/db.js');+ try {+ console.log(JSON.stringify(await verifyDatabaseMaintenanceTarget(args[1])));+ } catch {+ // Connection/parser errors may contain credentials or local identities.+ console.error('❌ Database target verification refused; maintenance remains fenced.');+ process.exitCode = 1;+ } finally {+ await close();+ }+} else {+ console.error('❌ Usage: node server/start.js [--verify-database <operation-id>]');+ process.exitCode = 1;+}diff --git a/server/start.test.js b/server/start.test.jsnew file mode 100644index 0000000000..b1c18b0624--- /dev/null+++ b/server/start.test.js@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { createDatabaseMaintenanceJournal } from './lib/databaseMaintenanceJournal.js';++const entry = fileURLToPath(new URL('./start.js', import.meta.url));+const application = new URL('./index.js', import.meta.url).href;+const source = { mode: 'native', host: 'localhost', port: 5432, user: 'example', database: 'example_test' };+const target = { ...source, mode: 'docker', port: 5561 };+let root;+let journal;+let loader;+let trace;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'portos-verify-boot-'));+ writeFileSync(join(root, '.portos-disposable-root'), '');+ journal = createDatabaseMaintenanceJournal(join(root, 'data'));+ trace = join(root, 'trace.jsonl');+ writeFileSync(trace, '');+ // A loader substitutes ONLY pg and the final application import. No real+ // database or running install can be reached, even if admission regresses.+ const stub = `import {appendFileSync,writeFileSync} from 'node:fs';+ const log = x => appendFileSync(${JSON.stringify(trace)}, JSON.stringify(x)+'\\n');+ export default {types:{setTypeParser(){}}, Pool:class {+ constructor(config){ log({pool:{host:config.host,port:config.port,database:config.database,user:config.user}}); }+ on(){} async end(){log('closed')}+ async connect(){log('connected');return {+ async query(q){log(q.text);if(process.env.EXAMPLE_PROBE_FAILURE==='throw') throw Error('example-secret');+ if(q.text.startsWith('\\n')){+ if(process.env.EXAMPLE_PROBE_FAILURE==='journal') writeFileSync(${JSON.stringify(join(root, 'data/database-maintenance/operation.json'))}, '{');+ return {rows:[{database:process.env.PGDATABASE,user:process.env.PGUSER,+ has_memories:true,has_links:true,has_sync:true,has_catalog:true,+ has_catalog_scraps:process.env.EXAMPLE_PROBE_FAILURE!=='schema',+ ...(process.env.EXAMPLE_PROBE_FAILURE==='identity'?{database:'different_test'}:{})}]};+ } return {rows:[]};+ }, release(discard){log({released:discard})}+ }}+ }};`;+ loader = join(root, 'loader.mjs');+ writeFileSync(loader, `export async function resolve(s,c,n){+ if(s==='pg')return {url:${JSON.stringify('data:text/javascript,' + encodeURIComponent(stub))},shortCircuit:true};+ const resolved=await n(s,c);+ if(resolved.url===${JSON.stringify(application)})return {url:'data:text/javascript,console.log("APPLICATION_IMPORTED")',shortCircuit:true};+ return resolved;+ }`);+});+afterEach(() => rmSync(root, { recursive: true, force: true }));++function run(args = [], endpoint = target, overrides = {}) {+ const env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root,+ PGHOST: endpoint.host, PGPORT: String(endpoint.port), PGUSER: endpoint.user,+ PGDATABASE: endpoint.database, PGPASSWORD: 'example-secret', ...overrides };+ delete env.VITEST;+ delete env.TEST_DB_OK;+ return spawnSync(process.execPath, ['--loader', pathToFileURL(loader).href, entry, ...args], {+ encoding: 'utf8', timeout: 15_000, env,+ });+}+function operation(from = source, to = target, finalStage = 'verifying') {+ const record = journal.begin({ source: from, target: to });+ const token = journal.acquireCoordinator(record.id);+ let previous = 'accepted';+ for (const next of ['quiescing', 'exporting', 'importing', 'committing', 'verifying', 'verified']) {+ if (previous === finalStage) break;+ journal.transition(record.id, token, previous, next);+ previous = next;+ }+ return journal.read();+}+const events = () => readFileSync(trace, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));++describe('managed database verification startup', () => {+ it.each([[source, target], [target, source]])('probes the recorded target through the actual pool without importing writers (%j)', (from, to) => {+ const record = operation(from, to);+ const result = run(['--verify-database', record.id], to);+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({ id: record.id, stage: 'verifying', target: to.mode, targetHealthy: true, fenced: true });+ expect(events()[0]).toEqual({ pool: { host: to.host, port: to.port, database: to.database, user: to.user } });+ const sql = events().filter(e => typeof e === 'string');+ expect(sql[1]).toBe('BEGIN READ ONLY');+ expect(sql[2]).toContain('current_database()');+ expect(sql.slice(3)).toEqual(['ROLLBACK', 'closed']);+ expect(journal.read()).toEqual(record);+ expect(() => journal.assertAdmission()).toThrow();+ });++ it('refuses ordinary startup before even resolving the application graph while fenced', () => {+ const record = operation();+ expect(run().status).toBe(1);+ expect(events()).toEqual([]);+ expect(journal.read()).toEqual(record);+ });++ it('loads the ordinary application through the managed entrypoint only when unfenced', () => {+ const result = run();+ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout.trim()).toBe('APPLICATION_IMPORTED');+ expect(events()).toEqual([]);+ });++ it('refuses wrong operations, old-source pools, premature stages, and non-test databases before checkout', () => {+ const record = operation();+ for (const [id, endpoint] of [['not-this-operation', target], [record.id, source],+ [record.id, { ...target, host: 'example.invalid' }], [record.id, { ...target, user: 'other' }]]) {+ expect(run(['--verify-database', id], endpoint).status).toBe(1);+ }+ expect(events()).not.toContain('connected');+ rmSync(join(root, 'data/database-maintenance'), { recursive: true });+ const early = operation(source, target, 'committing');+ expect(run(['--verify-database', early.id]).status).toBe(1);+ rmSync(join(root, 'data/database-maintenance'), { recursive: true });+ const production = { ...target, database: 'example_production' };+ const blocked = operation(source, production);+ expect(run(['--verify-database', blocked.id], production).status).toBe(1);+ expect(events()).not.toContain('connected');+ });++ it.each(['schema', 'identity', 'throw', 'journal'])('refuses %s failure without leaking details or opening admission', failure => {+ const record = operation();+ const result = run(['--verify-database', record.id], target, { EXAMPLE_PROBE_FAILURE: failure });+ expect(result.status).toBe(1);+ expect(result.stdout).toBe('');+ expect(result.stderr).not.toContain('example-secret');+ expect(result.stderr).toContain('maintenance remains fenced');+ expect(events()).toContain('ROLLBACK');+ expect(events().at(-1)).toBe('closed');+ expect(journal.isFenced()).toBe(true);+ });++ it('requires the same operation again on restart and never treats a verified stage as admission', () => {+ const record = operation(source, target, 'verified');+ for (let restart = 0; restart < 2; restart++) {+ const result = run(['--verify-database', record.id]);+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toMatchObject({ id: record.id, stage: 'verified', fenced: true });+ expect(run().status).toBe(1);+ }+ expect(journal.read()).toEqual(record);+ });+});