Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: bind fenced maintenance workers to one-use ownership (#8850)

[._.]/ Adam Eivy566796d74ab9
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index f532692aa6..9329a8850a 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -118,7 +118,7 @@ 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 an **internal ownership-recovery foundation**, not a callable transfer workflow. `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. A future coordinator launches its worker through `spawnDetached` with this directory and `cleanup: false`. `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 an **internal ownership-recovery foundation**, not a callable transfer workflow. `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 inspecting anything; copied arguments cannot enter it twice. 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.
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: before any export or import, the future execution coordinator must inventory and stop/drain PM2 server and CoS processes, admitted spawns, and owned detached writers, refusing unknown state. It must retain the complete source dump and re-establish quiescence before retrying the same target transaction. Those execution and transfer steps remain tracked by #8850; verified target restart, saved-mode commit, and admission release remain #8851.
@@ -126,7 +126,7 @@ For local diagnostics at any stage, run `node scripts/database-maintenance.mjs s
`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 pending Windows supervisor is still an unresolved inventoried launch, not proof that no process exists. Reservations contain only a random launch ID, timestamp, control directory, and process-group mode; active immutable records contain the observed PID; completion first records its code/signal, then compacts the entry into one durable `unreconciled-exits.json` marker before deleting that completed entry. The marker is published from fsynced bytes and its parent directory is synced before deletion, so a crash retains either the launch details or the marker (possibly both). Commands, arguments, environment variables, credentials, and application records are excluded. A partial/unreadable record fails inventory closed. Active/unresolved details and the aggregated unknown-exit history survive control-directory cleanup and caller restart. Ordinary completed jobs do not accumulate one permanent directory per launch.
-Run `node scripts/database-maintenance.mjs writers` for bounded counts at any stage; it always reports `quiescenceVerified: false` and exposes no control paths or process identities. A malformed inventory refuses the command. The internal `createDatabaseWriterRegistry().read()` returns `unresolved`, `launched`, or `exited` observations; a `{ state: 'unresolved', kind: 'retired-exits' }` entry represents compacted completion history. An `exited` entry can remain when compaction was interrupted or failed. **None proves descendant quiescence.** Do not infer safety from a PID probe, an exit record, an empty inventory on an upgraded install, or a successful reservation read while producers still run. Legacy children have no reservation, and admitted setup can still be pending. The offline coordinator must stop/drain producers, reconcile legacy and unknown children, establish descendant termination, then read this inventory before export. Active/unresolved entries and the aggregated unknown-history marker are retained until that coordinator supplies a verified reconciliation/retirement protocol; neither the CLI nor normal completion clears the marker. Do not delete them to unblock maintenance. They are local recovery evidence included in backups, never a federated application collection or reference seed. Public transfer entrypoints remain disabled, and there is no admission bypass flag for detached launches. The future maintenance coordinator needs its own narrowly bound ownership launch capability before it can use this path while fenced.
+Run `node scripts/database-maintenance.mjs writers` for bounded counts at any stage; it always reports `quiescenceVerified: false` and exposes no control paths or process identities. A malformed inventory refuses the command. The internal `createDatabaseWriterRegistry().read()` returns `unresolved`, `launched`, or `exited` observations; a `{ state: 'unresolved', kind: 'retired-exits' }` entry represents compacted completion history. An `exited` entry can remain when compaction was interrupted or failed. **None proves descendant quiescence.** Do not infer safety from a PID probe, an exit record, an empty inventory on an upgraded install, or a successful reservation read while producers still run. Legacy children have no reservation, and admitted setup can still be pending. The offline coordinator must stop/drain producers, reconcile legacy and unknown children, establish descendant termination, then read this inventory before export. Active/unresolved entries and the aggregated unknown-history marker are retained until that coordinator supplies a verified reconciliation/retirement protocol; neither the CLI nor normal completion clears the marker. Do not delete them to unblock maintenance. They are local recovery evidence included in backups, never a federated application collection or reference seed. Public transfer entrypoints remain disabled, and there is no admission bypass flag for detached launches. The fixed maintenance worker can launch while fenced, but can only inspect this bounded inventory: it reports direction, stage, counts, `quiescenceVerified: false`, and `transferReady: false`, then exits with code 78 (transfer not integrated). Empty inventory is not a successful cutover. Damaged ownership or inventory exits with code 1 and a redacted refusal. Its stdout/stderr, owner binding, one-use entry marker, and supervisor receipt remain in the reserved directory. It changes neither stage nor saved mode, stops no processes, and starts no child writers. This internal foundation is not wired to an operator launch or recovery command.
A cancelled unowned accepted operation moves to `data/database-maintenance-cancelled/<operation-id>/` as local recovery evidence. These records remain filesystem-backed and included in backups; they are not a growing application collection. Restoring an active journal deliberately restores its fence: do not delete it merely to make startup succeed. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.
diff --git a/scripts/database-maintenance-worker.mjs b/scripts/database-maintenance-worker.mjs
new file mode 100644
index 0000000000..e7d01c9008
--- /dev/null
+++ b/scripts/database-maintenance-worker.mjs
@@ -0,0 +1,28 @@
+#!/usr/bin/env node
+// Fixed internal worker entrypoint. No command, endpoint, environment, or
+// control-directory arguments are accepted. This slice inspects prerequisites;
+// it never stops writers, exports/imports data, commits mode, or opens admission.
+import { createDatabaseMaintenanceJournal } from '../server/lib/databaseMaintenanceJournal.js';
+import { createDatabaseWriterRegistry } from '../server/lib/databaseWriterRegistry.js';
+
+try {
+ const args = process.argv.slice(2);
+ if (args.length !== 2) throw new Error('Invalid worker identity');
+ const [id, token] = args;
+ const journal = createDatabaseMaintenanceJournal();
+ const operation = journal.enterCoordinatorWorker(id, token);
+ const writers = { unresolved: 0, launched: 0, exited: 0 };
+ for (const writer of createDatabaseWriterRegistry().read()) writers[writer.state] += 1;
+ journal.assertCoordinatorWorker(id, token);
+ console.log(JSON.stringify({ id: operation.id, stage: operation.stage,
+ source: operation.source.mode, target: operation.target.mode, writers,
+ quiescenceVerified: false, transferReady: false }));
+ // Successful inspection is NOT a successful cutover. Even an empty registry
+ // cannot exclude legacy children or an admitted producer still starting one.
+ console.error('⛔ Database transfer refused: writer shutdown and descendant reconciliation are not yet integrated.');
+ process.exitCode = 78;
+} catch {
+ // Never print tokens, paths, endpoints, or raw parser/OS exception messages.
+ console.error('⛔ Database maintenance worker refused: ownership or inventory evidence is incomplete.');
+ process.exitCode = 1;
+}
diff --git a/server/lib/README.md b/server/lib/README.md
index f90a0b22de..17264e8476 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -392,7 +392,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. |
| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
-| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
+| `detachedSpawn.js` | `spawnDatabaseMaintenanceWorker(id, token)` launches only the fixed, one-use fenced inspection worker and retains its supervisor evidence; it grants no ordinary launch bypass or transfer authority. `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
| `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. |
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index de28777e48..b58ede40ef 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -241,6 +241,24 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
return { state: 'exited', exitCode };
};
+ // The fixed maintenance worker checks both ownership and the supervisor's
+ // one-use reservation. This grants no ordinary database/spawn admission.
+ const assertCoordinatorWorker = (id, token) => {
+ assertCoordinator(id, token);
+ if (coordinatorStatus(id).state !== 'awaiting-exit') throw databaseMaintenanceError();
+ return read();
+ };
+
+ const enterCoordinatorWorker = (id, token) => {
+ assertNotRealDataWrite(activeDir, 'database maintenance worker entry');
+ const current = assertCoordinatorWorker(id, token);
+ // A second invocation with copied arguments cannot become a second worker.
+ writeDurableExclusive(join(workerDirectory(token), 'started.json'), { id, token });
+ syncDirectory(workerDirectory(token));
+ assertCoordinatorWorker(id, token);
+ return current;
+ };
+
// A durable CAS for EACH outgoing (owner, stage) state. Transition and
// recovery compete on the SAME file, so a predecessor paused after checking
// its token cannot publish a new stage after losing ownership. Interrupted
@@ -382,7 +400,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
};
return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition,
- reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator };
+ reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator, assertCoordinatorWorker, enterCoordinatorWorker };
}
const journal = createDatabaseMaintenanceJournal();
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
new file mode 100644
index 0000000000..6f040f3c68
--- /dev/null
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -0,0 +1,137 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
+import { createDatabaseWriterRegistry } from './databaseWriterRegistry.js';
+
+const detachedUrl = new URL('./detachedSpawn.js', import.meta.url).href;
+const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };
+const target = { ...source, mode: 'docker', port: 5561 };
+let root;
+let journal;
+let env;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'maintenance-worker-'));
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+ journal = createDatabaseMaintenanceJournal(join(root, 'data'));
+ env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root };
+ delete env.VITEST;
+});
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+function run(code) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], {
+ 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 }));
+ });
+}
+function launch(id, token) {
+ return run(`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;});
+ } catch { process.exitCode=1; }`);
+}
+
+describe('owned maintenance worker launch', () => {
+ it.each([[source, target], [target, source]])('runs one fixed inspection while ordinary launches remain fenced', async (from, to) => {
+ 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 inspection = JSON.parse(outcomes.find(value => value.status === 78).stdout);
+ expect(inspection).toEqual({ id: operation.id, stage: 'accepted', source: from.mode, target: to.mode,
+ writers: { unresolved: 0, launched: 0, exited: 0 }, quiescenceVerified: false, transferReady: false });
+ expect(journal.read()).toEqual(operation);
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'exited', exitCode: 78 });
+ expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toEqual([]);
+ expect(() => journal.assertAdmission()).toThrow();
+ const controlDir = join(root, 'data', 'database-maintenance', 'worker-' + token);
+ const before = readdirSync(controlDir).sort();
+ expect(before).toEqual(expect.arrayContaining(['owner.json', 'started.json', 'stdout.log', 'stderr.log', 'pid', 'exit']));
+ expect((await launch(operation.id, token)).status).toBe(1);
+ expect(readdirSync(controlDir).sort()).toEqual(before);
+ expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');
+
+ // 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 successor = journal.recoverCoordinator(operation.id, token, randomUUID());
+ expect((await launch(operation.id, token)).status).toBe(1);
+ expect((await launch(operation.id, successor)).status).toBe(78);
+ expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');
+ expect(journal.read()).toEqual(operation);
+ }, 60_000);
+
+ it('rejects a foreign owner and cannot relaunch an interrupted reservation', async () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ expect((await launch(operation.id, randomUUID())).status).toBe(1);
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });
+ const controlDir = journal.reserveCoordinatorWorker(operation.id, token);
+ writeFileSync(join(controlDir, 'stdout.log'), 'retained evidence');
+ expect((await launch(operation.id, token)).status).toBe(1);
+ expect(readFileSync(join(controlDir, 'stdout.log'), 'utf8')).toBe('retained evidence');
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });
+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();
+ }, 40_000);
+
+ it('retains unresolved inventory and refuses transfer after inspecting it', async () => {
+ createDatabaseWriterRegistry(join(root, 'data')).reserve(join(root, 'pending-writer'));
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const outcome = await launch(operation.id, token);
+ expect(outcome.status).toBe(78);
+ expect(JSON.parse(outcome.stdout)).toMatchObject({ writers: { unresolved: 1 }, transferReady: false });
+ expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toHaveLength(1);
+ expect(journal.read()).toEqual(operation);
+ }, 40_000);
+
+ it('refuses damaged inventory without printing local evidence', async () => {
+ const registry = createDatabaseWriterRegistry(join(root, 'data'));
+ registry.reserve(join(root, 'pending-writer'));
+ const [writer] = registry.read();
+ writeFileSync(join(root, 'data', 'database-writers', writer.id, 'reservation.json'), 'private-example-marker');
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const outcome = await launch(operation.id, token);
+ expect(outcome.status).toBe(1);
+ expect(outcome.stdout).toBe('');
+ expect(outcome.stderr).toContain('ownership or inventory evidence is incomplete');
+ expect(outcome.stderr).not.toContain('private-example-marker');
+ expect(outcome.stderr).not.toContain(root);
+ expect(outcome.stderr).not.toContain(token);
+ expect(journal.read()).toEqual(operation);
+ expect(() => journal.assertAdmission()).toThrow();
+ }, 40_000);
+
+ it('rejects repeated direct worker entry', async () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const controlDir = journal.reserveCoordinatorWorker(operation.id, token);
+ journal.enterCoordinatorWorker(operation.id, token);
+ expect(() => journal.enterCoordinatorWorker(operation.id, token)).toThrow();
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });
+ // The stopped reservation is never repaired or reused automatically.
+ expect(readFileSync(join(controlDir, 'started.json'), 'utf8')).toContain(token);
+ });
+});
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 293b2b69c8..0bf4d4aa2f 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -537,10 +537,36 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
* always the `taskkill /T /F` tree, group flag or not.
* @returns {Promise<object>} ChildProcess-like handle (resolves once the PID is known)
*/
-export async function spawnDetached(bin, args = [], {
+export async function spawnDetached(bin, args = [], options = {}) {
+ return spawnDetachedWithReservation(bin, args, options, reserveDatabaseWriter);
+}
+
+/**
+ * Internal, one-use launch of the fixed maintenance inspection worker. There
+ * is no bin/argv/env/controlDir override and no ordinary-writer bypass option.
+ * It retains the supervisor receipt even when the caller exits. Transfer and
+ * PM2 lifecycle execution remain disabled pending proven writer quiescence.
+ */
+export async function spawnDatabaseMaintenanceWorker(id, token) {
+ const [{ createDatabaseMaintenanceJournal }, { PATHS }] = await Promise.all([
+ import('./databaseMaintenanceJournal.js'), import('./paths.js'),
+ ]);
+ const journal = createDatabaseMaintenanceJournal();
+ const controlDir = journal.reserveCoordinatorWorker(id, token);
+ return spawnDetachedWithReservation(process.execPath,
+ [join(PATHS.root, 'scripts', 'database-maintenance-worker.mjs'), id, token],
+ { controlDir, cleanup: false, cwd: PATHS.root,
+ env: { ...process.env, PORTOS_DATA_ROOT: PATHS.installRoot } },
+ () => {
+ journal.assertCoordinatorWorker(id, token);
+ return { assertLaunchAllowed: () => journal.assertCoordinatorWorker(id, token) };
+ });
+}
+
+async function spawnDetachedWithReservation(bin, args, {
env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, pidTimeoutMs = PID_TIMEOUT_MS,
cleanup = false, killProcessGroup = false,
-} = {}) {
+}, reserveWriter) {
if (!controlDir) throw new Error('spawnDetached requires a controlDir');
const isWindows = process.platform === 'win32';
@@ -551,12 +577,12 @@ export async function spawnDetached(bin, args = [], {
// Publish before any await: a launch admitted immediately before maintenance
// is visible even while async setup or the detached supervisor is pending.
let writer;
- try { writer = reserveDatabaseWriter(controlDir, killProcessGroup); } catch (err) {
+ try { writer = reserveWriter(controlDir, killProcessGroup); } catch (err) {
setImmediate(() => handle.emit('error', err));
return handle;
}
const recordCompletion = (code, signal) => {
- try { writer.completed(code, signal); } catch {
+ try { writer.completed?.(code, signal); } catch {
// Missing evidence is unresolved, never synthesized into quiescence.
console.error('❌ Could not persist detached writer completion evidence');
}
@@ -673,7 +699,7 @@ export async function spawnDetached(bin, args = [], {
await awaitPid();
if (handle.pid !== null) {
- try { writer.launched(handle.pid); } catch {
+ try { writer.launched?.(handle.pid); } catch {
// The child may already exist. Preserve the reservation and control
// files; inventory cannot mistake this for a completed or absent writer.
console.error('❌ Could not persist detached writer launch evidence');