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: show verified database cutover and recovery in Settings (#8811)
[._.]/ Adam Eivyd07397ab0a5c
diff --git a/client/src/components/settings/DatabaseTab.jsx b/client/src/components/settings/DatabaseTab.jsxindex 22d35fd0ee..71afa032ca 100644--- a/client/src/components/settings/DatabaseTab.jsx+++ b/client/src/components/settings/DatabaseTab.jsx@@ -1,13 +1,31 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Trash2 } from 'lucide-react';+import { Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Trash2, AlertTriangle, CheckCircle2 } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';-import { formatBytes, formatCount } from '../../utils/formatters';+import { formatBytes, formatCount, formatDurationMs } from '../../utils/formatters';import {getDatabaseStatus, setupNativeDatabase, exportDatabase, fixDatabase,- syncDatabase, startDatabase, stopDatabase, destroyDatabase+ syncDatabase, startDatabase, stopDatabase, destroyDatabase,+ getDatabaseMaintenanceStatus, cutoverDatabase, recoverDatabaseCutover} from '../../services/api';import socket from '../../services/socket';+import { safeReadJsonSession, safeWriteJsonSession, safeRemoveSession } from '../../lib/safeStorage';++// Session-scoped: the cutover restarts this server, so the tab reloads or+// reconnects mid-operation. Persisting only for the tab's lifetime keeps a+// stale marker from resurrecting a finished operation in a future session.+const OWN_OPERATION_KEY = 'portos-database-cutover-operation';+const CUTOVER_TOAST_ID = 'portos-database-cutover';++const STAGE_LABELS = {+ accepted: 'Preparing cutover',+ quiescing: 'Draining writers',+ exporting: 'Exporting source database',+ importing: 'Importing into target',+ committing: 'Committing configuration',+ verifying: 'Restarting and verifying target',+ verified: 'Verified',+};function BackendCard({ label, icon: Icon, backend, isActive, dbStatus, runAction, setConfirmAction, actionInProgress, busy, exportDatabase: exportDb }) {const data = dbStatus?.[backend];@@ -149,13 +167,109 @@ function BackendCard({ label, icon: Icon, backend, isActive, dbStatus, runAction);}+/**+ * Coordinated offline backend cutover (#8811). The journal that backs+ * `GET /database/maintenance/status` is durable on disk and outlives the+ * server restart the cutover performs, so it is the single source of truth+ * for "what happened" — never the accepted-request response, a reconnect, or+ * a saved-mode change alone. Only a `fenced: false` read whose `lastCutover.id`+ * matches the operation THIS tab started counts as a verified success.+ */+function MigrationPanel({ dbStatus, maintenance, maintenanceLoading, downtimeMs, justVerified, onMigrate, onRecover, recovering, busy, recoverDisabled }) {+ if (maintenanceLoading && !maintenance) {+ return <BrailleSpinner text="Checking migration status" />;+ }+ if (!maintenance) {+ return (+ <p className="text-sm text-gray-500">Unable to check migration status. Use Refresh above to retry.</p>+ );+ }++ if (maintenance.fenced) {+ const needsRecovery = maintenance.coordinator === 'exited';+ const label = STAGE_LABELS[maintenance.stage] || maintenance.stage;+ return (+ <div className={`rounded-lg p-3 space-y-2 border ${needsRecovery ? 'bg-port-error/10 border-port-error/30' : 'bg-port-accent/10 border-port-accent/20'}`}>+ <div className="flex items-center gap-2 text-sm">+ {needsRecovery ? <AlertTriangle size={14} className="text-port-error" /> : <BrailleSpinner />}+ <span className={needsRecovery ? 'text-port-error' : 'text-port-accent'}>+ {maintenance.source} → {maintenance.target}: {label}+ {needsRecovery && ' (interrupted)'}+ </span>+ </div>+ {needsRecovery ? (+ <>+ <p className="text-xs text-gray-400">+ The cutover worker exited before finishing. It is safe to resume — the operation resumes from its recorded+ stage and will not reverse direction or repeat completed work.+ </p>+ <button+ onClick={() => onRecover(maintenance)}+ disabled={recoverDisabled}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {recovering ? <BrailleSpinner /> : <RotateCw size={14} />}+ Resume cutover+ </button>+ </>+ ) : (+ <p className="text-xs text-gray-400">+ PortOS will stop and restart itself to complete this. Other database actions are disabled until it finishes.+ </p>+ )}+ </div>+ );+ }++ const target = dbStatus?.mode === 'docker' ? 'native' : 'docker';+ const targetLabel = target === 'docker' ? 'Docker' : 'Native';+ const sourceLabel = dbStatus?.mode === 'docker' ? 'Docker' : 'Native';++ return (+ <div className="space-y-2">+ {justVerified && maintenance.lastCutover && (+ <div className="flex items-center gap-2 text-sm text-port-success bg-port-success/10 border border-port-success/20 rounded-lg px-3 py-2">+ <CheckCircle2 size={14} />+ <span>+ Verified — now running on {maintenance.lastCutover.target}+ {downtimeMs != null && ` (downtime ${formatDurationMs(downtimeMs)})`}+ </span>+ </div>+ )}+ <button+ onClick={() => onMigrate({ source: dbStatus?.mode, target })}+ disabled={busy || !dbStatus?.mode}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-border hover:bg-port-border/70 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ <ArrowRightLeft size={14} />+ Migrate {sourceLabel} → {targetLabel}+ </button>+ <p className="text-xs text-gray-500">+ Stops PortOS, transfers data, commits the new backend, and restarts — verifying the restarted server before+ reporting success. Expect brief downtime. Backups remain available regardless.+ </p>+ </div>+ );+}+export function DatabaseTab() {const [dbStatus, setDbStatus] = useState(null);const [dbLoading, setDbLoading] = useState(true);const [actionInProgress, setActionInProgress] = useState(null);const [progressMsg, setProgressMsg] = useState('');const [confirmAction, setConfirmAction] = useState(null);+ const [maintenance, setMaintenance] = useState(null);+ const [maintenanceLoading, setMaintenanceLoading] = useState(true);+ const [recovering, setRecovering] = useState(false);+ const [downtimeMs, setDowntimeMs] = useState(null);+ const [justVerified, setJustVerified] = useState(false);const progressTimer = useRef(null);+ // The operation THIS tab started, if any: { id, source, target, acceptedAt }.+ // Session-scoped because the server restarts mid-operation; a page reload in+ // the same tab must still recognize its own cutover once it reconciles.+ const ownOperationRef = useRef(safeReadJsonSession(OWN_OPERATION_KEY));+ const wentDownAtRef = useRef(null);+ const hasConnectedOnceRef = useRef(socket.connected);const loadStatus = useCallback(() => {setDbLoading(true);@@ -165,8 +279,46 @@ export function DatabaseTab() {.finally(() => setDbLoading(false));}, []);+ const reconcileMaintenance = useCallback(() => {+ setMaintenanceLoading(true);+ getDatabaseMaintenanceStatus()+ .then((status) => {+ setMaintenance(status);+ const own = ownOperationRef.current;+ if (!own) return;+ if (status.fenced && status.id !== own.id) {+ // A different operation is fenced (e.g. started from the CLI) —+ // this tab's own marker no longer applies.+ ownOperationRef.current = null;+ safeRemoveSession(OWN_OPERATION_KEY);+ toast.dismiss(CUTOVER_TOAST_ID);+ return;+ }+ if (!status.fenced) {+ if (status.lastCutover?.id === own.id) {+ const downtime = wentDownAtRef.current ? Date.now() - wentDownAtRef.current : null;+ setDowntimeMs(downtime);+ setJustVerified(true);+ toast.success(`Database migrated to ${status.lastCutover.target}`, { id: CUTOVER_TOAST_ID });+ } else {+ // No matching verified record — cancelled or superseded. Never+ // claim success for an accepted-but-unresolved operation.+ toast.dismiss(CUTOVER_TOAST_ID);+ }+ ownOperationRef.current = null;+ safeRemoveSession(OWN_OPERATION_KEY);+ wentDownAtRef.current = null;+ } else if (status.coordinator === 'exited') {+ toast.error('Database cutover was interrupted and needs recovery.', { id: CUTOVER_TOAST_ID });+ }+ })+ .catch(() => setMaintenance(null))+ .finally(() => setMaintenanceLoading(false));+ }, []);+useEffect(() => {loadStatus();+ reconcileMaintenance();const handleProgress = (data) => {clearTimeout(progressTimer.current);@@ -180,12 +332,37 @@ export function DatabaseTab() {}};+ // Push, don't poll: the cutover restarts this server, so there is no+ // event stream during that gap. Socket.IO's own reconnect (not a+ // client-driven interval) is the signal that it's safe to re-read the+ // durable maintenance journal.+ const handleConnect = () => {+ if (!hasConnectedOnceRef.current) {+ hasConnectedOnceRef.current = true;+ return;+ }+ // A real reconnect (not the initial connect) — the durable journal may+ // have moved on while this tab had no socket. Downtime (if any) was+ // already captured by handleDisconnect below.+ loadStatus();+ reconcileMaintenance();+ };+ const handleDisconnect = () => {+ if (ownOperationRef.current && wentDownAtRef.current == null) {+ wentDownAtRef.current = Date.now();+ }+ };+socket.on('database:progress', handleProgress);+ socket.on('connect', handleConnect);+ socket.on('disconnect', handleDisconnect);return () => {socket.off('database:progress', handleProgress);+ socket.off('connect', handleConnect);+ socket.off('disconnect', handleDisconnect);clearTimeout(progressTimer.current);};- }, [loadStatus]);+ }, [loadStatus, reconcileMaintenance]);const runAction = useCallback((key, fn, successMsg) => {setConfirmAction(null);@@ -199,7 +376,51 @@ export function DatabaseTab() {.finally(() => setActionInProgress(null));}, [loadStatus]);- const busy = actionInProgress != null;+ const handleMigrate = useCallback((direction) => {+ setConfirmAction(null);+ setActionInProgress('cutover');+ cutoverDatabase(direction)+ .then((accepted) => {+ const own = { id: accepted.id, source: accepted.source, target: accepted.target, acceptedAt: Date.now() };+ ownOperationRef.current = own;+ safeWriteJsonSession(OWN_OPERATION_KEY, own);+ wentDownAtRef.current = null;+ setDowntimeMs(null);+ setJustVerified(false);+ // Accepted only — never a success toast. PortOS is about to restart.+ toast.loading(`Cutover accepted (${accepted.source} → ${accepted.target}) — PortOS will restart`, {+ id: CUTOVER_TOAST_ID, duration: Infinity,+ });+ setMaintenance({ id: accepted.id, stage: accepted.stage, source: accepted.source, target: accepted.target, coordinator: 'unclaimed', fenced: true });+ })+ .catch(() => { /* request() already surfaces API errors as a toast */ })+ .finally(() => setActionInProgress(null));+ }, []);++ const handleRecover = useCallback((operation) => {+ setRecovering(true);+ recoverDatabaseCutover(operation.id)+ .then(() => {+ // Claim the same operation id — even a tab that only resumed it+ // (rather than starting it) should see the eventual verified result.+ const own = { id: operation.id, source: operation.source, target: operation.target, acceptedAt: Date.now() };+ ownOperationRef.current = own;+ safeWriteJsonSession(OWN_OPERATION_KEY, own);+ wentDownAtRef.current = null;+ setDowntimeMs(null);+ setJustVerified(false);+ toast.loading('Resuming interrupted cutover — PortOS will restart', { id: CUTOVER_TOAST_ID, duration: Infinity });+ reconcileMaintenance();+ })+ .catch(() => { /* request() already surfaces API errors as a toast */ })+ .finally(() => setRecovering(false));+ }, [reconcileMaintenance]);++ const busy = actionInProgress != null || Boolean(maintenance?.fenced) || recovering;+ // The Recover button lives INSIDE the fenced/interrupted state, so it must+ // not be gated by `maintenance.fenced` — that would make it permanently+ // disabled the one time it needs to be clickable.+ const recoverDisabled = actionInProgress != null || recovering;return (<div className="space-y-4">@@ -210,13 +431,13 @@ export function DatabaseTab() {<span className={`w-2 h-2 rounded-full ${dbStatus?.connected ? 'bg-port-success' : 'bg-port-error'}`} /><span className="text-sm text-gray-300">{dbStatus?.connected ? 'Connected' : dbStatus ? 'Disconnected' : ''}- {dbStatus?.memoryCount != null && ` \u2014 ${formatCount(dbStatus.memoryCount)} memories`}- {dbStatus?.dbBytes != null && ` \u2014 ${formatBytes(dbStatus.dbBytes)}`}+ {dbStatus?.memoryCount != null && ` — ${formatCount(dbStatus.memoryCount)} memories`}+ {dbStatus?.dbBytes != null && ` — ${formatBytes(dbStatus.dbBytes)}`}{dbStatus?.tableCount != null && ` (${dbStatus.tableCount} tables)`}</span></div><button- onClick={loadStatus}+ onClick={() => { loadStatus(); reconcileMaintenance(); }}disabled={dbLoading}className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-400 hover:text-white transition-colors"title="Refresh status" aria-label="Refresh status"@@ -247,11 +468,23 @@ export function DatabaseTab() {/></div>- <p className="text-sm text-port-warning">- Database migration and switching are temporarily unavailable to protect writes made while PortOS is running.- Keep using the current backend until a coordinated shutdown and restart is available.- Backups remain available.- </p>+ <MigrationPanel+ dbStatus={dbStatus}+ maintenance={maintenance}+ maintenanceLoading={maintenanceLoading}+ downtimeMs={downtimeMs}+ justVerified={justVerified}+ onMigrate={(direction) => setConfirmAction({+ type: 'migrate',+ label: `Migrate from ${direction.source} to ${direction.target}?`,+ detail: 'PortOS stops itself, transfers the data, and restarts on the new backend. This causes brief downtime and cannot be cancelled once the transfer starts.',+ action: () => handleMigrate(direction),+ })}+ onRecover={handleRecover}+ recovering={recovering}+ busy={busy}+ recoverDisabled={recoverDisabled}+ />{/* Progress indicator */}{progressMsg && (diff --git a/client/src/components/settings/DatabaseTab.test.jsx b/client/src/components/settings/DatabaseTab.test.jsxnew file mode 100644index 0000000000..bcad0cb6c4--- /dev/null+++ b/client/src/components/settings/DatabaseTab.test.jsx@@ -0,0 +1,143 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { render, cleanup, screen, fireEvent, waitFor, act } from '@testing-library/react';++import socket from '../../services/socket';+vi.mock('../../services/socket', () => ({+ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn(), connected: true },+}));+// Fires every handler registered for `event` — stands in for both a real+// Socket.IO reconnect and the initial connect, since the component tells+// them apart via its own "have we connected before" ref, not the event data.+const fireSocketEvent = (event) => {+ for (const [name, handler] of socket.on.mock.calls) if (name === event) handler({});+};++vi.mock('../../services/api', () => ({+ getDatabaseStatus: vi.fn(),+ getDatabaseMaintenanceStatus: vi.fn(),+ cutoverDatabase: vi.fn(),+ recoverDatabaseCutover: vi.fn(),+ setupNativeDatabase: vi.fn(),+ exportDatabase: vi.fn(),+ fixDatabase: vi.fn(),+ syncDatabase: vi.fn(),+ startDatabase: vi.fn(),+ stopDatabase: vi.fn(),+ destroyDatabase: vi.fn(),+}));++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(),+ warning: vi.fn(),+ dismiss: vi.fn(),+ }),+}));++vi.mock('../../lib/safeStorage', () => ({+ safeReadJsonSession: vi.fn(() => null),+ safeWriteJsonSession: vi.fn(),+ safeRemoveSession: vi.fn(),+}));++import {+ getDatabaseStatus, getDatabaseMaintenanceStatus, cutoverDatabase, recoverDatabaseCutover,+} from '../../services/api';+import toast from '../ui/Toast';+import { safeReadJsonSession } from '../../lib/safeStorage';+import { DatabaseTab } from './DatabaseTab';++const dbStatus = {+ connected: true, mode: 'docker', memoryCount: 10, dbBytes: 1000, tableCount: 5,+ docker: { containerRunning: true, installed: true, daemonRunning: true },+ native: { configured: false, installed: false, running: false },+};+const idleMaintenance = { stage: 'idle', fenced: false };++beforeEach(() => {+ vi.clearAllMocks();+ socket.connected = true;+ getDatabaseStatus.mockResolvedValue(dbStatus);+ getDatabaseMaintenanceStatus.mockResolvedValue(idleMaintenance);+ safeReadJsonSession.mockReturnValue(null);+});++afterEach(cleanup);++const renderTab = async () => {+ render(<DatabaseTab />);+ await waitFor(() => expect(getDatabaseStatus).toHaveBeenCalled());+ await waitFor(() => expect(screen.getByText(/Migrate Docker/i)).toBeTruthy());+};++describe('DatabaseTab migration', () => {+ it('offers a migrate action when idle and reads status without a stale-poll interval', async () => {+ await renderTab();+ expect(getDatabaseMaintenanceStatus).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('button', { name: /Migrate Docker/i })).toBeTruthy();+ });++ it('never toasts success from an accepted cutover — only a matching verified operation does', async () => {+ cutoverDatabase.mockResolvedValue({ id: 'op-1', stage: 'accepted', source: 'docker', target: 'native', accepted: true });+ await renderTab();++ fireEvent.click(screen.getByRole('button', { name: /Migrate Docker/i }));+ fireEvent.click(screen.getByRole('button', { name: /^Confirm$/i }));++ await waitFor(() => expect(cutoverDatabase).toHaveBeenCalledWith({ source: 'docker', target: 'native' }));+ // Accepted only: a loading toast, never a success toast.+ expect(toast.loading).toHaveBeenCalled();+ expect(toast.success).not.toHaveBeenCalled();+ // Disables competing backend actions while the cutover is in flight.+ await waitFor(() => expect(screen.getAllByRole('button', { name: /^Backup$/i })[0]).toBeDisabled());+ });++ it('reconciles the durable journal on socket reconnect, not on a timer', async () => {+ // Not yet connected at mount, so the socket's own first `connect` is the+ // initial handshake, not a reconnect worth re-reading the journal for.+ socket.connected = false;+ await renderTab();+ expect(getDatabaseMaintenanceStatus).toHaveBeenCalledTimes(1);++ await act(async () => { fireSocketEvent('connect'); }); // the initial connect — ignored (not a reconnect)+ expect(getDatabaseMaintenanceStatus).toHaveBeenCalledTimes(1);++ await act(async () => { fireSocketEvent('disconnect'); });+ await act(async () => { fireSocketEvent('connect'); }); // a real reconnect after a real disconnect+ await waitFor(() => expect(getDatabaseMaintenanceStatus).toHaveBeenCalledTimes(2));+ });++ it('shows an actionable recovery control for an interrupted cutover, and resumes the same operation id', async () => {+ getDatabaseMaintenanceStatus.mockResolvedValue({+ id: 'op-2', stage: 'importing', coordinator: 'exited', source: 'docker', target: 'native', fenced: true,+ });+ recoverDatabaseCutover.mockResolvedValue({ id: 'op-2', stage: 'importing', recovery: 'launched' });+ render(<DatabaseTab />);+ await waitFor(() => expect(screen.getByRole('button', { name: /Resume cutover/i })).toBeTruthy());++ fireEvent.click(screen.getByRole('button', { name: /Resume cutover/i }));+ await waitFor(() => expect(recoverDatabaseCutover).toHaveBeenCalledWith('op-2'));+ expect(toast.success).not.toHaveBeenCalled();+ });++ it('reports success only once the journal reports a verified match for this tab\'s own operation', async () => {+ safeReadJsonSession.mockReturnValue({ id: 'op-3', source: 'docker', target: 'native', acceptedAt: Date.now() });+ getDatabaseMaintenanceStatus.mockResolvedValue({+ stage: 'idle', fenced: false, lastCutover: { id: 'op-3', source: 'docker', target: 'native', sourceRetained: true },+ });+ await renderTab();++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(+ expect.stringContaining('native'), expect.objectContaining({ id: 'portos-database-cutover' })+ ));+ });++ it('does not claim success for a foreign or superseded operation id', async () => {+ safeReadJsonSession.mockReturnValue({ id: 'op-4', source: 'docker', target: 'native', acceptedAt: Date.now() });+ getDatabaseMaintenanceStatus.mockResolvedValue({ stage: 'idle', fenced: false });+ await renderTab();+ expect(toast.success).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiDatabase.js b/client/src/services/apiDatabase.jsindex 253e84b5f5..76c8cdf3df 100644--- a/client/src/services/apiDatabase.js+++ b/client/src/services/apiDatabase.js@@ -21,3 +21,15 @@ export const destroyDatabase = (backend) => request('/database/destroy', {method: 'POST',body: JSON.stringify({ backend })});++// Coordinated offline backend cutover (#8811). The journal survives the+// server's own restart, so status reads work before/after that gap too.+export const getDatabaseMaintenanceStatus = (options) => request('/database/maintenance/status', { silent: true, ...options });+export const cutoverDatabase = (direction) => request('/database/maintenance/cutover', {+ method: 'POST',+ body: JSON.stringify(direction)+});+export const recoverDatabaseCutover = (id) => request('/database/maintenance/recover', {+ method: 'POST',+ body: JSON.stringify({ id })+});diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 6f88641a22..258715c778 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -13,16 +13,25 @@ Implementation: `server/services/backup.js` (snapshot/dump/restore), `server/ser## Database backend migration-Migration and switching between Docker and native PostgreSQL are temporarily-unavailable in Settings. `scripts/db.sh migrate`, `use-native`, and `use-docker`-also refuse. Native setup provisions without selecting a backend. Copying a live database and switching-mode can strand writes accepted after the snapshot. Backups and standalone-exports remain available; they do not make a new backend authoritative.--Keep using the current backend until the coordinated offline cutover ships-(#8797 / #8805). It must stop/drain every PortOS writer, including the CoS-runner, then verify the restarted server's target connection before declaring-success. Expect downtime. Do not substitute Sync followed by Switch.+Settings (Database tab) offers a coordinated offline cutover between Docker and+native PostgreSQL. It stops/drains every PortOS writer (including the CoS+runner), transfers the data, commits the new backend, restarts, and verifies+the restarted server's target connection before reporting success — the same+lifecycle `scripts/database-maintenance.mjs` drives from the CLI (see+[Database maintenance admission](#database-maintenance-admission) below).+`scripts/db.sh migrate`, `use-native`, and `use-docker` still refuse directly;+native setup provisions without selecting a backend. Do not substitute Sync+followed by Switch — that copies data without stopping writers or verifying+the restart, and can strand writes accepted after the snapshot.++Expect brief downtime while PortOS restarts. The Database tab shows the+operation's stage (preparing, exporting/importing, restarting and verifying),+never reports success from an accepted request, a reconnect, or a saved-mode+change alone, and reconciles the outcome from the durable maintenance journal+on socket reconnect and page reload — because the server it is watching is the+one restarting. If the cutover worker exits before finishing, the tab shows an+interrupted state with a Resume control that continues the same recorded+operation; there is no rollback, force, or skip.If a previous migration left records missing, preserve both backend databasesand the migration dump. The source may hold accepted writes absent from the@@ -50,8 +59,9 @@ Import retains the dump and uses one transaction with `ON_ERROR_STOP`.An explicit endpoint only selects where a standalone transfer runs. Importreplaces database objects present in the dump: keep recovery copies and stopthe target's writers before restoring. These commands do not stop PortOS,-change saved mode, verify a restarted pool, or authorize a backend cutover.-The complete offline migration lifecycle remains unavailable under #8816.+change saved mode, verify a restarted pool, or authorize a backend cutover —+use the coordinated cutover above (Settings Database tab or+`scripts/database-maintenance.mjs`) for that.## What gets backed up@@ -260,7 +270,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; `node scripts/database-maintenance.mjs recover <operation-id>` only resumes the recorded operation 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 recovery feedback is #8811. `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; `node scripts/database-maintenance.mjs recover <operation-id>` only resumes the recorded operation 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.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.