Skip to content

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

fix: keep destination database authority when restoring snapshot files (#10064)

[._.]/ Adam Eivy7c1327d18259
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 6213a12384..f405d5ceb5 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -262,6 +262,10 @@ Snapshots from PortOS versions that predate `manifest.json` remain restorable as
After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. Restore always passes `--checksum`, so rsync compares file contents even when the live file has the same size and modification time as the snapshot; equal-content files remain skippable, while differing bytes appear in previews and are restored. This applies to dry-run and live restores, including selective subdirectory restores and legacy snapshots without a manifest. `dryRun: true` (the default) reports what would change without writing; an optional `subdirFilter` limits the restore to one subdirectory.
+#### Database authority is not restored
+
+`data/database-authority.json` is backed up as cutover evidence but is never installed by a file restore. It records which database backend a completed cutover retired on the machine that ran it, so restoring it from another machine's snapshot (or from an older snapshot after a reverse cutover) would make PortOS refuse its own healthy database with `DATABASE_RETIRED_BACKEND`, including after a restart. Every file restore therefore excludes it, in preview and execution alike, and the integrity preflight ignores it too. The destination's existing file stays byte-for-byte as it was: an absent record stays absent and a damaged one stays fail-closed. Other records in the snapshot restore normally. Selecting `database-authority.json` itself is refused with `BACKUP_RESTORE_MACHINE_LOCAL` before anything is transferred. This does not touch an active maintenance journal (`database-maintenance/`): its recovery semantics are unchanged, and another machine's cutover endpoints are never imported. To change which backend is authoritative, run a database cutover.
+
### Database — `restorePostgres()`
Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the **SQL replay is atomic**: a failed replay rolls back.
@@ -427,7 +431,7 @@ 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. There is no rollback, force or skip command. Cancellation clears an ownerless `accepted` fence; `node scripts/database-maintenance.mjs recover <operation-id>` is a different case: it only resumes the same recorded, coordinator-owned operation (identity preserved) after its worker exited. The offline transfer, its retained `data/db-dumps/portos-maintenance-<operation-id>.sql` recovery dump, mode commit, verified restart and release are described in [offline transfer](STORAGE.md#offline-transfer) and [mode commit, verified restart, and release](STORAGE.md#mode-commit-verified-restart-and-release); Settings (Database tab) surfaces the interrupted state and its Resume control from the same journal. `data/database-authority.json` and `data/database-maintenance-completed/` are local records of a finished cutover — restoring an older backup without them lifts the retired-backend guard. Normal startup and migration must not be re-enabled by treating this preparatory operation as a completed cutover.
+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. There is no rollback, force or skip command. Cancellation clears an ownerless `accepted` fence; `node scripts/database-maintenance.mjs recover <operation-id>` is a different case: it only resumes the same recorded, coordinator-owned operation (identity preserved) after its worker exited. The offline transfer, its retained `data/db-dumps/portos-maintenance-<operation-id>.sql` recovery dump, mode commit, verified restart and release are described in [offline transfer](STORAGE.md#offline-transfer) and [mode commit, verified restart, and release](STORAGE.md#mode-commit-verified-restart-and-release); Settings (Database tab) surfaces the interrupted state and its Resume control from the same journal. `data/database-authority.json` and `data/database-maintenance-completed/` are local records of a finished cutover. Snapshots keep them as recovery evidence, but a file restore never installs `database-authority.json` (see [Database authority is not restored](#database-authority-is-not-restored)), so restoring another machine's or an older backup can neither lift nor impose the retired-backend guard. 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.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 1c7f914f28..0e86600643 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -129,7 +129,7 @@ For local diagnostics at any stage, run `node scripts/database-maintenance.mjs s
Run `node scripts/database-maintenance.mjs writers` for bounded counts at any stage (`unresolved`, `launching`, `launched`, `exited`, `abandoned`); it always reports `quiescenceVerified: false` and exposes no control paths or process identities. A malformed inventory refuses the command. A `{ state: 'unresolved', kind: 'retired-exits' }` entry represents legacy or Windows compacted completion history. **An inventory read never proves descendant quiescence.** Only the internal `reconcileDetachedWriters(id, token)` stage (`server/services/databaseMaintenanceQuiescence.js`) can, and only for the owning coordinator worker after `stopOwnedDatabaseProducers` recorded producer shutdown at `quiescing`. It classifies each record against a POSIX process-table snapshot: a job still alive with a verified identity (its PGID is recorded and it started inside the launch window) has its recorded groups sent SIGTERM, then SIGKILL after a grace period; a group seen empty is never signalled again. It refuses, leaving the fence and every record in place, when an admitted launch has not recorded a process identity, when a record is legacy/compacted, lacks a launcher group, or is a process-group job whose own PID was never recorded, when a live PID does not match its recorded identity (possible reuse), when an exited job still has surviving group members, when groups do not terminate, when a detached supervisor of this install's data directory is running without a record (for example a launch from code that predates the registry), or on Windows for anything but abandoned launches. Two consecutive quiescent snapshots are required before it archives every record to `data/database-maintenance/reconciled-writers/<launch-id>/` and returns `quiescenceVerified: true, transferReady: false`. It never infers absence from a PID probe or elapsed time and has no force/skip option. It is internal: `quiesceDatabaseWriters(id, token)` runs producer shutdown, the predecessor-coordinator proof, then reconciliation inside the entered transfer worker, which repeats it on every attempt. Limits: a descendant that deliberately leaves its session and process group (`setsid`) is not observable by group, and orphans of a pre-registry launch whose supervisor already exited cannot be identified. Records are local recovery evidence included in backups, never a federated application collection or reference seed; do not delete them to unblock maintenance. Damaged ownership or inventory makes the transfer worker exit with code 1 and a redacted refusal. Its stdout/stderr, owner binding, one-use entry marker, group record and supervisor receipt remain in the reserved directory.
-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. A released operation moves to `data/database-maintenance-completed/<operation-id>/` the same way. `data/database-authority.json` is `file-primary`, machine-local state read before PostgreSQL: one versioned record naming the last released cutover's operation id and its retired source and released target endpoints (no password or records). Absent means no cutover has completed; malformed fails closed. It is never federated, has no reference seed, and needs no migration. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.
+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. A released operation moves to `data/database-maintenance-completed/<operation-id>/` the same way. `data/database-authority.json` is `file-primary`, machine-local state read before PostgreSQL: one versioned record naming the last released cutover's operation id and its retired source and released target endpoints (no password or records). Absent means no cutover has completed; malformed fails closed. It is never federated, has no reference seed, and needs no migration. Snapshots still contain it as recovery evidence, but `restoreSnapshot` excludes it from every file restore (full or scoped, preview and execution alike): the record describes a cutover on the machine that made it, so installing another machine's — or an older snapshot's, after a reverse cutover — would fence a healthy local backend as retired. The destination's file is left byte-for-byte as it was (absent stays absent, damaged stays damaged), and an explicit `database-authority.json` selection is refused with `BACKUP_RESTORE_MACHINE_LOCAL`. Ordinary records in the same snapshot restore normally. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.
#### Offline transfer
diff --git a/server/services/backup.js b/server/services/backup.js
index 09f1bff20e..221ea502d9 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1279,6 +1279,7 @@ function manifestDataEntries(manifest, srcDir, subdirFilter) {
if (dataPaths.has(normalized)) return null;
dataPaths.add(normalized);
+ if (isRestorePreservedPath(normalized)) continue;
if (!subdirFilter || normalized === subdirFilter || normalized.startsWith(`${subdirFilter}/`)) {
selected.push({ filePath, expectedHash });
}
@@ -1307,6 +1308,30 @@ const isOsMetadataFile = (name) => OS_METADATA_FILES.has(name) || name.startsWit
*/
const OS_METADATA_RSYNC_EXCLUDES = [...OS_METADATA_FILES, '._*'].map(name => `--exclude=${name}`);
+/**
+ * Data-root files a restore never installs, though a snapshot keeps them as
+ * recovery evidence. `database-authority.json` names which database backend a
+ * completed cutover retired ON THE MACHINE THAT RAN IT. Installing another
+ * machine's record (or an older snapshot's, after a reverse cutover) would fence
+ * a healthy local backend as `DATABASE_RETIRED_BACKEND`, including across
+ * restarts. The destination keeps whatever authority it already has,
+ * byte-for-byte: absent stays absent, damaged stays damaged. Root-anchored
+ * relative names, like `DEFAULT_EXCLUDES`; this one list feeds the rsync
+ * filter, the manifest selection and the scope inventory so preview,
+ * verification and execution cannot disagree.
+ */
+const RESTORE_PRESERVED_FILES = Object.freeze(['database-authority.json']);
+const RESTORE_PRESERVED_RSYNC_EXCLUDES = RESTORE_PRESERVED_FILES.map(name => `--exclude=/${name}`);
+const isRestorePreservedPath = (relativePath) => RESTORE_PRESERVED_FILES.includes(relativePath);
+
+// A filter naming a preserved file would otherwise be a silent no-op restore.
+// Compared case-insensitively after dropping empty/`.` segments, so
+// `./Database-Authority.json/` cannot slip past on a case-insensitive volume.
+const restoreScopeIsPreservedFile = (subdirFilter) => {
+ const normalized = subdirFilter?.split('/').filter(part => part && part !== '.').join('/').toLowerCase();
+ return RESTORE_PRESERVED_FILES.includes(normalized);
+};
+
const snapshotFileIntegrityError = (snapshotId, unmanifestedPath = null) => new ServerError(
// Name the offending entry: without it the operator is told their only backup
// failed integrity and given nothing to act on.
@@ -1351,6 +1376,8 @@ async function snapshotScopeInventory(srcDir, subdirFilter) {
// OS metadata never reaches rsync (OS_METADATA_RSYNC_EXCLUDES), so it must
// not inflate the digest floor either.
if (isOsMetadataFile(basename(filePath))) continue;
+ const scopedPath = relative(srcDir, filePath).replaceAll('\\', '/');
+ if (isRestorePreservedPath(scopedPath)) continue;
if (info.size > largestFileBytes) largestFileBytes = info.size;
const normalized = relative(srcDir, filePath).replaceAll('\\', '/');
@@ -1460,6 +1487,14 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
if (subdirFilter != null && !isSafeSubdirFilter(subdirFilter)) {
throw new Error(`Invalid subdirFilter: ${subdirFilter}`);
}
+ // Refused for previews too, before any verification or transfer, so a preview
+ // never promises a restore that execution would silently skip.
+ if (restoreScopeIsPreservedFile(subdirFilter)) {
+ throw new ServerError(
+ 'database-authority.json is machine-local and is never restored from a snapshot: it records which database backend a cutover completed on THIS machine, and installing another copy would fence the healthy local database. Restore your records with a data or database restore instead; to change the authority, run a database cutover (see docs/STORAGE.md, retired backend).',
+ { status: 400, code: 'BACKUP_RESTORE_MACHINE_LOCAL' },
+ );
+ }
// Run the preflight independently for preview and execution. A preview is an
// aid to confirmation, not an integrity lease: snapshot bytes may change
@@ -1491,7 +1526,10 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
// exclude placed after `--include=/<filter>/***` would never be consulted.
// These are the files `snapshotScopeInventory` skips — keeping the two in
// step is what preserves "everything transferred was verified".
- const flags = ['-ii', '--checksum', ...OS_METADATA_RSYNC_EXCLUDES];
+ // Same placement rule: excluded before the include chain, and kept out of the
+ // manifest selection and inventory above, so what rsync may write is exactly
+ // what the preflight verified.
+ const flags = ['-ii', '--checksum', ...OS_METADATA_RSYNC_EXCLUDES, ...RESTORE_PRESERVED_RSYNC_EXCLUDES];
if (dryRun) flags.push('--dry-run');
if (subdirFilter) {
// Anchored with a leading `/` — rsync matches an unanchored pattern against
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 5affa571b0..d1f99f907e 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -156,6 +156,7 @@ vi.mock('./brainStorage.js', async (importOriginal) => ({
invalidateAllCaches: vi.fn(),
}));
import { reloadSettings, withLiveSettingsRestore } from './settings.js';
+import { createDatabaseAuthority } from '../lib/databaseAuthority.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot, resolveRsyncBinary, deleteSnapshot } from './backup.js';
import { EXCLUDE_PATTERN_MAX_LENGTH, anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../lib/sharedSchemas.js';
@@ -2072,6 +2073,7 @@ describe('restoreSnapshot manifest verification', () => {
afterEach(async () => {
await realFs?.rm(tmpRoot, { recursive: true, force: true });
await realFs?.rm(joinPath(PATHS.data, 'restore-integrity'), { recursive: true, force: true });
+ await realFs?.rm(joinPath(PATHS.data, 'database-authority.json'), { force: true });
});
async function writeSnapshotFile(relativePath, content) {
@@ -2299,6 +2301,120 @@ describe('restoreSnapshot manifest verification', () => {
}
});
+ // #10064: database-authority.json is machine-local admission state. A snapshot
+ // keeps it as recovery evidence, but a restore must never install it: another
+ // machine's (or an older cutover's) record would fence a healthy local backend
+ // as DATABASE_RETIRED_BACKEND, including across restarts. Real rsync + the real
+ // authority adapter, because a mocked transfer cannot show the fence.
+ describe('machine-local database authority (#10064)', () => {
+ const native = { mode: 'native', host: '127.0.0.1', port: 5432, database: 'example_db', user: 'example_user' };
+ const docker = { mode: 'docker', host: '127.0.0.1', port: 5561, database: 'example_db', user: 'example_user' };
+ const authorityDoc = (operationId, source, target) => JSON.stringify({
+ version: 1, operationId, releasedAt: '2026-09-01T00:00:00.000Z', source, target,
+ }, null, 2) + '\n';
+ const SNAPSHOT_AUTHORITY = authorityDoc('11111111-1111-4111-8111-111111111111', native, docker);
+ const NEWER_LOCAL_AUTHORITY = authorityDoc('22222222-2222-4222-8222-222222222222', docker, native);
+ const poolFor = endpoint => ({ host: endpoint.host, port: endpoint.port, database: endpoint.database, user: endpoint.user });
+ const authorityPath = () => joinPath(PATHS.data, 'database-authority.json');
+ const RECORD = 'brain/authority-neighbor.json';
+
+ async function seedSnapshot({ withManifest = true } = {}) {
+ const recordHash = await writeSnapshotFile(RECORD, '{"value":"snapshot"}');
+ const authorityHash = await writeSnapshotFile('database-authority.json', SNAPSHOT_AUTHORITY);
+ if (withManifest) await writeManifest({ [RECORD]: recordHash, 'database-authority.json': authorityHash });
+ }
+
+ async function withRealRsync(context, run) {
+ if (process.platform === 'win32' && spawnSync('rsync', ['--version']).error?.code === 'ENOENT') {
+ context.skip('Windows runner has no rsync executable; real rsync remains required on Linux/macOS.');
+ return;
+ }
+ const previousRsync = process.env.PORTOS_RSYNC;
+ delete process.env.PORTOS_RSYNC;
+ spawn.mockImplementation((...args) => spawnChild(...args));
+ try {
+ await run();
+ } finally {
+ if (previousRsync === undefined) delete process.env.PORTOS_RSYNC;
+ else process.env.PORTOS_RSYNC = previousRsync;
+ spawn.mockReset();
+ await realFs.rm(joinPath(PATHS.data, 'brain', 'authority-neighbor.json'), { force: true });
+ }
+ }
+
+ it.each([
+ { name: 'full restore', options: {} },
+ { name: 'brain-scoped restore', options: { subdirFilter: 'brain' } },
+ ])('a $name keeps an absent destination authority absent, so a healthy native backend is still admitted', async ({ options }, context) => {
+ await withRealRsync(context, async () => {
+ for (const manifest of [true, false]) {
+ await realFs.rm(joinPath(snapshotDir, 'manifest.json'), { force: true });
+ await seedSnapshot({ withManifest: manifest });
+ await realFs.rm(authorityPath(), { force: true });
+ await realFs.rm(joinPath(PATHS.data, RECORD), { force: true });
+
+ const preview = await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: true, ...options });
+ expect(preview.changedFiles.some(line => line.includes('database-authority.json'))).toBe(false);
+ expect(preview.changedFiles.some(line => line.includes(RECORD))).toBe(true);
+
+ await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false, ...options });
+ expect(existsSync(authorityPath())).toBe(false);
+ expect(await realFs.readFile(joinPath(PATHS.data, RECORD), 'utf8')).toBe('{"value":"snapshot"}');
+ expect(createDatabaseAuthority(PATHS.data).assertPool(poolFor(native))).toBeNull();
+ }
+ });
+ });
+
+ it('keeps a newer reverse-cutover authority over an older snapshot\'s, and still refuses the genuinely retired backend', async context => {
+ await withRealRsync(context, async () => {
+ await seedSnapshot();
+ await realFs.writeFile(authorityPath(), NEWER_LOCAL_AUTHORITY);
+
+ await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false });
+
+ expect(await realFs.readFile(authorityPath(), 'utf8')).toBe(NEWER_LOCAL_AUTHORITY);
+ const authority = createDatabaseAuthority(PATHS.data);
+ expect(authority.assertPool(poolFor(native))).toMatchObject({ operationId: '22222222-2222-4222-8222-222222222222' });
+ expect(() => authority.assertPool(poolFor(docker))).toThrow(expect.objectContaining({ code: 'DATABASE_RETIRED_BACKEND' }));
+ });
+ });
+
+ it('leaves a damaged destination authority byte-identical and still fail-closed', async context => {
+ await withRealRsync(context, async () => {
+ await seedSnapshot();
+ await realFs.writeFile(authorityPath(), '{ not json');
+
+ await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false });
+
+ expect(await realFs.readFile(authorityPath(), 'utf8')).toBe('{ not json');
+ expect(() => createDatabaseAuthority(PATHS.data).assertPool(poolFor(native)))
+ .toThrow(expect.objectContaining({ code: 'DATABASE_MAINTENANCE' }));
+ });
+ });
+
+ it('does not fail integrity for an authority file the restore never transfers', async () => {
+ await seedSnapshot();
+ await realFs.writeFile(joinPath(snapshotDataDir, 'database-authority.json'), 'edited after sealing');
+ spawn.mockReturnValueOnce(fakeProc());
+ const pending = restoreSnapshot(tmpRoot, 'snap-1', { dryRun: true });
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ spawn.mock.results[0].value.emit('close', 0);
+ await expect(pending).resolves.toMatchObject({ verification: { status: 'verified', checkedFiles: 1 } });
+ });
+
+ it.each(['database-authority.json', './database-authority.json', 'database-authority.json/', 'Database-Authority.json'])(
+ 'refuses an explicit %s selection before verification or transfer, for preview and execution alike',
+ async subdirFilter => {
+ await seedSnapshot();
+ for (const dryRun of [true, false]) {
+ await expect(restoreSnapshot(tmpRoot, 'snap-1', { dryRun, subdirFilter }))
+ .rejects.toMatchObject({ status: 400, code: 'BACKUP_RESTORE_MACHINE_LOCAL', message: expect.stringMatching(/machine-local/) });
+ }
+ expect(spawn).not.toHaveBeenCalled();
+ },
+ );
+ });
+
// #7299: `--checksum` makes rsync digest BOTH copies of every file in scope,
// and `--itemize-changes`/`--progress` report only TRANSFERRING files. A file
// that matches emitted nothing, so a preview of a large unchanged tree ran
@@ -2847,6 +2963,8 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
'--exclude=Thumbs.db',
'--exclude=desktop.ini',
'--exclude=._*',
+ // Machine-local admission state is never installed by a restore (#10064).
+ '--exclude=/database-authority.json',
'--dry-run',
// Leading `/` is load-bearing: rsync matches an unanchored pattern
// against the end of every path, so `brain/***` would also restore
@@ -2872,6 +2990,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
'--exclude=Thumbs.db',
'--exclude=desktop.ini',
'--exclude=._*',
+ '--exclude=/database-authority.json',
]);
});