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: commit database mode and release admission only after verified target restart (#8851)
[._.]/ Adam Eivy7ad5559b3a84
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 9a259b4273..6f88641a22 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -260,7 +260,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 still no operator transfer-stage launch, resume or rollback command. The internal offline transfer, its retained `data/db-dumps/portos-maintenance-<operation-id>.sql` recovery dump, and the stage-specific `status` fields are described in [offline transfer](STORAGE.md#offline-transfer); verified restart is tracked in #8851, and Settings recovery feedback in #8811. 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 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.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.mdindex 7729a52e97..5b60a47b99 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -118,17 +118,17 @@ recorded endpoints, and the running pool before cutover.Coordinator ownership and cancellation share one exclusive durable initial claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, current ownership token, and expected previous stage. Immutable stage publications tolerate a retry of the same transition. Every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. Verification-only server startup can read the recorded target through its actual pool at the `verifying` or `verified` stage; its bounded result is transient, creates no new store, and never advances the journal or reopens admission.-The journal also supplies **internal ownership recovery** for the transfer worker; neither is an operator command. `reserveCoordinatorWorker(id, token)` atomically publishes a complete, one-use `worker-<token>/` directory bound to that operation and owner. A crash while preparing its binding leaves only an unpublished temporary directory, so the same owner can retry reservation. The internal `spawnDatabaseMaintenanceWorker(id, token)` path reserves this directory and uses the shared detached launcher with `cleanup: false`, a fixed Node executable and worker entrypoint, and no caller-selected command, arguments, environment, or control directory. It verifies current ownership before setup and again before supervisor launch. The worker claims an exclusive `started.json` marker before doing anything else; copied arguments cannot enter it twice. On POSIX it then records its process group in `group.json` before starting any database child. Ordinary `spawnDetached` calls still require normal admission, even if passed extra options or an owner token. `recoverCoordinator(id, previousToken, recoveryToken)` accepts only the recorded operation and current token, at `accepted`, `quiescing`, `exporting`, or `importing`, after the detached supervisor has published a complete numeric `exit` receipt. The caller durably records its unique recovery token before attempting recovery. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token; retrying that same recorded request returns its published token after a crash between publication and acknowledgement. A different claimant cannot recover or reuse the winner's token. A shared per-owner/per-stage decision publication serializes ownership handoff with stage transitions. Recovery completes an already-decided forward stage before choosing its successor; a predecessor that lost the decision cannot publish a new stage. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success or advance to committing.+The journal also supplies **internal ownership recovery** for the transfer worker; neither is an operator command. `reserveCoordinatorWorker(id, token)` atomically publishes a complete, one-use `worker-<token>/` directory bound to that operation and owner. A crash while preparing its binding leaves only an unpublished temporary directory, so the same owner can retry reservation. The internal `spawnDatabaseMaintenanceWorker(id, token)` path reserves this directory and uses the shared detached launcher with `cleanup: false`, a fixed Node executable and worker entrypoint, and no caller-selected command, arguments, environment, or control directory. It verifies current ownership before setup and again before supervisor launch. The worker claims an exclusive `started.json` marker before doing anything else; copied arguments cannot enter it twice. On POSIX it then records its process group in `group.json` before starting any database child. Ordinary `spawnDetached` calls still require normal admission, even if passed extra options or an owner token. `recoverCoordinator(id, previousToken, recoveryToken)` accepts only the recorded operation and current token, at any unreleased stage, after the detached supervisor has published a complete numeric `exit` receipt. The caller durably records its unique recovery token before attempting recovery. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token; retrying that same recorded request returns its published token after a crash between publication and acknowledgement. A different claimant cannot recover or reuse the winner's token. A shared per-owner/per-stage decision publication serializes ownership handoff with stage transitions. Recovery completes an already-decided forward stage before choosing its successor; a predecessor that lost the decision cannot publish a new stage. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success; `importing` → `committing` additionally requires this operation's committed import receipt. `prepareRecovery(id)` wraps this for the operator: it publishes the successor token in `recovery-after-<token>.json` before recovering, so concurrent or repeated requests adopt the same successor instead of stranding a second owner.-There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped, so every transfer attempt — including each recovered successor — repeats quiescence before any export or import (see [offline transfer](#offline-transfer) below). Verified target restart, saved-mode commit, and admission release remain #8851.+There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped, so every transfer attempt — including each recovered successor — repeats quiescence before any export or import (see [offline transfer](#offline-transfer) below). Mode commit, verified target restart, and admission release follow the transfer in the same worker (see [mode commit, verified restart, and release](#mode-commit-verified-restart-and-release)).-For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. From `exporting` onward it adds `transfer: { dump: "absent" | "recorded", import: "pending" | "committed" }`; malformed transfer records fail closed. An owned operation adds a bounded `coordinator` result: `unregistered` means no worker reservation; `awaiting-exit` means no supervisor completion proof (either running or interrupted); `exited` includes the supervisor exit code. Neither is a transfer-success verdict. Malformed ownership, binding, or exit records fail closed. Only an **unowned accepted** operation can use `node scripts/database-maintenance.mjs cancel <operation-id>` after checking saved source configuration. There is no operator launch, resume, force or skip command for an owned operation; the worker and its recovery are internal until verified restart (#8851) wires them. Preserve the journal, worker records, `transfer-*.json`, the source database and the `portos-maintenance-<operation-id>.sql` dump; do not delete markers, edit or replace the dump, or call `scripts/db.sh migrate` (still refused). Stage-specific meaning: `accepted` — nothing stopped; `quiescing` — producers may be stopped, no dump yet; `exporting` + `dump: absent` — the next attempt re-exports from the quiesced source; `exporting`/`importing` + `dump: recorded` — the source copy is fixed and only it may be imported; `importing` + `import: pending` — the target transaction did not commit, retry imports the same dump; `import: committed` — only restart verification remains. If a successor refuses because an earlier coordinator's process is still running, inspect this install's process table (`ps -A -o pid,pgid,command`) and stop that leftover dump/import yourself before the next recovery.+For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. From `exporting` onward it adds `transfer: { dump: "absent" | "recorded", import: "pending" | "committed" }`; malformed transfer records fail closed. An owned operation adds a bounded `coordinator` result: `unregistered` means no worker reservation; `awaiting-exit` means no supervisor completion proof (either running or interrupted); `exited` includes the supervisor exit code. Neither is a transfer-success verdict. Malformed ownership, binding, or exit records fail closed. Only an **unowned accepted** operation can use `node scripts/database-maintenance.mjs cancel <operation-id>` after checking saved source configuration. For an owned operation whose worker exited (`coordinator.state: "exited"`), `node scripts/database-maintenance.mjs recover <operation-id>` relaunches the worker for the SAME recorded operation and prints `{ recovery: "launched" | "running" }`; there is no launch of a new operation, force, skip or reverse command. `awaiting-exit` means no recovery is possible yet: wait for the running worker, or — if it was interrupted before its supervisor recorded an exit — keep the fence and inspect it by hand. Run `recover` from a shell without `PGHOST`/`PGPORT` overrides; the worker refuses when the saved configuration does not resolve to the recorded target. Preserve the journal, worker records, `transfer-*.json`, the source database and the `portos-maintenance-<operation-id>.sql` dump; do not delete markers, edit or replace the dump, or call `scripts/db.sh migrate` (still refused). Stage-specific meaning: `accepted` — nothing stopped; `quiescing` — producers may be stopped, no dump yet; `exporting` + `dump: absent` — the next attempt re-exports from the quiesced source; `exporting`/`importing` + `dump: recorded` — the source copy is fixed and only it may be imported; `importing` + `import: pending` — the target transaction did not commit, retry imports the same dump; `import: committed` — mode commit and restart verification remain; `committing` — saved mode is being set to the target; `verifying` — saved mode names the target, waiting for a restarted server's own proof; `verified` — only release remains. After release `status` reports `{ stage: "idle", lastCutover: { id, source, target } }`. If a successor refuses because an earlier coordinator's process is still running, inspect this install's process table (`ps -A -o pid,pgid,command`) and stop that leftover dump/import yourself before the next recovery.`data/database-writers/<launch-id>/` is machine-local, file-primary **detached launch evidence**. `spawnDetached` publishes and fsyncs a reservation before its first asynchronous setup step, then checks admission again. A launch that races fence acceptance is therefore either refused or already represented in the inventory. It checks admission again after setup; a launch refused before any launcher started records `abandoned.json`, the only proof that no child exists. On POSIX the detached outer `sh` is a session and process-group leader, so its PID (`launcher.json`) names the group every supervisor/job descendant inherits; `launch.json` adds the job PID and launch time. Reservations contain only a random launch ID, timestamp, control directory, and process-group mode. Commands, arguments, environment variables, credentials, and application records are excluded. A partial/unreadable record fails inventory closed. On completion, POSIX keeps the identity and retires the entry only after two consecutive process-table snapshots show the job gone and every recorded group empty (a group ID cannot be reused while it has members); a surviving descendant or slow supervisor leaves the record for maintenance reconciliation. Windows has no group proof, so its completion still compacts into the identity-free `unreconciled-exits.json` marker, published from fsynced bytes with its parent directory synced before deletion. Ordinary completed jobs do not accumulate one permanent directory per launch.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. 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. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.#### Offline transfer@@ -137,10 +137,25 @@ The fixed worker (`scripts/database-maintenance-worker.mjs` → `runDatabaseTran- **`quiescing` → `exporting`**: `scripts/db.sh export --endpoint` with the journal's recorded source host, port, user and database. The worker builds the child environment from an allowlist (the password is the only libpq variable passed), and `db.sh` strips every other inherited `PG*` variable again, so `PGHOST`, `PGHOSTADDR`, `PGSERVICE`, `PGOPTIONS` and the like cannot redirect it. The dump is `data/db-dumps/portos-maintenance-<operation-id>.sql`. A failed `pg_dump`, missing completion trailer, or unexpected output path is never recorded. A complete dump and its directory are fsynced, then `transfer-dump.json` publishes its operation, source identity, size and SHA-256, immutably, before `exporting` → `importing`.- **`importing`**: the recorded dump must still match its size and digest (a changed or missing dump refuses). `db.sh import --endpoint` loads it into the recorded target in one `psql --single-transaction` with `ON_ERROR_STOP`; a failed import commits nothing. Success publishes `transfer-import.json`, binding that digest to the target. A crash between the commit and that receipt makes the next attempt import the same `--clean` dump again, which reproduces the same state because nothing writes the target before verified restart.-The worker then exits `78` with `{ stage: "importing", importCommitted: true, sourceRetained: true, restartVerified: false }`: saved mode is unchanged, producers stay stopped, the source database and dump are retained, and admission stays fenced until verified target restart (#8851) exists. Ordinary pooled writes and detached spawns refuse throughout. A refusal exits `1` with a bounded reason (counts and stage only; no hosts, paths, tokens or PIDs); `db.sh` output stays internal.+Ordinary pooled writes and detached spawns refuse throughout. A refusal exits `1` with a bounded reason (counts and stage only; no hosts, paths, tokens or PIDs); `db.sh` output stays internal.Recovery is same-operation only and never reverses direction. A successor (`recoverCoordinator` after the predecessor's supervisor exit receipt, then a new `spawnDatabaseMaintenanceWorker`) repeats the whole quiescence sequence, then: at `exporting` with no recorded dump it exports again (an interrupted or failed export is never reused); at `exporting` with a recorded dump it verifies the bytes and advances; at `importing` it retries the same recorded dump into the same recorded target; with an import receipt it reports the committed import without importing again. A killed worker can leave its `pg_dump`/`psql` running after its supervisor records an exit: while any recorded predecessor group still has members, the successor refuses (`a previous coordinator's dump or import process is still running`) and signals nothing, because a group ID seen empty could have been reused. A predecessor with no group record never started a database child. Windows has no group proof, so a successor there refuses once any predecessor had entered. Descendants that leave their process group (`setsid`) are not observable.+#### Mode commit, verified restart, and release++After a committed import the same worker (`runDatabaseCutover` in `server/services/databaseMaintenanceCutover.js`) continues. The source keeps authority until the mode commit; the target has it afterward, and nothing is ever reversed:++- **`importing` → `committing`**: only with this operation's import receipt.+- **`committing` → `verifying`**: `.env` `PGMODE` is rewritten to the RECORDED target mode (temporary file, fsync, rename; every other line kept). A fresh process then evaluates `ecosystem.config.cjs` and must resolve exactly the recorded target endpoint. Recovery at `committing` repeats this same write — it never reads the file's current mode as evidence and never restores the source mode.+- **`verifying` → `verified`**: the worker restarts the recorded `portos-server` with `pm2 restart ecosystem.config.cjs --only portos-server --update-env` (so PM2's cached environment cannot supply the old `PGPORT`). `server/start.js` sees the fence and runs only the narrow handshake (`server/services/databaseCutoverHandshake.js`): it proves ITS OWN pool — the captured host/port/database/user must equal the recorded target, and a read-only transaction must find the schema — publishes `target-proof-<pid>.json`, and waits. Routes, migrations, schedulers and CoS never load before release. The worker accepts proof only for the pid PM2 reports for that server now. PM2 `online`, the saved mode, or an earlier pid's proof is not success; a wrong pool or unhealthy target makes the server exit and the worker time out (3 minutes) with the operation left at `verifying`.+- **release**: after re-checking that the saved configuration still names the target, the worker writes `data/database-authority.json` (operation id, retired source and released target endpoints), then moves `data/database-maintenance/` to `data/database-maintenance-completed/<operation-id>/`, which reopens admission. The waiting server continues only when that authority names this operation and its own pool as the target. CoS restarts last, if it was running before the cutover. The worker prints `{ stage: "released", importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted }`.++**Expected downtime** is the whole run: PortOS (UI, API, CoS, agents and schedules) is stopped from `quiescing` until release. It is roughly one export plus one import of the database (seconds for a small install, minutes for a large catalog/memory store) plus a server restart. The API answers the cutover request with `202`; the next page load is the restarted server.++**Retired backend.** The source database and `data/db-dumps/portos-maintenance-<operation-id>.sql` are retained untouched as the recovery copy — they no longer receive writes. Every pooled operation and every managed boot (`databaseBootFence`) refuses with `DATABASE_RETIRED_BACKEND` when its pool names the retired source and not the released target: for example a PM2 app restarted with a cached environment, or a shell exporting an old `PGPORT`. Restart that process from the saved configuration (`pm2 restart ecosystem.config.cjs --update-env`). To move back, run a cutover in the other direction; hand-editing `PGMODE` back to the retired backend is refused rather than silently writing to the stale copy. Removing `data/database-authority.json` lifts the guard and is only safe once you have confirmed which backend holds your records.++**Recovery commands.** Inspect with `node scripts/database-maintenance.mjs status`. If `coordinator.state` is `exited`, repair the reported cause (for example start the target backend, or fix `.env`) and run `node scripts/database-maintenance.mjs recover <operation-id>`; repeat as needed — each run resumes the recorded stage. `verifying` with a server that keeps exiting usually means the target is unreachable or `.env`/the launch environment points elsewhere; `pm2 logs portos-server` shows the bounded refusal. `verified` with no release (a crash between them) is completed by the same `recover`. Never delete the fence, the proofs, or the authority record to force startup.+### Calendar daily-review recoveryDaily reviews remain in the existing `data/calendar/daily-reviews/<date>.json`@@ -304,7 +319,7 @@ saved backend. Producer shutdown alone does **not** prove child/spawn quiescenceor authorize a dump. The internal transfer worker follows it with predecessorand descendant reconciliation, then exports the recorded source and imports therecorded dump into the recorded target (see [offline transfer](#offline-transfer)).-Public migration stays disabled until verified restart (#8851) is integrated.+The backend cutover API (`POST /api/database/maintenance/cutover`, `POST /api/database/maintenance/recover`, host-control gated) now runs the whole verified lifecycle; the Settings database tab stays disabled until #8811 surfaces its progress and recovery.For stage diagnostics, run `node scripts/database-maintenance.mjs status` and`node scripts/database-maintenance.mjs writers`. `accepted` means no transfer@@ -315,8 +330,8 @@ for the transfer stages. A same-operation internal successor requiresthe prior detached supervisor's durable exit receipt and repeats shutdownreadback, predecessor and writer reconciliation before any export or import.-Keep the existing backend selected and use backups until the coordinated-offline cutover is available (tracked in #8797 / #8805). A safe cutover requires+Until the Settings flow ships (#8811), keep the existing backend selected and use+backups unless you drive the cutover API deliberately. A safe cutover requiresdowntime for **all** PortOS writers, including the CoS runner, and verificationthat the restarted server actually uses the target. A server-only restart ora saved-mode change is not that verification. Do not use Sync followed by Switchdiff --git a/scripts/database-maintenance-worker.mjs b/scripts/database-maintenance-worker.mjsindex c62c8bdb6d..930d0801b3 100644--- a/scripts/database-maintenance-worker.mjs+++ b/scripts/database-maintenance-worker.mjs@@ -1,25 +1,20 @@#!/usr/bin/env node// Fixed internal worker entrypoint. No command, endpoint, environment, or-// control-directory arguments are accepted. It quiesces every owned writer and-// transfers the RECORDED operation (source dump → one target transaction). It-// never changes saved mode, restarts producers, or reopens admission: a-// committed import still awaits verified target restart (#8851).-import { runDatabaseTransfer } from '../server/services/databaseMaintenanceTransfer.js';+// control-directory arguments are accepted. It quiesces every owned writer,+// transfers the RECORDED operation (source dump → one target transaction),+// commits the saved mode, restarts the server with it, and releases admission+// only after that restarted process proved its own pool reached the target.+import { runDatabaseCutover } from '../server/services/databaseMaintenanceCutover.js';try {const args = process.argv.slice(2);if (args.length !== 2) throw new Error('Invalid worker identity');const [id, token] = args;- const result = await runDatabaseTransfer(id, token);- console.log(JSON.stringify(result));- // A committed import is NOT a successful cutover: saved mode, restart and- // admission release belong to the verified-restart stage.- console.error('⚠️ Database transfer imported; target restart verification is not yet integrated. Maintenance remains fenced.');- process.exitCode = 78;+ console.log(JSON.stringify(await runDatabaseCutover(id, token)));} catch (err) {// Never print tokens, paths, endpoints, or raw parser/OS exception messages.- // Transfer and quiescence refusals carry only bounded, redacted reasons.- console.error(['DATABASE_TRANSFER', 'DATABASE_WRITER_QUIESCENCE'].includes(err?.code)+ // Cutover, transfer and quiescence refusals carry only bounded reasons.+ console.error(['DATABASE_CUTOVER', 'DATABASE_TRANSFER', 'DATABASE_WRITER_QUIESCENCE'].includes(err?.code)? `⛔ ${err.message}`: '⛔ Database maintenance worker refused: ownership, writer, or transfer evidence is incomplete.');process.exitCode = 1;diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjsindex 3b0587b738..c2f6c86bd7 100644--- a/scripts/database-maintenance.mjs+++ b/scripts/database-maintenance.mjs@@ -1,13 +1,15 @@#!/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.-// Transfer runs only inside the owned internal worker; there is no command-// here that starts, resumes, forces, or skips it.+// Transfer, mode commit and restart run only inside the owned internal worker.+// `recover` relaunches that worker for the SAME recorded operation after its+// supervisor recorded an exit; there is no force, skip, or reverse command.import { createRequire } from 'node:module';import { join } from 'node:path';import { PATHS } from '../server/lib/paths.js';import { createDatabaseMaintenanceJournal } from '../server/lib/databaseMaintenanceJournal.js';import { createDatabaseWriterRegistry } from '../server/lib/databaseWriterRegistry.js';+import { createDatabaseAuthority } from '../server/lib/databaseAuthority.js';const journal = createDatabaseMaintenanceJournal();const require = createRequire(import.meta.url);@@ -20,7 +22,7 @@ function configuredEndpoints() {return { source: DATABASE_ENDPOINTS[DATABASE_MODE], endpoints: DATABASE_ENDPOINTS };}-function main() {+async function main() {const [command, ...args] = process.argv.slice(2);if (command === 'writers' && args.length === 0) {const counts = { unresolved: 0, launching: 0, launched: 0, exited: 0, abandoned: 0 };@@ -30,7 +32,10 @@ function main() {if (command === 'status' && args.length === 0) {const record = journal.read();// Endpoints are local-only; the operator-facing status needs only direction.- if (!record) return { stage: 'idle' };+ if (!record) {+ const last = createDatabaseAuthority().read();+ return last ? { stage: 'idle', lastCutover: { id: last.operationId, source: last.source.mode, target: last.target.mode } } : { stage: 'idle' };+ }const coordinator = journal.coordinatorStatus(record.id);return { id: record.id, stage: record.stage, source: record.source.mode, target: record.target.mode,...(coordinator.state === 'unclaimed' ? {} : { coordinator }),@@ -45,18 +50,27 @@ function main() {const record = journal.begin({ source, target: endpoints[targetMode] });return { id: record.id, stage: record.stage, source: sourceMode, target: targetMode };}+ if (command === 'recover' && args.length === 1) {+ const { recoverDatabaseCutover } = await import('../server/services/databaseMaintenanceCutover.js');+ return recoverDatabaseCutover(args[0]);+ }if (command === 'cancel' && args.length === 1) {return journal.cancel(args[0], configuredEndpoints().source);}- throw new Error('Usage: node scripts/database-maintenance.mjs status | writers | begin <native|docker> <native|docker> | cancel <operation-id>');+ throw new Error('Usage: node scripts/database-maintenance.mjs status | writers | begin <native|docker> <native|docker> | cancel <operation-id> | recover <operation-id>');}try {- console.log(JSON.stringify(main()));+ console.log(JSON.stringify(await main()));} catch (err) {// No filesystem paths, connection details, or raw parser inputs in output.- console.error(err.code === 'DATABASE_MAINTENANCE'+ console.error(err.code === 'DATABASE_CUTOVER' ? err.message : 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;}+// `recover` leaves a detached worker running; its handle's log tailer must+// not hold this command open (a released worker never writes an exit receipt+// back into the archived control directory). Drain output first: pipes are+// asynchronous on macOS.+process.stdout.write('', () => process.stderr.write('', () => process.exit()));diff --git a/server/lib/README.md b/server/lib/README.mdindex 408282c24c..9ef17fd0d2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -766,6 +766,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `messageBrowserIdentity.js` | Shared Outlook row extraction and identity-safe browser action scripts; exact unique targets and confirmed row removal. |-| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, worker process-group records, immutable recovery-dump and import receipts, and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |+| `databaseAuthority.js` | `createDatabaseAuthority(dataDir?)` durably records which backend a verified cutover released admission to and which it retired; `assertDatabasePoolAuthority(pool)` refuses a process whose pool still names the retired source (enforced at boot and on every pooled operation). |++| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, worker process-group records, immutable recovery-dump and import receipts, durable forward-only stages through `verified`, per-pid target proofs from a restarted server, token-persisting same-operation recovery, and `releaseAdmission` (authority record, then completed archive); source-only cancellation archives an unowned accepted operation. || `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |diff --git a/server/lib/databaseAuthority.js b/server/lib/databaseAuthority.jsnew file mode 100644index 0000000000..a962afc52e--- /dev/null+++ b/server/lib/databaseAuthority.js@@ -0,0 +1,108 @@+import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { z } from 'zod';+import { PATHS } from './paths.js';+import { assertNotRealDataWrite } from './testDataIsolation.js';++// Same shape as the maintenance journal's endpoint identity (kept local so the+// journal can depend on this module without a cycle).+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 authoritySchema = z.object({+ version: z.literal(1),+ operationId: z.string().uuid(),+ releasedAt: z.string().datetime(),+ source: endpointSchema,+ target: endpointSchema,+}).strict();++const normalizedHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(String(host).toLowerCase())+ ? 'loopback' : String(host).toLowerCase();+const sameEndpoint = (pool, endpoint) => normalizedHost(pool.host) === normalizedHost(endpoint.host)+ && Number(pool.port) === endpoint.port && pool.database === endpoint.database && pool.user === endpoint.user;++const staleBackendError = () => Object.assign(+ new Error('This process is connected to the database backend a completed cutover retired. Restart it with the saved configuration; see docs/STORAGE.md (retired backend).'),+ { status: 503, code: 'DATABASE_RETIRED_BACKEND' },+);+const unreadableError = () => Object.assign(+ new Error('The database authority record is unreadable. Inspect data/database-authority.json; see docs/STORAGE.md.'),+ { status: 503, code: 'DATABASE_MAINTENANCE' },+);++function syncDirectory(path) {+ if (process.platform === 'win32') return;+ const fd = openSync(path, 'r');+ try { fsyncSync(fd); } finally { closeSync(fd); }+}++/**+ * The backend a verified cutover released admission to, and the one it+ * retired. After release the retired source still holds a complete (now+ * stale) copy, so a process whose pool still names it — a PM2 app restarted+ * with a cached environment, a shell with an old PGPORT — must never write+ * there. Absent means no cutover has completed on this install.+ */+export function createDatabaseAuthority(dataDir = PATHS.data) {+ const recordPath = join(dataDir, 'database-authority.json');+ let cache = { key: null, value: null };++ const read = () => {+ let stat;+ try { stat = statSync(recordPath); } catch (err) {+ if (err.code === 'ENOENT') return null;+ throw unreadableError();+ }+ // Re-parse only when the file changes; the check runs on every pooled query.+ const key = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;+ if (cache.key === key) return cache.value;+ let value;+ try {+ if (!lstatSync(recordPath).isFile()) throw unreadableError();+ value = authoritySchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));+ } catch {+ throw unreadableError();+ }+ cache = { key, value };+ return value;+ };++ // Durable replace: a later cutover (e.g. back again) supersedes the record.+ const record = ({ operationId, source, target }) => {+ assertNotRealDataWrite(recordPath, 'database authority record');+ const value = authoritySchema.parse({ version: 1, operationId, releasedAt: new Date().toISOString(), source, target });+ const existing = read();+ if (existing?.operationId === operationId) return existing;+ mkdirSync(dataDir, { recursive: true });+ const pending = join(dataDir, `database-authority-${randomUUID()}.pending`);+ const fd = openSync(pending, 'wx', 0o600);+ try {+ writeFileSync(fd, JSON.stringify(value, null, 2) + '\n');+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ renameSync(pending, recordPath);+ syncDirectory(dataDir);+ return read();+ };++ // A pool naming the retired source (and not the released target) is stale.+ const assertPool = (pool) => {+ const authority = read();+ if (authority && sameEndpoint(pool, authority.source) && !sameEndpoint(pool, authority.target)) throw staleBackendError();+ return authority;+ };++ return { read, record, assertPool, sameEndpoint };+}++const authority = createDatabaseAuthority();+export const assertDatabasePoolAuthority = authority.assertPool;diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex 519ccac266..d57f3e930a 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto';import { z } from 'zod';import { PATHS } from './paths.js';import { assertNotRealDataWrite } from './testDataIsolation.js';+import { createDatabaseAuthority } from './databaseAuthority.js';export const databaseMaintenanceEndpointSchema = z.object({mode: z.enum(['native', 'docker']),@@ -53,6 +54,19 @@ const transferImportSchema = z.object({target: databaseMaintenanceEndpointSchema,sha256: sha256Schema,}).strict();+// A restarted ordinary server proved ITS OWN pool reaches the recorded target.+// Evidence, not authority: the coordinator accepts it only for the PM2 pid it+// reads back itself, and every booting process still proves its own pool.+const targetProofSchema = z.object({+ id: z.string().uuid(),+ pid: z.number().int().positive(),+ target: databaseMaintenanceEndpointSchema,+}).strict();+const recoveryIntentSchema = z.object({+ id: z.string().uuid(),+ previousToken: z.string().uuid(),+ recoveryToken: z.string().uuid(),+}).strict();const workerGroupSchema = coordinatorSchema.extend({ pgid: z.number().int().positive() }).strict();const decisionSchema = coordinatorSchema.extend({stage: z.enum(stages),@@ -364,9 +378,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return receipt;};- // Immutable no-replace publication of already-fsynced bytes. A retry of the- // identical record is accepted; a different record is never substituted.- const publishImmutable = (destination, value) => {+ // No-replace publication of already-fsynced bytes; the first writer wins.+ const publishFirst = (destination, value) => {const pending = join(activeDir, 'record-' + randomUUID() + '.pending');writeDurableExclusive(pending, value);try {@@ -377,6 +390,12 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {unlinkSync(pending);}syncDirectory(activeDir);+ };++ // Immutable publication: a retry of the identical record is accepted; a+ // different record is never substituted.+ const publishImmutable = (destination, value) => {+ publishFirst(destination, value);if (readFileSync(destination, 'utf8') !== JSON.stringify(value, null, 2) + '\n') throw databaseMaintenanceError();};@@ -481,11 +500,12 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {}assertCoordinator(id, previousToken);if (coordinatorStatus(id).state !== 'exited') throw databaseMaintenanceError();- // Only four transfer stages can advance here; each interrupted transition- // completion moves strictly forward, never reverses an import to success.+ // Every unreleased stage can advance here; each interrupted transition+ // completion moves strictly forward, never reverses an import to success+ // or a committed mode back to the source.while (true) {const current = read();- if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(current.stage)) throw databaseMaintenanceError();+ if (!stages.includes(current.stage)) throw databaseMaintenanceError();const decision = decide(id, previousToken, current.stage, { kind: 'recovery', recoveryToken });if (decision.kind === 'recovery') {if (decision.recoveryToken !== recoveryToken) throw databaseMaintenanceError();@@ -527,6 +547,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return current;}if (current.stage !== expectedStage) throw databaseMaintenanceError();+ // Mode commit is reachable only from a committed import of this operation.+ if (nextStage === 'committing' && !readTransferImport(id)) throw databaseMaintenanceError();// Do not reinterpret interrupted writes from the old publication protocol.if (existsSync(join(activeDir, 'stage-' + expectedStage + '.claim'))) throw databaseMaintenanceError();const decision = decide(id, token, expectedStage, { kind: 'transition', nextStage });@@ -579,7 +601,79 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {// Operation-scoped archive for detached-writer records proven quiescent.const reconciledWritersDirectory = join(activeDir, 'reconciled-writers');+ const targetProofPath = pid => join(activeDir, 'target-proof-' + z.number().int().positive().parse(pid) + '.json');++ // Published by a booting ordinary server AFTER its own pool passed the+ // read-only target verification. Only verifying/verified may carry one.+ const recordTargetProof = (id, pid) => {+ assertNotRealDataWrite(activeDir, 'database maintenance target proof');+ const current = read();+ if (!current || current.id !== id || !['verifying', 'verified'].includes(current.stage)) throw databaseMaintenanceError();+ publishImmutable(targetProofPath(pid), targetProofSchema.parse({ id, pid, target: current.target }));+ return readTargetProof(id, pid);+ };++ function readTargetProof(id, pid) {+ const current = read();+ if (!current || current.id !== id) throw databaseMaintenanceError();+ const proof = readRecord(targetProofPath(pid), targetProofSchema);+ if (proof && (proof.id !== id || proof.pid !== pid+ || JSON.stringify(proof.target) !== JSON.stringify(current.target))) throw databaseMaintenanceError();+ return proof;+ }++ /**+ * Same-operation recovery, as one retryable step for the operator/API. The+ * successor token is persisted BEFORE recoverCoordinator publishes it, so a+ * crash after publication is completed by the next call with the SAME token+ * instead of stranding an owner nobody can launch. Returns the token that may+ * launch a worker, or null while the current owner's worker has no exit+ * receipt (running, or interrupted before its supervisor recorded one).+ */+ const prepareRecovery = (id) => {+ assertNotRealDataWrite(activeDir, 'database maintenance recovery');+ const current = read();+ if (!current || current.id !== id) throw databaseMaintenanceError();+ const owner = readCoordinator(id);+ if (!owner) throw databaseMaintenanceError();+ const status = coordinatorStatus(id);+ if (status.state === 'unregistered') return owner.token;+ if (status.state !== 'exited') return null;+ const intentPath = join(activeDir, 'recovery-after-' + owner.token + '.json');+ // Concurrent requests race to publish; every one adopts the winner.+ if (!readRecord(intentPath, recoveryIntentSchema)) {+ publishFirst(intentPath, recoveryIntentSchema.parse({ id, previousToken: owner.token, recoveryToken: randomUUID() }));+ }+ const intent = readRecord(intentPath, recoveryIntentSchema);+ if (!intent || intent.id !== id || intent.previousToken !== owner.token) throw databaseMaintenanceError();+ return recoverCoordinator(id, owner.token, intent.recoveryToken);+ };++ /**+ * Reopen admission for a VERIFIED operation, from its entered worker only.+ * The authority record (target in, source retired) is durable BEFORE the+ * fence directory moves, so no process can be admitted without the stale-+ * backend check seeing it. A crash between the two leaves `verified` fenced+ * and the next recovery repeats both steps idempotently.+ */+ const releaseAdmission = (id, token) => {+ assertNotRealDataWrite(activeDir, 'database maintenance release');+ const current = assertEnteredCoordinatorWorker(id, token);+ if (current.stage !== 'verified' || !readTransferImport(id)) throw databaseMaintenanceError();+ createDatabaseAuthority(dataDir).record({ operationId: id, source: current.source, target: current.target });+ const archiveDir = join(dataDir, 'database-maintenance-completed');+ mkdirSync(archiveDir, { recursive: true, mode: 0o700 });+ const destination = join(archiveDir, id);+ if (existsSync(destination)) throw databaseMaintenanceError();+ assertEnteredCoordinatorWorker(id, token);+ renameSync(activeDir, destination);+ syncDirectory(archiveDir);+ syncDirectory(dataDir);+ return { id, stage: 'released', source: current.source.mode, target: current.target.mode };+ };+return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition, reconciledWritersDirectory,+ recordTargetProof, readTargetProof, prepareRecovery, releaseAdmission,reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator, assertCoordinatorWorker, enterCoordinatorWorker,readProducerSnapshot, recordProducerSnapshot, assertEnteredCoordinatorWorker, recordCoordinatorGroup,readPredecessorWorkers, transferDumpPath, readTransferDump, readTransferImport, recordTransferDump,diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.jsindex ebc7e4c443..9a5eb61df1 100644--- a/server/lib/databaseMaintenanceJournal.test.js+++ b/server/lib/databaseMaintenanceJournal.test.js@@ -60,7 +60,7 @@ describe('persistent database maintenance boundary', () => {expect(() => journal.transition(operation.id, 'wrong', 'accepted', 'quiescing')).toThrow();expect(() => journal.transition(operation.id, token, 'accepted', 'importing')).toThrow();let stage = 'accepted';- for (const next of ['quiescing', 'exporting', 'importing', 'committing', 'verifying', 'verified']) {+ for (const next of ['quiescing', 'exporting', 'importing']) {const result = node(`import {createDatabaseMaintenanceJournal} from ${JSON.stringify(moduleUrl)};const j=createDatabaseMaintenanceJournal(${JSON.stringify(data)});j.transition(${JSON.stringify(operation.id)}, ${JSON.stringify(token)}, ${JSON.stringify(stage)}, ${JSON.stringify(next)});`);@@ -70,8 +70,10 @@ describe('persistent database maintenance boundary', () => {expect(() => journal.assertAdmission()).toThrow();stage = next;}- // Even verified is evidence, not permission to reopen writers. The future- // coordinator must separately prove boot identity before releasing the fence.+ // Mode commit needs this operation's committed import receipt; the later+ // stages and release are covered end to end by databaseMaintenanceCutover.+ expect(() => journal.transition(operation.id, token, 'importing', 'committing')).toThrow();+ expect(journal.read().stage).toBe('importing');expect(() => journal.cancel(operation.id, source)).toThrow();});diff --git a/server/lib/databaseMaintenanceRecovery.test.js b/server/lib/databaseMaintenanceRecovery.test.jsindex f1384fecd1..86ef596d24 100644--- a/server/lib/databaseMaintenanceRecovery.test.js+++ b/server/lib/databaseMaintenanceRecovery.test.js@@ -238,18 +238,23 @@ describe('same-operation coordinator recovery', () => {expect(() => journal.assertAdmission()).toThrow();});- it('does not let a stale predecessor or later-stage recovery reopen an operation', () => {+ it('does not let a stale predecessor advance, or recovery reopen, an operation', () => {const operation = journal.begin({ source, target });const token = journal.acquireCoordinator(operation.id);const directory = journal.reserveCoordinatorWorker(operation.id, token);writeFileSync(join(directory, 'exit'), '0');let current = 'accepted';- for (const next of ['quiescing', 'exporting', 'importing', 'committing']) {+ for (const next of ['quiescing', 'exporting', 'importing']) {journal.transition(operation.id, token, current, next);current = next;}+ const successor = journal.recoverCoordinator(operation.id, token, randomUUID());+ // Ownership moved; the stage and the fence did not.+ expect(() => journal.transition(operation.id, token, 'importing', 'committing')).toThrow();expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();- expect(journal.read().stage).toBe('committing');+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });+ expect(successor).not.toBe(token);+ expect(journal.read().stage).toBe('importing');expect(() => journal.assertAdmission()).toThrow();});});diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.jsindex b1388aeb12..72bd6db256 100644--- a/server/lib/databaseMaintenanceWorker.test.js+++ b/server/lib/databaseMaintenanceWorker.test.js@@ -1,7 +1,9 @@// The real detached worker, end to end: supervisor launch, producer stop,-// writer reconciliation, db.sh dump/import. PM2 is replaced at its module-// boundary by a loader hook in the worker process only, and pg_dump/psql are-// disposable stubs; no live daemon, database or install data is touched.+// writer reconciliation, db.sh dump/import, mode commit, restart with target+// proof, and release. PM2 is replaced at its module boundary by a loader hook+// in the worker process only; pg_dump/psql are disposable stubs; the restarted+// "server" is a surrogate running the real boot handshake against a stubbed+// pg module. No live daemon, database or install data is touched.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { spawn, spawnSync } from 'node:child_process';import { randomUUID } from 'node:crypto';@@ -12,6 +14,9 @@ import { fileURLToPath, pathToFileURL } from 'node:url';import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';import { createDatabaseWriterRegistry } from './databaseWriterRegistry.js';import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';+import { installCutoverStubs } from '../test/fixtures/databaseCutoverStubs.js';++const cutoverFixtureUrl = new URL('../test/fixtures/databaseCutoverStubs.js', import.meta.url).href;const detachedUrl = new URL('./detachedSpawn.js', import.meta.url).href;const source = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };@@ -21,6 +26,7 @@ let journal;let env;let stubs;let strays;+let cutover;// Writes a PM2 module stand-in with file-backed state and a loader hook that// substitutes it for server/services/pm2.js.@@ -32,8 +38,22 @@ function installPm2Stub() {]));const stubModule = join(stubs.dir, 'pm2.mjs');writeFileSync(stubModule, `import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';+import { launchSurrogateServer, restartedServerEndpoint } from ${JSON.stringify(cutoverFixtureUrl)};const state = ${JSON.stringify(state)};-export async function listMaintenanceProcesses() { return JSON.parse(readFileSync(state, 'utf8')); }+const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };+export async function listMaintenanceProcesses() {+ return JSON.parse(readFileSync(state, 'utf8')).map(row => row.surrogate && !alive(row.pid) ? { ...row, status: 'errored', pid: 0 } : row);+}+export async function restartMaintenanceProducer(name) {+ const rows = JSON.parse(readFileSync(state, 'utf8'));+ const row = rows.find(value => value.name === name);+ appendFileSync(${JSON.stringify(join(stubs.dir, 'events.log'))}, 'restart ' + name + '\\n');+ row.surrogate = name === 'portos-server';+ row.pid = row.surrogate ? launchSurrogateServer(${JSON.stringify(root)}, ${JSON.stringify(stubs.dir)}, restartedServerEndpoint(${JSON.stringify(root)}, ${JSON.stringify(stubs.dir)})) : 2012;+ row.status = 'online';+ writeFileSync(state, JSON.stringify(rows));+ return { success: true };+}export async function stopApp(id) {const rows = JSON.parse(readFileSync(state, 'utf8'));const row = rows.find(value => value.pmId === id);@@ -60,6 +80,8 @@ beforeEach(() => {writeFileSync(join(root, 'server', 'cos-runner', 'index.js'), '');journal = createDatabaseMaintenanceJournal(join(root, 'data'));stubs = installDatabaseStubs(root);+ cutover = installCutoverStubs(root, stubs.dir, { source, target });+ writeFileSync(join(root, '.env'), 'PGMODE=native\n');strays = [];env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root, PATH: `${stubs.bin}${delimiter}${process.env.PATH}`,PGPASSWORD: 'example-password', PGHOST: 'inherited.example.invalid', PGHOSTADDR: '192.0.2.10',@@ -68,6 +90,7 @@ beforeEach(() => {});afterEach(() => {for (const group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }+ for (const pid of cutover.surrogatePids()) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }rmSync(root, { recursive: true, force: true });});@@ -84,16 +107,26 @@ function run(code) {child.once('close', status => resolve({ status, stdout, stderr }));});}+// Exit status of one worker launch. A worker that RELEASED admission moved its+// control directory with the fence, so its supervisor can publish no exit+// receipt; that outcome reports `released` once the worker process is gone.function launch(id, token) {- return run(`import {spawnDatabaseMaintenanceWorker} from ${JSON.stringify(detachedUrl)};+ return run(`import {existsSync} from 'node:fs';+ import {spawnDatabaseMaintenanceWorker} from ${JSON.stringify(detachedUrl)};try {const child=await spawnDatabaseMaintenanceWorker(${JSON.stringify(id)},${JSON.stringify(token)});child.stdout.on('data',chunk=>process.stdout.write(chunk));child.stderr.on('data',chunk=>process.stderr.write(chunk));child.on('error',()=>{process.exitCode=1;});- child.on('close',code=>{process.exitCode=code;});+ child.on('close',code=>{process.exitCode=code;process.exit();});+ const released=setInterval(()=>{+ if(existsSync(${JSON.stringify(controlDirFor(token))})) return;+ try{process.kill(child.pid,0);}catch{clearInterval(released);setTimeout(()=>{process.stdout.write('\\nRELEASED\\n',()=>process.exit(0));},300);}+ },50);} catch { process.exitCode=1; }`);}+const releasedResult = outcome => JSON.parse(outcome.stdout.split('\n').find(line => line.startsWith('{')));+const isReleased = outcome => outcome.status === 0 && outcome.stdout.includes('RELEASED');// Operator status: bounded stage evidence, never endpoints, paths or tokens.const status = () => {@@ -104,52 +137,66 @@ const status = () => {return JSON.parse(result.stdout);};const controlDirFor = token => join(root, 'data', 'database-maintenance', 'worker-' + token);+// The operator CLI's same-operation recovery, as a separate process.+const recover = id => new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [fileURLToPath(new URL('../../scripts/database-maintenance.mjs', import.meta.url)), 'recover', id],+ { env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000 });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', chunk => { stdout += chunk; });+ child.stderr.on('data', chunk => { stderr += chunk; });+ child.once('error', reject);+ child.once('close', status => resolve({ status, stdout, stderr }));+});const importsStarted = () => stubs.events().filter(line => line === 'import-start').length;describe.skipIf(process.platform === 'win32')('owned maintenance worker', () => {- it.each([[source, target], [target, source]])('transfers the recorded operation once while ordinary launches remain fenced (%#)', async (from, to) => {+ it.each([[source, target], [target, source]])('cuts over the recorded operation once and releases only after the restarted server proves the target (%#)', async (from, to) => {+ writeFileSync(join(root, '.env'), `PGMODE=${from.mode}\n`);const operation = journal.begin({ source: from, target: to });const token = journal.acquireCoordinator(operation.id);const outcomes = await Promise.all([launch(operation.id, token), launch(operation.id, token)]);- expect(outcomes.map(value => value.status).sort((a, b) => a - b)).toEqual([1, 78]);- const transferred = JSON.parse(outcomes.find(value => value.status === 78).stdout);- expect(transferred).toEqual({ id: operation.id, stage: 'importing', source: from.mode, target: to.mode,- imported: true, importCommitted: true, sourceRetained: true, restartVerified: false });- expect(stubs.events()).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none', 'import-start', 'import-commit']);+ const released = outcomes.filter(isReleased);+ expect(released, outcomes.map(value => value.stderr).join('\n')).toHaveLength(1);+ expect(outcomes.filter(value => value.status === 1)).toHaveLength(1);+ expect(releasedResult(released[0])).toEqual({ id: operation.id, stage: 'released', source: from.mode, target: to.mode,+ importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted: true });+ await vi.waitFor(() => expect(stubs.events()).toContain(`server booted ${to.port}`), { timeout: 15_000, interval: 50 });+ expect(stubs.events().slice(0, 6)).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none',+ 'import-start', 'import-commit', 'restart portos-server']);+ expect(stubs.events()).toContain('restart portos-cos');expect(stubs.invocations('pg_dump')).toEqual([`pg_dump -h ${from.host} -p ${from.port} -U ${from.user} -d ${from.database} --no-owner --no-privileges --if-exists --clean`]);expect(stubs.invocations('psql')).toEqual([`psql -h ${to.host} -p ${to.port} -U ${to.user} -d ${to.database} -v ON_ERROR_STOP=1 --single-transaction`]);expect(stubs.receivedVariables()).toEqual(['PGPASSWORD']);expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);- expect(journal.read()).toEqual({ ...operation, stage: 'importing' });- expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'exited', exitCode: 78 });+ expect(readFileSync(join(root, '.env'), 'utf8')).toBe(`PGMODE=${to.mode}\n`);+ expect(journal.read()).toBeNull();+ expect(status()).toEqual({ stage: 'idle', lastCutover: { id: operation.id, source: from.mode, target: to.mode } });expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toEqual([]);- expect(() => journal.assertAdmission()).toThrow();- const controlDir = controlDirFor(token);- const before = readdirSync(controlDir).sort();- expect(before).toEqual(expect.arrayContaining(['owner.json', 'started.json', 'group.json', 'stdout.log', 'stderr.log', 'pid', 'exit']));+ // The one-use owner cannot run again, and its evidence is archived.expect((await launch(operation.id, token)).status).toBe(1);- expect(readdirSync(controlDir).sort()).toEqual(before);- expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');+ expect(readdirSync(join(root, 'data', 'database-maintenance-completed', operation.id, 'worker-' + token)))+ .toEqual(expect.arrayContaining(['owner.json', 'started.json', 'group.json', 'stdout.log', 'stderr.log', 'pid']));+ }, 90_000);- // Neither knowing the token nor passing extra spawn options authorizes a- // different executable, arguments, control directory, or ordinary child.- const ran = join(root, 'ordinary-ran');- const ordinary = await run(`import {spawnDetached} from ${JSON.stringify(detachedUrl)};- const child=await spawnDetached(process.execPath,['-e',${JSON.stringify(`require('fs').writeFileSync(${JSON.stringify(ran)},'bad')`)}],{- controlDir:${JSON.stringify(join(root, 'ordinary'))}, maintenanceCoordinator:{id:${JSON.stringify(operation.id)},token:${JSON.stringify(token)}}});- child.on('error',()=>{process.exitCode=1;}); child.on('close',()=>{process.exitCode=2;});`);- expect(ordinary.status).toBe(1);- expect(existsSync(ran)).toBe(false);- // A recovered owner re-proves quiescence but never re-imports a committed transfer.- const successor = journal.recoverCoordinator(operation.id, token, randomUUID());+ it('relaunches only the recorded operation once across repeated operator recovery', async () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ stubs.setMode('dump', 'fail');expect((await launch(operation.id, token)).status).toBe(1);- const resumed = await launch(operation.id, successor);- expect(resumed.status).toBe(78);- expect(JSON.parse(resumed.stdout)).toMatchObject({ imported: false, importCommitted: true });- expect(stubs.invocations('pg_dump')).toHaveLength(1);+ expect(status()).toMatchObject({ stage: 'exporting', coordinator: { state: 'exited', exitCode: 1 } });+ stubs.setMode('dump', 'ok');+ const outcomes = await Promise.all([recover(operation.id), recover(operation.id)]);+ expect(outcomes.map(value => value.status), outcomes.map(value => value.stderr).join('\n')).toEqual([0, 0]);+ expect(outcomes.map(value => JSON.parse(value.stdout).recovery).sort()).toEqual(['launched', 'running']);+ await vi.waitFor(() => expect(stubs.events()).toContain(`server booted ${target.port}`), { timeout: 30_000, interval: 50 });+ await vi.waitFor(() => expect(journal.read()).toBeNull(), { timeout: 10_000, interval: 50 });+ // One recovered worker: one export retry, one import, one server restart.+ expect(stubs.invocations('pg_dump')).toHaveLength(2);expect(importsStarted()).toBe(1);- expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');- expect(journal.read()).toEqual({ ...operation, stage: 'importing' });+ expect(stubs.events().filter(line => line === 'restart portos-server')).toHaveLength(1);+ // A released operation has nothing left to recover.+ expect((await recover(operation.id)).status).toBe(1);}, 90_000);// Regression caught: a successor importing while an import started by a@@ -166,6 +213,16 @@ describe.skipIf(process.platform === 'win32')('owned maintenance worker', () =>expect((await first).status).not.toBe(78);await vi.waitFor(() => expect(journal.coordinatorStatus(operation.id).state).toBe('exited'), { timeout: 10_000, interval: 50 });+ // Neither knowing the token nor passing extra spawn options authorizes a+ // different executable, arguments, control directory, or ordinary child.+ const ran = join(root, 'ordinary-ran');+ const ordinary = await run(`import {spawnDetached} from ${JSON.stringify(detachedUrl)};+ const child=await spawnDetached(process.execPath,['-e',${JSON.stringify(`require('fs').writeFileSync(${JSON.stringify(ran)},'bad')`)}],{+ controlDir:${JSON.stringify(join(root, 'ordinary'))}, maintenanceCoordinator:{id:${JSON.stringify(operation.id)},token:${JSON.stringify(token)}}});+ child.on('error',()=>{process.exitCode=1;}); child.on('close',()=>{process.exitCode=2;});`);+ expect(ordinary.status).toBe(1);+ expect(existsSync(ran)).toBe(false);+const second = journal.recoverCoordinator(operation.id, token, randomUUID());const refused = await launch(operation.id, second);expect(refused.status).toBe(1);@@ -178,12 +235,12 @@ describe.skipIf(process.platform === 'win32')('owned maintenance worker', () =>stubs.setMode('import', 'ok');const third = journal.recoverCoordinator(operation.id, second, randomUUID());const done = await launch(operation.id, third);- expect(done.status).toBe(78);+ expect(isReleased(done), done.stderr).toBe(true);expect(stubs.invocations('pg_dump')).toHaveLength(1);expect(importsStarted()).toBe(2);- expect(status()).toMatchObject({ stage: 'importing', transfer: { dump: 'recorded', import: 'committed' } });+ expect(status()).toMatchObject({ stage: 'idle', lastCutover: { id: operation.id } });expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);- expect(journal.read()).toEqual({ ...operation, stage: 'importing' });+ expect(journal.read()).toBeNull();}, 90_000);it('retains unresolved inventory and refuses to export', async () => {diff --git a/server/lib/db.js b/server/lib/db.jsindex 5258f3377a..424644cca9 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -9,6 +9,7 @@ import pg from 'pg';import { AsyncLocalStorage } from 'node:async_hooks';import { isTestRunner } from './runtimeEnv.js';import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';+import { assertDatabasePoolAuthority } from './databaseAuthority.js';const { Pool } = pg;@@ -214,8 +215,10 @@ function maintenanceError() {}async function databaseOperation(fn) {- // A process-local restore context cannot bypass a durable cutover fence.+ // A process-local restore context cannot bypass a durable cutover fence,+ // and a pool still naming a cutover's retired backend never reaches it.assertDatabaseAdmission();+ assertDatabasePoolAuthority(POOL_CONFIG);if (maintenanceActive && !databaseContext.getStore()?.active) throw maintenanceError();const context = { active: true };const pending = databaseContext.run(context, async () => fn());@@ -231,6 +234,7 @@ async function databaseOperation(fn) {/** Drain admitted database work and reject new work until restore completes. */export async function withDatabaseMaintenance(fn) {assertDatabaseAdmission();+ assertDatabasePoolAuthority(POOL_CONFIG);if (maintenanceActive || databaseContext.getStore()?.active) throw maintenanceError();maintenanceActive = true;const context = { active: true };diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex f1065bb503..28143907e4 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -76,6 +76,10 @@ import { isPlainObject } from './objects.js';import { escapeRegExp } from './textUtils.js';export const HOST_CONTROL_ROUTES = Object.freeze([+ // Database cutover stops/restarts PortOS under PM2 and rewrites .env (#8851).+ 'POST /api/database/maintenance/cutover',+ 'POST /api/database/maintenance/recover',+// Setting a password mints an operator session: bootstrap must be local,// and rotation must already hold operator authority (#8771).'POST /api/auth/password',diff --git a/server/lib/index.js b/server/lib/index.jsindex 5a7f50971a..44d4e07eeb 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -748,6 +748,8 @@ export * from './styleSourcePrompt.js';export * from './messageBrowserIdentity.js';+export * from './databaseAuthority.js';+export * from './databaseMaintenanceJournal.js';export * from './databaseWriterRegistry.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d0c918ee6f..59f2eb31d0 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1642,6 +1642,12 @@ export const databaseMaintenancePreflightSchema = z.object({target: z.enum(DB_BACKENDS)}).strict().refine(value => value.source !== value.target, { message: 'Source and target must differ' });+// POST /api/database/maintenance/cutover — accepts the offline cutover (202).+export const databaseMaintenanceCutoverSchema = databaseMaintenancePreflightSchema;++// POST /api/database/maintenance/recover — same-operation recovery only.+export const databaseMaintenanceRecoverSchema = z.object({ id: z.string().uuid() }).strict();+// POST /api/database/{start,stop,destroy} — operate on a named backend.export const databaseBackendSchema = z.object({backend: z.enum(DB_BACKENDS)diff --git a/server/routes/database.js b/server/routes/database.jsindex 304ff0048b..e2eefa564c 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -5,7 +5,9 @@ import {databaseSwitchSchema,databaseBackendSchema,databaseExportSchema,- databaseMaintenancePreflightSchema+ databaseMaintenancePreflightSchema,+ databaseMaintenanceCutoverSchema,+ databaseMaintenanceRecoverSchema} from '../lib/validation.js';import * as dbAdmin from '../services/dbAdmin.js';@@ -25,6 +27,22 @@ router.post('/maintenance/preflight', asyncHandler(async (req, res) => {res.json(await dbAdmin.preflightDatabaseMaintenance(direction));}));+// Accept the offline cutover. 202: the detached worker then stops PortOS,+// transfers, commits mode and restarts; progress is the status route above+// (and scripts/database-maintenance.mjs status while the server is down).+router.post('/maintenance/cutover', asyncHandler(async (req, res) => {+ const direction = validateRequest(databaseMaintenanceCutoverSchema, req.body);+ res.set('Cache-Control', 'no-store');+ res.status(202).json(await dbAdmin.acceptDatabaseCutover(direction));+}));++// Relaunch the worker for the SAME recorded operation after its exit receipt.+router.post('/maintenance/recover', asyncHandler(async (req, res) => {+ const { id } = validateRequest(databaseMaintenanceRecoverSchema, req.body);+ res.set('Cache-Control', 'no-store');+ res.status(202).json(await dbAdmin.recoverDatabaseCutover(id));+}));+// GET /api/database/status — current mode, connectivity, row counts, resource statsrouter.get('/status', asyncHandler(async (_req, res) => {res.json(await dbAdmin.getStatus());diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex f2a79f4cc9..cdfaeeb107 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -187,16 +187,16 @@ describe('database maintenance status', () => {const operation = journal.begin({ source, target: { ...source, mode: 'docker', port: 5561 } });const accepted = await request(app).get('/api/database/maintenance/status');expect(accepted.body).toEqual({- id: operation.id, stage: 'accepted', source: 'native', target: 'docker', fenced: true,+ id: operation.id, stage: 'accepted', coordinator: 'unclaimed', source: 'native', target: 'docker', fenced: true,});const owner = journal.acquireCoordinator(operation.id);- const stages = ['accepted', 'quiescing', 'exporting', 'importing', 'committing', 'verifying', 'verified'];+ const stages = ['accepted', 'quiescing', 'exporting', 'importing'];for (let i = 1; i < stages.length; i++) {journal.transition(operation.id, owner, stages[i - 1], stages[i]);}- const verified = await request(app).get('/api/database/maintenance/status');- expect(verified.status).toBe(200);- expect(verified.body).toEqual({ ...accepted.body, stage: 'verified' });+ const importing = await request(app).get('/api/database/maintenance/status');+ expect(importing.status).toBe(200);+ expect(importing.body).toEqual({ ...accepted.body, stage: 'importing', coordinator: 'unregistered' });expect(() => journal.assertAdmission()).toThrow();expect(execFile).not.toHaveBeenCalled();expect(spawn).not.toHaveBeenCalled();diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.jsindex 7ac73ef9f6..7a76a600a5 100644--- a/server/routes/databasePreflight.test.js+++ b/server/routes/databasePreflight.test.js@@ -22,6 +22,11 @@ vi.mock('../services/updatePreflight.js', () => ({vi.mock('../lib/childProcess.js', async importOriginal => ({...await importOriginal(), execFile: vi.fn(), spawn: vi.fn(),}));+// The detached cutover worker is launched only after acceptance; never here.+vi.mock('../lib/detachedSpawn.js', async importOriginal => ({+ ...await importOriginal(),+ spawnDatabaseMaintenanceWorker: vi.fn(async () => ({ on() {} })),+}));import databaseRoutes from './database.js';import { PATHS } from '../lib/paths.js';@@ -31,6 +36,8 @@ import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJourimport { cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';import { getSystemActivity } from '../services/activeProcessing.js';import { countActiveCosAgents, getPersistentMindImageWorkGuard } from '../services/updatePreflight.js';+import { spawnDatabaseMaintenanceWorker } from '../lib/detachedSpawn.js';+import { hostControlRouteGate } from '../services/authGate.js';const idle = () => ({jobs: [], extras: { imageTo3d: [] }, agents: { trusted: true, active: 0, queued: 0 },@@ -43,6 +50,7 @@ app.use(express.json());app.use('/api/database', databaseRoutes);app.use((err, _req, res, _next) => res.status(err.status ?? 500).json({ error: err.message, code: err.code }));const preflight = (body = { source: 'native', target: 'docker' }) => request(app).post('/api/database/maintenance/preflight').send(body);+const accept = (body = { source: 'native', target: 'docker' }) => request(app).post('/api/database/maintenance/cutover').send(body);beforeEach(() => {vi.clearAllMocks();@@ -57,6 +65,7 @@ beforeEach(() => {afterEach(() => {vi.unstubAllEnvs();rmSync(join(PATHS.data, 'database-maintenance'), { recursive: true, force: true });+ rmSync(join(PATHS.data, 'database-maintenance-cancelled'), { recursive: true, force: true });expect(execFile).not.toHaveBeenCalled();expect(spawn).not.toHaveBeenCalled();expect(query).not.toHaveBeenCalled();@@ -186,3 +195,87 @@ describe('database maintenance preflight HTTP contract', () => {expect(getSystemActivity).not.toHaveBeenCalled();});});++describe('database cutover acceptance HTTP contract', () => {+ const busy = () => ({ ...idle(), agents: { trusted: true, active: 1, queued: 0 } });++ it.each(['native', 'docker'])('accepts a trusted idle %s source, takes ownership, and launches one worker', async source => {+ saveMode(source);+ POOL_CONFIG.port = source === 'native' ? 5432 : 5561;+ const target = source === 'native' ? 'docker' : 'native';+ const result = await accept({ source, target });+ expect(result.status).toBe(202);+ expect(result.headers['cache-control']).toBe('no-store');+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ const operation = journal.read();+ expect(result.body).toEqual({ id: operation.id, stage: 'accepted', source, target, accepted: true });+ expect(operation).toMatchObject({ stage: 'accepted', source: { mode: source }, target: { mode: target } });+ // Owned before launch: cancellation and a second owner are refused.+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });+ expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(1);+ expect(spawnDatabaseMaintenanceWorker.mock.calls[0][0]).toBe(operation.id);+ expect(() => journal.acquireCoordinator(operation.id)).toThrow();+ // Acceptance itself never changes the saved mode.+ expect(readFileSync(join(PATHS.installRoot, '.env'), 'utf8')).toBe(`PGMODE=${source}\n`);+ expect((await accept({ source, target })).status).toBe(503);+ });++ it('refuses stale and reversed requests without publishing an operation', async () => {+ expect((await accept({ source: 'docker', target: 'native' })).body.code).toBe('DATABASE_PREFLIGHT_STALE');+ POOL_CONFIG.port = 6000;+ expect((await accept()).body.code).toBe('DATABASE_PREFLIGHT_STALE');+ expect(createDatabaseMaintenanceJournal(PATHS.data).read()).toBeNull();+ expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();+ });++ it.each([+ ['work admitted before the fence', () => busy()],+ ['a saved-mode change', () => { saveMode('docker'); return idle(); }],+ ])('cancels the unowned operation when the final fenced check sees %s', async (_label, observe) => {+ getSystemActivity.mockResolvedValueOnce(idle()).mockImplementationOnce(async () => {+ // This observation runs AFTER publication: admission is already closed.+ expect(createDatabaseMaintenanceJournal(PATHS.data).isFenced()).toBe(true);+ return observe();+ });+ const result = await accept();+ expect(result.status).toBe(409);+ expect(['DATABASE_PREFLIGHT_BUSY', 'DATABASE_PREFLIGHT_STALE']).toContain(result.body.code);+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();+ expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();+ });++ it('requires host-control authority before accepting or recovering', async () => {+ const gated = express();+ gated.use((req, _res, next) => { req.portosAuthContext = { enabled: true, authenticated: false }; next(); });+ gated.use(hostControlRouteGate);+ gated.use(express.json());+ gated.use('/api/database', databaseRoutes);+ for (const path of ['cutover', 'recover']) {+ const result = await request(gated).post(`/api/database/maintenance/${path}`).send({ source: 'native', target: 'docker' });+ expect(result.status).toBe(403);+ }+ expect(getSystemActivity).not.toHaveBeenCalled();+ expect(createDatabaseMaintenanceJournal(PATHS.data).read()).toBeNull();+ });++ it('recovers only the recorded operation after its worker exit receipt', async () => {+ const recover = id => request(app).post('/api/database/maintenance/recover').send({ id });+ expect((await recover('not-a-uuid')).status).toBe(400);+ const accepted = await accept();+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ const [id, token] = spawnDatabaseMaintenanceWorker.mock.calls[0];+ const directory = journal.reserveCoordinatorWorker(id, token);+ // Still running (no receipt): recovery launches nothing.+ expect((await recover(id)).body).toEqual({ id, stage: 'accepted', recovery: 'running' });+ writeFileSync(join(directory, 'exit'), '1\n');+ expect((await recover('00000000-0000-4000-8000-000000000000')).status).toBe(503);+ const recovered = await recover(id);+ expect(recovered.status).toBe(202);+ expect(recovered.body).toEqual({ id: accepted.body.id, stage: 'accepted', recovery: 'launched' });+ expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(2);+ expect(spawnDatabaseMaintenanceWorker.mock.calls[1][0]).toBe(id);+ expect(spawnDatabaseMaintenanceWorker.mock.calls[1][1]).not.toBe(token);+ });+});diff --git a/server/services/README.md b/server/services/README.mdindex d63f117874..490e486a20 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -6,6 +6,8 @@ image-generation paths below are useful entry points when tracing render jobs.| Module | Responsibility || --- | --- |+| `databaseCutoverHandshake.js` | Narrow fenced-boot path for the ordinary server: at `verifying`/`verified` prove this process's own pool reaches the recorded target, publish a per-pid proof, and wait for admission release before the app graph loads. |+| `databaseMaintenanceCutover.js` | Internal cutover worker body (transfer → forward-only `.env` mode commit → server restart with target proof → release → CoS restart) and `recoverDatabaseCutover(id)` same-operation recovery for the CLI/API. || `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. || `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. || `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |diff --git a/server/services/databaseBootFence.js b/server/services/databaseBootFence.jsindex 1e2a9a13da..d3d35702f8 100644--- a/server/services/databaseBootFence.js+++ b/server/services/databaseBootFence.js@@ -1,5 +1,10 @@// Evaluate before importing either managed process's application graph.-// A pending or damaged journal must not allow boot-time writers/schedulers.+// A pending or damaged journal must not allow boot-time writers/schedulers,+// and a process whose pool still names the backend a completed cutover+// retired (a cached PM2 environment, a stale shell PGPORT) must not boot.import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';+import { assertDatabasePoolAuthority } from '../lib/databaseAuthority.js';+import { POOL_CONFIG } from '../lib/db.js';assertDatabaseAdmission();+assertDatabasePoolAuthority(POOL_CONFIG);diff --git a/server/services/databaseCutoverHandshake.js b/server/services/databaseCutoverHandshake.jsnew file mode 100644index 0000000000..bdcae6b921--- /dev/null+++ b/server/services/databaseCutoverHandshake.js@@ -0,0 +1,53 @@+import { setTimeout as delay } from 'node:timers/promises';+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { createDatabaseAuthority } from '../lib/databaseAuthority.js';++const RELEASE_TIMEOUT_MS = 300_000;+const POLL_MS = 250;++const refused = (reason) => Object.assign(+ new Error(`Database cutover boot refused: ${reason}. Maintenance remains fenced.`),+ { code: 'DATABASE_MAINTENANCE' },+);++/**+ * Narrow startup handshake for the ordinary server while a cutover is fenced.+ * Imports only the journal and the pool module — never routes, migrations,+ * schedulers or the CoS graph — so nothing writes before this returns.+ *+ * At `verifying`/`verified`, THIS process proves its own actual pool reaches+ * the recorded target (read-only; the pool's captured host/port/database/user+ * must equal the record), publishes that proof under its pid, and waits for+ * the coordinator to release admission. It returns only when the fence is gone+ * AND the released authority names this operation's target as this pool.+ * Any other stage, a wrong pool, an unhealthy target, or a different+ * operation throws and the process exits still fenced.+ */+export async function awaitDatabaseCutoverRelease({ releaseTimeoutMs = RELEASE_TIMEOUT_MS, pollMs = POLL_MS } = {}) {+ const journal = createDatabaseMaintenanceJournal();+ const operation = journal.read();+ if (!operation) return { released: false };+ if (!['verifying', 'verified'].includes(operation.stage)) throw refused(`stage ${operation.stage} does not admit a restart`);+ const { POOL_CONFIG, verifyDatabaseMaintenanceTarget } = await import('../lib/db.js');+ await verifyDatabaseMaintenanceTarget(operation.id).catch(() => {+ throw refused('this process could not prove the recorded target backend');+ });+ journal.recordTargetProof(operation.id, process.pid);+ console.log(`🗄️ Database cutover target verified by pid ${process.pid}; waiting for admission release`);++ const deadline = Date.now() + releaseTimeoutMs;+ while (journal.isFenced()) {+ const current = journal.read();+ if (current && (current.id !== operation.id || !['verifying', 'verified'].includes(current.stage))) {+ throw refused('the fenced operation changed');+ }+ if (Date.now() >= deadline) throw refused('admission was not released');+ await delay(pollMs);+ }+ const authority = createDatabaseAuthority();+ const released = authority.read();+ if (released?.operationId !== operation.id || !authority.sameEndpoint(POOL_CONFIG, released.target)) {+ throw refused('the released backend is not this process\'s pool');+ }+ return { released: true, id: operation.id };+}diff --git a/server/services/databaseMaintenanceCutover.js b/server/services/databaseMaintenanceCutover.jsnew file mode 100644index 0000000000..1eb85a17eb--- /dev/null+++ b/server/services/databaseMaintenanceCutover.js@@ -0,0 +1,192 @@+import { closeSync, fsyncSync, openSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { setTimeout as delay } from 'node:timers/promises';+import { join } from 'node:path';+import { spawn } from '../lib/childProcess.js';+import { PATHS } from '../lib/paths.js';+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { isTestRunner } from '../lib/runtimeEnv.js';+import { isDisposableRoot } from '../lib/dataRoot.js';+import { runDatabaseTransfer } from './databaseMaintenanceTransfer.js';+import { readRecordedProducers } from './databaseMaintenanceProducers.js';+import { restartMaintenanceProducer } from './pm2.js';++const TRANSFER_STAGES = ['accepted', 'quiescing', 'exporting', 'importing'];+const PROOF_TIMEOUT_MS = 180_000;+const POLL_MS = 250;++const refused = (reason) => Object.assign(+ new Error(`Database cutover refused: ${reason}. Maintenance remains fenced.`),+ { code: 'DATABASE_CUTOVER' },+);++function syncPath(path) {+ if (process.platform === 'win32') return;+ const fd = openSync(path, 'r');+ try { fsyncSync(fd); } finally { closeSync(fd); }+}++/**+ * The endpoint the SAVED configuration resolves to, evaluated in a fresh+ * process exactly as the next `pm2 restart ecosystem.config.cjs` will. This+ * process's own require cache and environment captured the pre-cutover mode.+ */+function readSavedEndpoint() {+ const config = join(PATHS.installRoot, 'ecosystem.config.cjs');+ const code = `const c=require(${JSON.stringify(config)});process.stdout.write(JSON.stringify(c.DATABASE_ENDPOINTS?.[c.DATABASE_MODE]??null))`;+ return new Promise((resolve) => {+ const child = spawn(process.execPath, ['-e', code], { cwd: PATHS.installRoot, stdio: ['ignore', 'pipe', 'ignore'] });+ let stdout = '';+ child.stdout.on('data', chunk => { if (stdout.length < 4096) stdout += chunk; });+ child.once('error', () => resolve(null));+ child.once('close', status => {+ try { resolve(status === 0 ? JSON.parse(stdout) : null); } catch { resolve(null); }+ });+ });+}++async function assertSavedTarget(target) {+ if (JSON.stringify(await readSavedEndpoint()) !== JSON.stringify(target)) {+ throw refused('the saved configuration does not resolve to the recorded target');+ }+}++/**+ * Forward-only, idempotent mode commit: rewrite `.env` PGMODE to the RECORDED+ * target. Recovery at `committing` repeats exactly this write — it never+ * guesses from the file's current contents or restores the source mode.+ * Every other line is preserved byte for byte.+ */+async function commitSavedMode(target) {+ const envPath = join(PATHS.installRoot, '.env');+ // .env lives beside data/, outside the data-root write guard: a test run+ // must never rewrite a real install's configuration.+ if (isTestRunner() && !isDisposableRoot(PATHS.installRoot)) {+ throw refused('a test run cannot commit a real install configuration');+ }+ let content = '';+ let mode = 0o600;+ try {+ content = readFileSync(envPath, 'utf8');+ mode = statSync(envPath).mode & 0o777;+ } catch (err) {+ if (err.code !== 'ENOENT') throw refused('the saved configuration is unreadable');+ }+ const line = `PGMODE=${target.mode}`;+ const next = /^PGMODE=.*$/m.test(content)+ ? content.replace(/^PGMODE=.*$/gm, line)+ : `${content}${content && !content.endsWith('\n') ? '\n' : ''}${line}\n`;+ if (next !== content) {+ const pending = join(PATHS.installRoot, `.env.${randomUUID()}.pending`);+ const fd = openSync(pending, 'wx', mode);+ try {+ writeFileSync(fd, next);+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ renameSync(pending, envPath);+ syncPath(PATHS.installRoot);+ }+ await assertSavedTarget(target);+}++/**+ * Restart the recorded server with the committed configuration and wait for+ * THAT restarted process — the one PM2 reports now — to publish proof that its+ * own pool reached the recorded target. PM2 `online`, the saved mode, or a+ * proof from an earlier pid is not success. The server is restarted at most+ * once per attempt; a crash-looping or wrong-pool server times out fenced.+ */+async function awaitRestartedTarget(journal, id, token, saved, { proofTimeoutMs = PROOF_TIMEOUT_MS, pollMs = POLL_MS }) {+ const deadline = Date.now() + proofTimeoutMs;+ let restarted = false;+ while (true) {+ journal.assertEnteredCoordinatorWorker(id, token);+ const server = (await readRecordedProducers(saved)).find(row => row.name === 'portos-server');+ if (server.status === 'online' && server.pid > 0 && journal.readTargetProof(id, server.pid)) return server.pid;+ if (server.status !== 'online' && !restarted) {+ journal.assertEnteredCoordinatorWorker(id, token);+ const result = await restartMaintenanceProducer('portos-server').catch(() => null);+ if (result?.success !== true) throw refused('the server could not be restarted');+ restarted = true;+ }+ if (Date.now() >= deadline) throw refused('the restarted server did not prove the target backend');+ await delay(pollMs);+ }+}++/**+ * Internal worker body for one entered coordinator. Transfer stages run the+ * offline transfer (quiescence, recorded dump, one target transaction); then:+ *+ * importing → committing only with this operation's committed import receipt+ * committing → verifying after `.env` durably names the target and a fresh+ * evaluation of the saved config resolves to it+ * verifying → verified after the restarted server proved its own pool+ * verified → released authority record, then the fence moves to the+ * completed archive; CoS restarts afterward+ *+ * Source authority holds until the mode commit; target authority afterward.+ * A recovered successor resumes at the recorded stage and never reverses.+ * `options` only shortens waits for subprocess tests.+ */+export async function runDatabaseCutover(id, token, options = {}) {+ const journal = createDatabaseMaintenanceJournal();+ let operation = journal.enterCoordinatorWorker(id, token);+ if (TRANSFER_STAGES.includes(operation.stage)) {+ await runDatabaseTransfer(id, token, { ...options, entered: true });+ operation = journal.assertEnteredCoordinatorWorker(id, token);+ }+ const saved = journal.readProducerSnapshot(id, token);+ if (!saved) throw refused('the producer identities were never recorded');+ if (operation.stage === 'importing') {+ if (!journal.readTransferImport(id)) throw refused('the target import has not committed');+ operation = journal.transition(id, token, 'importing', 'committing');+ }+ if (operation.stage === 'committing') {+ await commitSavedMode(operation.target);+ journal.assertEnteredCoordinatorWorker(id, token);+ operation = journal.transition(id, token, 'committing', 'verifying');+ }+ if (operation.stage === 'verifying') {+ await awaitRestartedTarget(journal, id, token, saved, options);+ operation = journal.transition(id, token, 'verifying', 'verified');+ }+ if (operation.stage !== 'verified') throw refused(`stage ${operation.stage} cannot be released`);+ // A hand edit while fenced must never release admission onto another backend.+ await assertSavedTarget(operation.target);+ journal.releaseAdmission(id, token);++ // Admission is open; CoS boots through its own fence and authority check.+ let cosRestarted = false;+ if (saved.find(row => row.name === 'portos-cos')?.status === 'online') {+ cosRestarted = (await restartMaintenanceProducer('portos-cos').catch(() => null))?.success === true;+ if (!cosRestarted) console.error('❌ Database cutover released, but portos-cos did not restart; start it with pm2');+ }+ return { id, stage: 'released', source: operation.source.mode, target: operation.target.mode,+ importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted };+}++/**+ * Same-operation recovery for the operator CLI and the authenticated API.+ * Requires the current owner's supervisor exit receipt (or an owner whose+ * worker was never reserved); repeated calls reuse the one persisted successor+ * and never start a second worker for it. Returns bounded status only.+ */+export async function recoverDatabaseCutover(id) {+ const journal = createDatabaseMaintenanceJournal();+ const token = journal.prepareRecovery(id);+ if (!token) return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'running' };+ const { spawnDatabaseMaintenanceWorker } = await import('../lib/detachedSpawn.js');+ let worker;+ try {+ worker = await spawnDatabaseMaintenanceWorker(id, token);+ } catch {+ // A concurrent recovery already reserved this successor's one-use worker.+ if (journal.coordinatorStatus(id).state === 'awaiting-exit') return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'running' };+ throw refused('the recovery worker could not be launched');+ }+ worker.on('error', () => console.error('❌ Database cutover recovery worker failed to launch'));+ return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'launched' };+}diff --git a/server/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.jsnew file mode 100644index 0000000000..10fa182c1a--- /dev/null+++ b/server/services/databaseMaintenanceCutover.test.js@@ -0,0 +1,236 @@+// Offline cutover past the transfer: forward-only mode commit, restart of the+// recorded server with the committed configuration, the restarted process's+// own target proof, and admission release. PM2 is mocked at its module+// boundary; pg_dump/psql are disposable stubs; the "server" is a surrogate+// process running the REAL boot handshake and boot fence against a stubbed pg+// module. No live database, PM2 daemon, install configuration or data.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';+import { installCutoverStubs, restartedServerEndpoint } from '../test/fixtures/databaseCutoverStubs.js';++const context = vi.hoisted(() => ({ root: undefined, list: null, stop: null, restart: null }));+vi.mock('../lib/paths.js', async original => {+ const actual = await original();+ return { ...actual, PATHS: new Proxy(actual.PATHS, {+ get: (target, key) => {+ if (key === 'data' && context.root) return context.root + '/data';+ if (key === 'installRoot' && context.root) return context.root;+ return target[key];+ },+ }) };+});+vi.mock('./pm2.js', () => ({+ listMaintenanceProcesses: (...args) => context.list(...args),+ stopApp: (...args) => context.stop(...args),+ restartMaintenanceProducer: (...args) => context.restart(...args),+}));+const { createDatabaseMaintenanceJournal } = await import('../lib/databaseMaintenanceJournal.js');+const { createDatabaseAuthority } = await import('../lib/databaseAuthority.js');+const { runDatabaseTransfer } = await import('./databaseMaintenanceTransfer.js');+const { runDatabaseCutover } = await import('./databaseMaintenanceCutover.js');++const native = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };+const docker = { mode: 'docker', host: 'docker.example.invalid', port: 5561, database: 'example_test', user: 'example' };+const fast = { graceMs: 1500, pollMs: 20, proofTimeoutMs: 4000 };+const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };+const savedEnv = { ...process.env };++let root;+let journal;+let stubs;+let cutover;+let rows;+let operation;+let token;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'database-cutover-'));+ writeFileSync(join(root, '.portos-disposable-root'), '');+ mkdirSync(join(root, 'server', 'cos-runner'), { recursive: true });+ writeFileSync(join(root, 'server', 'start.js'), '');+ writeFileSync(join(root, 'server', 'cos-runner', 'index.js'), '');+ context.root = root;+ journal = createDatabaseMaintenanceJournal(join(root, 'data'));+ stubs = installDatabaseStubs(root);+ rows = [+ { name: 'portos-cos', pmId: 12, pid: 1012, status: 'online', cwd: root, script: 'server/cos-runner/index.js' },+ { name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: root, script: 'server/start.js' },+ ];+ // A surrogate server that exited (refused boot) reads back as errored.+ context.list = vi.fn(async () => rows.map(row => (row.surrogate && !alive(row.pid)+ ? { ...row, status: 'errored', pid: 0 } : { ...row })));+ context.stop = vi.fn(async id => {+ const row = rows.find(value => value.pmId === id);+ stubs.event('stop ' + row.name);+ row.status = 'stopped'; row.pid = 0;+ return { success: true };+ });+ // Emulates `pm2 restart ecosystem.config.cjs --only <name> --update-env`:+ // the server receives the endpoint the saved configuration names NOW.+ context.restart = vi.fn(async name => {+ stubs.event('restart ' + name);+ const row = rows.find(value => value.name === name);+ row.pid = name === 'portos-server' ? cutover.launchServer(restartedServerEndpoint(root, stubs.dir)) : 2012;+ row.surrogate = name === 'portos-server';+ row.status = 'online';+ return { success: true };+ });+ Object.assign(process.env, { PATH: `${stubs.bin}:${savedEnv.PATH}`, PGPASSWORD: 'example-password' });+});+afterEach(() => {+ for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key];+ Object.assign(process.env, savedEnv);+ for (const pid of cutover?.surrogatePids() ?? []) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }+ context.root = undefined;+ rmSync(root, { recursive: true, force: true });+});++function begin(source = native, target = docker) {+ cutover = installCutoverStubs(root, stubs.dir, { source, target });+ // Other saved settings must survive the mode commit byte for byte.+ writeFileSync(join(root, '.env'), `PGPASSWORD=example-password\nPGMODE=${source.mode}\nPORTOS_EXAMPLE=kept\n`);+ operation = journal.begin({ source, target });+ token = journal.acquireCoordinator(operation.id);+ journal.reserveCoordinatorWorker(operation.id, token);+}++// Same-operation recovery exactly as a detached supervisor receipt permits it.+function successor() {+ writeFileSync(join(root, 'data', 'database-maintenance', 'worker-' + token, 'exit'), '1\n');+ token = journal.prepareRecovery(operation.id);+ journal.reserveCoordinatorWorker(operation.id, token);+}++const run = () => runDatabaseCutover(operation.id, token, fast);+const savedMode = () => /^PGMODE=(\S+)/m.exec(readFileSync(join(root, '.env'), 'utf8'))?.[1];+const serverEvents = () => stubs.events().filter(line => line.startsWith('server '));+const waitForEvent = (line) => vi.waitFor(() => expect(stubs.events()).toContain(line), { timeout: 15_000, interval: 20 });++describe.skipIf(process.platform === 'win32')('offline database cutover', () => {+ it.each([[native, docker], [docker, native]])('commits mode and releases only after the restarted server proves the target (%#)', async (source, target) => {+ begin(source, target);+ const result = await run();+ expect(result).toEqual({ id: operation.id, stage: 'released', source: source.mode, target: target.mode,+ importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted: true });+ await waitForEvent(`server booted ${target.port}`);+ // Regression caught: a restart before the committed import, or a release+ // (CoS back online) before the restarted server's own proof.+ expect(stubs.events().slice(0, 6)).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none',+ 'import-start', 'import-commit', 'restart portos-server']);+ expect(stubs.events().indexOf('restart portos-cos')).toBeGreaterThan(stubs.events().indexOf('restart portos-server'));+ expect(readFileSync(join(root, '.env'), 'utf8'))+ .toBe(`PGPASSWORD=example-password\nPGMODE=${target.mode}\nPORTOS_EXAMPLE=kept\n`);+ // Admission is open; the authority record retires the source endpoint.+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();+ expect(createDatabaseAuthority(join(root, 'data')).read()).toMatchObject({ operationId: operation.id, source, target });+ expect(existsSync(join(root, 'data', 'database-maintenance-completed', operation.id, 'operation.json'))).toBe(true);+ // The source recovery copy is retained.+ expect(readFileSync(join(root, 'data', 'db-dumps', `portos-maintenance-${operation.id}.sql`), 'utf8')).toBe(STUB_DUMP_COMPLETE);++ // Release admits no process still pointed at the retired source.+ cutover.launchServer(source);+ await waitForEvent('server refused DATABASE_RETIRED_BACKEND');+ expect(serverEvents().filter(line => line.startsWith('server booted'))).toEqual([`server booted ${target.port}`]);+ }, 60_000);++ it.each(['wrong pool', 'unhealthy target'])('stays fenced when the restarted server cannot prove the target (%s), then recovers the same operation', async (fault) => {+ begin();+ if (fault === 'wrong pool') cutover.overrideRestartPool(native);+ else cutover.setHealth('unhealthy');+ await expect(run()).rejects.toThrow(/did not prove the target backend/);+ await waitForEvent('server refused DATABASE_MAINTENANCE');+ // Mode is committed forward, but PM2 `online`/saved mode is not success.+ expect(journal.read()).toEqual({ ...operation, stage: 'verifying' });+ expect(savedMode()).toBe('docker');+ expect(() => journal.assertAdmission()).toThrow();+ expect(createDatabaseAuthority(join(root, 'data')).read()).toBeNull();+ expect(context.restart).not.toHaveBeenCalledWith('portos-cos');++ // Operator repairs the backend; same-operation recovery restarts the+ // crashed server once more and never re-exports, re-imports or reverses.+ cutover.clearRestartPool();+ cutover.setHealth('healthy');+ successor();+ expect(await run()).toMatchObject({ stage: 'released', restartVerified: true });+ await waitForEvent(`server booted ${docker.port}`);+ expect(stubs.invocations('pg_dump')).toHaveLength(1);+ expect(stubs.invocations('psql')).toHaveLength(1);+ expect(journal.read()).toBeNull();+ }, 60_000);++ it.each(['before', 'after', 'reverted'])('recovers a mode commit interrupted %s the .env write without guessing or reversing', async (point) => {+ begin();+ await runDatabaseTransfer(operation.id, token, fast);+ // The crashed worker published `committing`, then died.+ journal.transition(operation.id, token, 'importing', 'committing');+ const env = readFileSync(join(root, '.env'), 'utf8');+ if (point === 'after') writeFileSync(join(root, '.env'), env.replace('PGMODE=native', 'PGMODE=docker'));+ if (point === 'reverted') writeFileSync(join(root, '.env'), env.replace('PGMODE=native\n', ''));+ successor();+ expect(await run()).toMatchObject({ stage: 'released', source: 'native', target: 'docker' });+ // The recorded target — never the file's current contents — decides.+ expect(savedMode()).toBe('docker');+ expect(readFileSync(join(root, '.env'), 'utf8')).toMatch(/PORTOS_EXAMPLE=kept/);+ expect(stubs.invocations('psql')).toHaveLength(1);+ await waitForEvent(`server booted ${docker.port}`);+ }, 60_000);++ it('keeps a verified-but-unreleased operation fenced until recovery releases it', async () => {+ begin();+ cutover.setHealth('unhealthy');+ await expect(run()).rejects.toThrow(/did not prove/);+ cutover.setHealth('healthy');+ // A healthy restarted server proves the target and waits at the fence.+ const pid = cutover.launchServer(docker);+ rows.find(row => row.name === 'portos-server').pid = pid;+ await vi.waitFor(() => expect(journal.readTargetProof(operation.id, pid)).not.toBeNull(), { timeout: 15_000, interval: 20 });+ // A worker crashes between verification and release.+ successor();+ journal.enterCoordinatorWorker(operation.id, token);+ journal.transition(operation.id, token, 'verifying', 'verified');+ await new Promise(resolve => setTimeout(resolve, 200));+ expect(serverEvents().filter(line => line.startsWith('server booted'))).toEqual([]);+ expect(() => journal.assertAdmission()).toThrow();++ successor();+ expect(await run()).toMatchObject({ stage: 'released' });+ await waitForEvent(`server booted ${docker.port}`);+ expect(journal.read()).toBeNull();+ // Repeated recovery of a released operation has nothing to reopen.+ expect(() => journal.prepareRecovery(operation.id)).toThrow();+ }, 60_000);++ it('refuses to release onto a saved configuration edited away from the target', async () => {+ begin();+ cutover.setHealth('unhealthy');+ await expect(run()).rejects.toThrow(/did not prove/);+ cutover.setHealth('healthy');+ const pid = cutover.launchServer(docker);+ rows.find(row => row.name === 'portos-server').pid = pid;+ await vi.waitFor(() => expect(journal.readTargetProof(operation.id, pid)).not.toBeNull(), { timeout: 15_000, interval: 20 });+ successor();+ journal.enterCoordinatorWorker(operation.id, token);+ journal.transition(operation.id, token, 'verifying', 'verified');+ writeFileSync(join(root, '.env'), readFileSync(join(root, '.env'), 'utf8').replace('PGMODE=docker', 'PGMODE=native'));+ successor();+ await expect(run()).rejects.toThrow(/saved configuration does not resolve/);+ expect(journal.read().stage).toBe('verified');+ expect(() => journal.assertAdmission()).toThrow();+ }, 60_000);++ it('reuses one persisted successor across repeated recovery requests', async () => {+ begin();+ writeFileSync(join(root, 'data', 'database-maintenance', 'worker-' + token, 'exit'), '1\n');+ const first = journal.prepareRecovery(operation.id);+ // A retry before the successor launched gets the SAME token, not a second owner.+ expect(journal.prepareRecovery(operation.id)).toBe(first);+ journal.reserveCoordinatorWorker(operation.id, first);+ expect(journal.prepareRecovery(operation.id)).toBeNull();+ expect(() => journal.reserveCoordinatorWorker(operation.id, first)).toThrow();+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });+ });+});diff --git a/server/services/databaseMaintenanceProducers.js b/server/services/databaseMaintenanceProducers.jsindex 400a3a2ae4..cccffd9818 100644--- a/server/services/databaseMaintenanceProducers.js+++ b/server/services/databaseMaintenanceProducers.js@@ -38,6 +38,27 @@ function sameIdentities(current, saved) {}}+/**+ * Fresh readback of the RECORDED producer identities after a restart. The PM2+ * id, working directory and script must still match; the pid and status are+ * whatever PM2 reports now (a restart changes the pid; a crash loop may show+ * `errored`). Returns `{ name, pmId, pid, status }` per producer.+ */+export async function readRecordedProducers(saved) {+ const rows = await listMaintenanceProcesses();+ if (!Array.isArray(rows)) throw refused();+ const root = realpathSync(PATHS.installRoot);+ return names.map(name => {+ const matches = rows.filter(row => row?.name === name);+ const original = saved.find(value => value.name === name);+ if (matches.length !== 1 || !original) throw refused();+ const [row] = matches;+ if (row.pmId !== original.pmId || typeof row.cwd !== 'string' || typeof row.script !== 'string'+ || realpathSync(row.cwd) !== root || realpathSync(resolve(row.cwd, row.script)) !== original.script) throw refused();+ return { name, pmId: row.pmId, pid: Number.isSafeInteger(row.pid) && row.pid > 0 ? row.pid : 0, status: String(row.status) };+ });+}+/*** Internal one-use coordinator worker stage. Stops producers only; descendants* and pre-fence admitted spawns still require reconciliation before any dump.diff --git a/server/services/databaseMaintenanceTransfer.js b/server/services/databaseMaintenanceTransfer.jsindex 796c1176c2..d418278cd1 100644--- a/server/services/databaseMaintenanceTransfer.js+++ b/server/services/databaseMaintenanceTransfer.js@@ -110,17 +110,20 @@ async function assertRecordedDump(journal, id, dump) {/*** Internal offline transfer for the one entered coordinator worker. It never* changes saved mode, restarts producers, or reopens admission: the result is- * a committed target import at `importing`, awaiting verified restart (#8851).+ * a committed target import at `importing`. The cutover worker+ * (databaseMaintenanceCutover.js) then commits mode and verifies the restart.** Every attempt (including a recovered successor) first repeats quiescence.* `exporting` without a recorded dump re-exports; a recorded dump is reused* only when its bytes still match. `importing` retries only the recorded dump* into the recorded target, in one transaction. Direction never changes.- * `options` only shortens reconciliation waits for subprocess tests.+ * `options` only shortens reconciliation waits for subprocess tests; the+ * cutover worker passes `entered: true` after claiming the one-use entry.*/export async function runDatabaseTransfer(id, token, options = {}) {const journal = createDatabaseMaintenanceJournal();- const entered = journal.enterCoordinatorWorker(id, token);+ const entered = options.entered+ ? journal.assertEnteredCoordinatorWorker(id, token) : journal.enterCoordinatorWorker(id, token);if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(entered.stage)) {throw refused(`stage ${entered.stage} is not a transfer stage`);}@@ -141,7 +144,7 @@ export async function runDatabaseTransfer(id, token, options = {}) {let imported = false;// A crash after the target commits but before the receipt publishes makes the// next attempt import the same --clean dump again. That retry is idempotent:- // nothing can write the target before verified restart (#8851), which needs+ // nothing can write the target before verified restart, which needs// this receipt, so it reproduces the identical committed state.if (!journal.readTransferImport(id)) {const path = await assertRecordedDump(journal, id, dump);diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.jsindex b5a91844d8..acd0f1d866 100644--- a/server/services/databaseMaintenanceTransfer.test.js+++ b/server/services/databaseMaintenanceTransfer.test.js@@ -151,7 +151,7 @@ describe.skipIf(process.platform === 'win32')('offline database transfer', () =>const manifest = JSON.parse(readFileSync(join(root, 'data', 'database-maintenance', 'transfer-dump.json'), 'utf8'));expect(manifest).toEqual({ id: operation.id, source, file: `portos-maintenance-${operation.id}.sql`,bytes: Buffer.byteLength(STUB_DUMP_COMPLETE), sha256: sha256(STUB_DUMP_COMPLETE) });- // Direction, mode and the fence are unchanged; restart is #8851's.+ // Direction, mode and the fence are unchanged; restart is the cutover worker's.expect(journal.read()).toEqual({ ...operation, stage: 'importing' });expect(journal.transferStatus(operation.id)).toEqual({ dump: 'recorded', import: 'committed' });expect(existsSync(join(root, '.env'))).toBe(false);diff --git a/server/services/databasePreflight.js b/server/services/databasePreflight.jsindex d73b805aed..c2a3f9d9af 100644--- a/server/services/databasePreflight.js+++ b/server/services/databasePreflight.js@@ -5,7 +5,7 @@ import { join } from 'node:path';import { z } from 'zod';import { PATHS } from '../lib/paths.js';import { POOL_CONFIG } from '../lib/db.js';-import { assertDatabaseAdmission, databaseMaintenanceEndpointSchema } from '../lib/databaseMaintenanceJournal.js';+import { assertDatabaseAdmission, createDatabaseMaintenanceJournal, databaseMaintenanceEndpointSchema } from '../lib/databaseMaintenanceJournal.js';import { databaseMaintenancePreflightSchema } from '../lib/validation.js';import { ServerError } from '../lib/errorHandler.js';import { summarizeSystemActivity } from '../lib/systemIdle.js';@@ -57,12 +57,9 @@ function validateDirection(direction, configuration) {|| ['host', 'port', 'database', 'user'].some(key => configuration.source[key] !== POOL_CONFIG[key])) throw stale();}-/** Non-mutating advice only; no operation token, reservation, or writer drain. */-export async function preflightDatabaseMaintenance(input) {- const direction = databaseMaintenancePreflightSchema.parse(input);- assertDatabaseAdmission();- const initial = readConfiguration();- validateDirection(direction, initial);+// Trusted idle: every activity slice present and quiet. Reads process/state+// files only, so it stays valid after the admission fence closes.+async function assertTrustedIdle() {// Keep heavy activity/CoS graphs off ordinary database admin imports. Use the// lifecycle-only reader, not GPU telemetry or external Ollama probes.const [snapshot, activeAgents, mindGuard] = await Promise.all([@@ -74,6 +71,15 @@ export async function preflightDatabaseMaintenance(input) {if (!activity.success || !Number.isInteger(activeAgents) || activeAgents < 0|| mindGuard?.trusted !== true || typeof mindGuard.safe !== 'boolean') throw unavailable();if (!summarizeSystemActivity(activity.data).idle || activeAgents > 0 || !mindGuard.safe) throw busy();+}++/** Non-mutating advice only; no operation token, reservation, or writer drain. */+export async function preflightDatabaseMaintenance(input) {+ const direction = databaseMaintenancePreflightSchema.parse(input);+ assertDatabaseAdmission();+ const initial = readConfiguration();+ validateDirection(direction, initial);+ await assertTrustedIdle();// No await between the final fence/configuration checks and the response.// This narrows the observation race, but is deliberately NOT acceptance.assertDatabaseAdmission();@@ -82,3 +88,39 @@ export async function preflightDatabaseMaintenance(input) {if (JSON.stringify(initial) !== JSON.stringify(final)) throw stale();return { source: direction.source, target: direction.target, advisory: true, accepted: false };}++/**+ * Accept a cutover. Repeats the advisory validation, then publishes the+ * operation — which closes admission synchronously — and repeats the idle and+ * configuration checks UNDER the fence: work admitted just before publication+ * must already be finished, and nothing new can be admitted. Only then does a+ * coordinator take ownership and the detached worker launch. A failed final+ * check cancels the still-unowned operation, reopening admission unchanged.+ */+export async function acceptDatabaseMaintenance(input) {+ const direction = databaseMaintenancePreflightSchema.parse(input);+ await preflightDatabaseMaintenance(direction);+ const configuration = readConfiguration();+ validateDirection(direction, configuration);+ const journal = createDatabaseMaintenanceJournal();+ let operation;+ try {+ operation = journal.begin({ source: configuration.source, target: configuration.target });+ } catch {+ throw refuse('DATABASE_MAINTENANCE', 'Another database maintenance operation is active or requires recovery.');+ }+ try {+ await assertTrustedIdle();+ const final = readConfiguration();+ validateDirection(direction, final);+ if (final.revision !== configuration.revision) throw stale();+ } catch (err) {+ journal.cancel(operation.id, configuration.source);+ throw err;+ }+ const token = journal.acquireCoordinator(operation.id);+ const { spawnDatabaseMaintenanceWorker } = await import('../lib/detachedSpawn.js');+ const worker = await spawnDatabaseMaintenanceWorker(operation.id, token);+ worker.on('error', () => console.error('❌ Database cutover worker failed to launch; inspect scripts/database-maintenance.mjs status'));+ return { id: operation.id, stage: 'accepted', source: direction.source, target: direction.target, accepted: true };+}diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex d1a889f57b..cf7e570f50 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -10,6 +10,9 @@ import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';import { resolvePostgresPort } from '../lib/ports.js';import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { acceptDatabaseMaintenance } from './databasePreflight.js';+import { createDatabaseAuthority } from '../lib/databaseAuthority.js';+export { preflightDatabaseMaintenance } from './databasePreflight.js';const rootDir = PATHS.root;@@ -41,19 +44,39 @@ async function withDatabaseOperation(operation) {* Read only the durable operation, including while pool admission is fenced.* This is not a health probe or permission to resume writers. Even a verified* journal remains fenced until the coordinator explicitly releases admission.+ * Bounded: modes, stage and coordinator state — never endpoints or tokens.*/export function getMaintenanceStatus() {- const operation = createDatabaseMaintenanceJournal().read();- if (!operation) return { stage: 'idle', fenced: false };+ const journal = createDatabaseMaintenanceJournal();+ const operation = journal.read();+ if (!operation) {+ const last = createDatabaseAuthority().read();+ return { stage: 'idle', fenced: false,+ ...(last ? { lastCutover: { id: last.operationId, source: last.source.mode, target: last.target.mode, sourceRetained: true } } : {}) };+ }return {id: operation.id,stage: operation.stage,source: operation.source.mode,target: operation.target.mode,+ coordinator: journal.coordinatorStatus(operation.id).state,fenced: true,};}+/**+ * Accept an offline cutover (202). Serialized with every other database admin+ * mutation; the worker then stops PortOS, so the response is the last thing+ * this server process sends before its restart.+ */+export const acceptDatabaseCutover = (direction) => withDatabaseOperation(() => acceptDatabaseMaintenance(direction));++/** Same-operation recovery. Runs while fenced, so it bypasses the admin lock. */+export async function recoverDatabaseCutover(id) {+ const { recoverDatabaseCutover: recover } = await import('./databaseMaintenanceCutover.js');+ return recover(id);+}+/*** Run a command and return { stdout, stderr, exitCode }.*/diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 24c3eb427a..0e8576a6de 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -9,6 +9,7 @@ import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { parseCommandArgs } from '../lib/commandSecurity.js';import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';import { parsePm2JlistStdout } from '../lib/pm2Jlist.js';+import { PATHS } from '../lib/paths.js';const IS_WIN = process.platform === 'win32';@@ -561,6 +562,20 @@ export async function listMaintenanceProcesses() {}));}+/**+ * Internal maintenance restart of one PortOS producer. Re-evaluates the+ * install's ecosystem file with --update-env so the app receives the saved+ * database configuration a cutover just committed, never PM2's cached env.+ * PM2 success is not proof of the backend: the restarted process must still+ * prove its own pool (services/databaseCutoverHandshake.js).+ */+export async function restartMaintenanceProducer(name) {+ if (!['portos-server', 'portos-cos'].includes(name)) throw new Error('Unknown maintenance producer.');+ await execPm2(['restart', join(PATHS.installRoot, 'ecosystem.config.cjs'), '--only', name, '--update-env'],+ { cwd: PATHS.installRoot });+ return { success: true };+}+// Shared shaping for listProcesses / listProcessesStrict so the two never drift.function mapProcess(proc) {return {diff --git a/server/start.js b/server/start.jsindex 030819c629..646f191e09 100644--- a/server/start.js+++ b/server/start.js@@ -1,7 +1,22 @@+// Evaluate before importing either managed process's application graph.+import { createDatabaseMaintenanceJournal } from './lib/databaseMaintenanceJournal.js';+// 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) {+ // A fenced cutover admits exactly one path: the verifying/verified handshake,+ // which proves this process's own pool and waits for release. Every other+ // stage (or a damaged journal) refuses before any writer can start.+ if (createDatabaseMaintenanceJournal().isFenced()) {+ const { awaitDatabaseCutoverRelease } = await import('./services/databaseCutoverHandshake.js');+ try {+ await awaitDatabaseCutoverRelease();+ } catch (err) {+ console.error(`❌ ${err.code === 'DATABASE_MAINTENANCE' ? err.message : 'Database maintenance is fenced; boot refused.'}`);+ process.exit(1);+ }+ }await import('./services/databaseBootFence.js');await import('./index.js');} else if (args.length === 2 && args[0] === '--verify-database') {diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.jsnew file mode 100644index 0000000000..f5290de5a3--- /dev/null+++ b/server/test/fixtures/databaseCutoverStubs.js@@ -0,0 +1,112 @@+// Disposable stand-ins for the restart half of a database cutover. Nothing+// here reaches a real database, PM2 daemon or install configuration:+//+// - `ecosystem.config.cjs` in the disposable root resolves DATABASE_MODE from+// that root's `.env` exactly like the real file, over fixed test endpoints.+// - a `pg` stub (loaded through a module hook) answers the read-only target+// verification: `pg-health` = healthy | unhealthy switches the outcome, and+// the reported database/user are the pool's own configuration.+// - `launchServer(endpoint)` starts a surrogate ordinary server: the REAL+// databaseCutoverHandshake + databaseBootFence against a pool configured+// from its environment, then records `server booted` (or `server refused`).+import { appendFileSync, chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+import { spawn } from 'node:child_process';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';++const handshakeUrl = new URL('../../services/databaseCutoverHandshake.js', import.meta.url).href;+const bootFenceUrl = new URL('../../services/databaseBootFence.js', import.meta.url).href;++export function installCutoverStubs(root, dir, { source, target }) {+ writeFileSync(join(dir, 'endpoints.json'), JSON.stringify({ [source.mode]: source, [target.mode]: target }));+ writeFileSync(join(root, 'ecosystem.config.cjs'), `const fs = require('fs');+const path = require('path');+const endpoints = JSON.parse(fs.readFileSync(${JSON.stringify(join(dir, 'endpoints.json'))}, 'utf8'));+let mode = ${JSON.stringify(source.mode)};+try { mode = /^PGMODE=(\\S+)/m.exec(fs.readFileSync(path.join(__dirname, '.env'), 'utf8'))?.[1] ?? mode; } catch {}+module.exports = { DATABASE_MODE: mode, DATABASE_ENDPOINTS: endpoints };+`);++ const pgStub = join(dir, 'pg-stub.mjs');+ writeFileSync(pgStub, `import { existsSync, readFileSync } from 'node:fs';+const health = () => existsSync(${JSON.stringify(join(dir, 'pg-health'))}) ? readFileSync(${JSON.stringify(join(dir, 'pg-health'))}, 'utf8').trim() : 'healthy';+function Pool(config) {+ return {+ on() {},+ async end() {},+ async query() { throw new Error('pooled query is not stubbed'); },+ async connect() {+ if (health() !== 'healthy') throw new Error('connection refused');+ return {+ async query(input) {+ const text = typeof input === 'string' ? input : input.text;+ if (!/current_database/.test(text)) return { rows: [] };+ return { rows: [{ database: config.database, user: config.user, has_memories: true, has_links: true,+ has_sync: true, has_catalog: true, has_catalog_scraps: true }] };+ },+ release() {},+ };+ },+ };+}+export default { Pool, types: { setTypeParser() {} } };+`);+ const hooks = join(dir, 'pg-hooks.mjs');+ writeFileSync(hooks, `export async function resolve(specifier, context, next) {+ if (specifier === 'pg') return { url: ${JSON.stringify(pathToFileURL(pgStub).href)}, format: 'module', shortCircuit: true };+ return next(specifier, context);+}\n`);+ const register = join(dir, 'pg-register.mjs');+ writeFileSync(register, `import { register } from 'node:module';\nregister(${JSON.stringify(pathToFileURL(hooks).href)});\n`);++ const events = join(dir, 'events.log');+ const surrogate = join(dir, 'server-surrogate.mjs');+ writeFileSync(surrogate, `import { appendFileSync } from 'node:fs';+const log = line => appendFileSync(${JSON.stringify(events)}, line + '\\n');+try {+ const { awaitDatabaseCutoverRelease } = await import(${JSON.stringify(handshakeUrl)});+ await awaitDatabaseCutoverRelease({ pollMs: 20, releaseTimeoutMs: 20000 });+ await import(${JSON.stringify(bootFenceUrl)});+ log('server booted ' + process.env.PGPORT);+} catch (err) {+ log('server refused ' + (err.code ?? 'error'));+ process.exit(1);+}+setInterval(() => {}, 1000);+`);+ chmodSync(surrogate, 0o644);++ const pidsPath = join(dir, 'surrogates');+ return {+ setHealth: value => writeFileSync(join(dir, 'pg-health'), value),+ // Make the next stubbed PM2 restart hand the server this endpoint instead+ // of the one the saved configuration names (a stale cached environment).+ overrideRestartPool: endpoint => writeFileSync(join(dir, 'restart-pool.json'), JSON.stringify(endpoint)),+ clearRestartPool: () => writeFileSync(join(dir, 'restart-pool.json'), 'null'),+ launchServer: endpoint => launchSurrogateServer(root, dir, endpoint),+ surrogatePids: () => (existsSync(pidsPath) ? readFileSync(pidsPath, 'utf8').split('\n').filter(Boolean).map(Number) : []),+ };+}++/** The endpoint a stubbed `pm2 restart ecosystem.config.cjs --update-env` hands the server. */+export function restartedServerEndpoint(root, dir) {+ const override = join(dir, 'restart-pool.json');+ const forced = existsSync(override) ? JSON.parse(readFileSync(override, 'utf8')) : null;+ if (forced) return forced;+ const endpoints = JSON.parse(readFileSync(join(dir, 'endpoints.json'), 'utf8'));+ const env = existsSync(join(root, '.env')) ? readFileSync(join(root, '.env'), 'utf8') : '';+ const mode = /^PGMODE=(\S+)/m.exec(env)?.[1];+ return endpoints[mode] ?? Object.values(endpoints)[0];+}++/** A surrogate ordinary server whose pool is `endpoint`. Returns its pid. */+export function launchSurrogateServer(root, dir, endpoint) {+ const env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root,+ PGHOST: endpoint.host, PGPORT: String(endpoint.port), PGDATABASE: endpoint.database, PGUSER: endpoint.user,+ PGPASSWORD: 'example-password', NODE_OPTIONS: `--import=${pathToFileURL(join(dir, 'pg-register.mjs')).href}` };+ delete env.VITEST;+ const child = spawn(process.execPath, [join(dir, 'server-surrogate.mjs')], { env, stdio: 'ignore', detached: true });+ child.unref();+ appendFileSync(join(dir, 'surrogates'), `${child.pid}\n`);+ return child.pid;+}