Skip to content

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

fix: inventory detached writers before maintenance admission (#8850)

[._.]/ Adam Eivy3018bc364371
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index a434c4205b..358dfb5f6c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -124,6 +124,10 @@ There is deliberately no PID-death, elapsed-time, or force recovery. A launch in
For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. 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 recovery command for an owned/interrupted operation yet: preserve its journal, worker records, source, and any dump; do not delete markers or call `scripts/db.sh migrate` (still refused). No public lifecycle coordinator or ownership-recovery command is exposed by this foundation.
+`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; later immutable records contain the observed PID and completion code/signal. Commands, arguments, environment variables, credentials, and application records are excluded. A partial/unreadable record fails inventory closed. Evidence survives control-directory cleanup and caller restart.
+
+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. **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. Entries are retained until that coordinator supplies a verified reconciliation/retirement protocol; 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.
+
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.
### Calendar daily-review recovery
diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjs
index d465494461..2a904f2e54 100644
--- a/scripts/database-maintenance.mjs
+++ b/scripts/database-maintenance.mjs
@@ -5,6 +5,7 @@ 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';
const journal = createDatabaseMaintenanceJournal();
const require = createRequire(import.meta.url);
@@ -19,6 +20,11 @@ function configuredEndpoints() {
function main() {
const [command, ...args] = process.argv.slice(2);
+ if (command === 'writers' && args.length === 0) {
+ const counts = { unresolved: 0, launched: 0, exited: 0 };
+ for (const writer of createDatabaseWriterRegistry().read()) counts[writer.state] += 1;
+ return { ...counts, quiescenceVerified: false };
+ }
if (command === 'status' && args.length === 0) {
const record = journal.read();
// Endpoints are local-only; the operator-facing status needs only direction.
@@ -39,7 +45,7 @@ function main() {
if (command === 'cancel' && args.length === 1) {
return journal.cancel(args[0], configuredEndpoints().source);
}
- throw new Error('Usage: node scripts/database-maintenance.mjs status | 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>');
}
try {
diff --git a/server/lib/README.md b/server/lib/README.md
index c0ec88c515..e7c2afa124 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -767,3 +767,5 @@ 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, and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |
+
+| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. Completion is evidence, never descendant-quiescence authority. |
diff --git a/server/lib/databaseMaintenanceRecovery.test.js b/server/lib/databaseMaintenanceRecovery.test.js
index a6ad35f829..f1384fecd1 100644
--- a/server/lib/databaseMaintenanceRecovery.test.js
+++ b/server/lib/databaseMaintenanceRecovery.test.js
@@ -1,3 +1,8 @@
+// Lifecycle-specific suite; durable admission has its own subprocess contract.
+vi.mock('./databaseWriterRegistry.js', () => ({ reserveDatabaseWriter: () => ({
+ assertLaunchAllowed() {}, launched() {}, completed() {},
+}) }));
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { randomUUID } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
diff --git a/server/lib/databaseWriterRegistry.js b/server/lib/databaseWriterRegistry.js
new file mode 100644
index 0000000000..ef7eb4d016
--- /dev/null
+++ b/server/lib/databaseWriterRegistry.js
@@ -0,0 +1,93 @@
+import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { isAbsolute, join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { z } from 'zod';
+import { PATHS } from './paths.js';
+import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
+import { assertNotRealDataWrite } from './testDataIsolation.js';
+
+const reservationSchema = z.object({
+ version: z.literal(1), id: z.string().uuid(), controlDir: z.string().refine(isAbsolute),
+ createdAt: z.string().datetime(), processGroup: z.boolean(),
+}).strict();
+const launchSchema = z.object({ pid: z.number().int().positive() }).strict();
+const completionSchema = z.object({
+ code: z.number().int().nullable(), signal: z.string().nullable(),
+}).strict();
+const refused = () => new Error('Detached writer inventory is incomplete or unreadable; maintenance must remain fenced.');
+
+function syncDirectory(directory) {
+ if (process.platform === 'win32') return;
+ const fd = openSync(directory, 'r');
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
+function publish(directory, name, value) {
+ const fd = openSync(join(directory, name), 'wx', 0o600);
+ try { writeFileSync(fd, JSON.stringify(value) + '\n'); fsyncSync(fd); }
+ finally { closeSync(fd); }
+ syncDirectory(directory);
+}
+function readRecord(directory, name, schema, optional = false) {
+ const path = join(directory, name);
+ try {
+ if (!lstatSync(path).isFile()) throw refused();
+ return schema.parse(JSON.parse(readFileSync(path, 'utf8')));
+ } catch (err) {
+ if (optional && err.code === 'ENOENT') return null;
+ throw refused();
+ }
+}
+
+/** Machine-local launch evidence, NOT a declaration of writer quiescence. */
+export function createDatabaseWriterRegistry(dataDir = PATHS.data) {
+ const directory = join(dataDir, 'database-writers');
+ const journal = createDatabaseMaintenanceJournal(dataDir);
+ const reserve = (controlDir, processGroup = false) => {
+ assertNotRealDataWrite(directory, 'detached writer reservation');
+ // Reject already-fenced callers without creating records. This check is an
+ // optimization only: the check AFTER durable publication closes the race.
+ journal.assertAdmission();
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ syncDirectory(dataDir);
+ const record = reservationSchema.parse({ version: 1, id: randomUUID(),
+ controlDir: resolve(controlDir), createdAt: new Date().toISOString(), processGroup });
+ const entry = join(directory, record.id);
+ mkdirSync(entry, { mode: 0o700 });
+ syncDirectory(directory);
+ // Incomplete publication stays visible and fails inventory closed after a
+ // crash. No child may start before this record is durable and admitted.
+ publish(entry, 'reservation.json', record);
+ const assertLaunchAllowed = () => journal.assertAdmission();
+ assertLaunchAllowed();
+ return {
+ assertLaunchAllowed,
+ launched: pid => publish(entry, 'launch.json', launchSchema.parse({ pid })),
+ completed: (code, signal) => publish(entry, 'completion.json', completionSchema.parse({ code, signal })),
+ };
+ };
+ const read = () => {
+ let names;
+ try {
+ if (!lstatSync(directory).isDirectory()) throw refused();
+ names = readdirSync(directory);
+ } catch (err) {
+ if (err.code === 'ENOENT') return [];
+ throw refused();
+ }
+ return names.sort().map(name => {
+ if (!z.string().uuid().safeParse(name).success) throw refused();
+ const entry = join(directory, name);
+ if (!lstatSync(entry).isDirectory()) throw refused();
+ const record = readRecord(entry, 'reservation.json', reservationSchema);
+ if (record.id !== name) throw refused();
+ const launch = readRecord(entry, 'launch.json', launchSchema, true);
+ const completion = readRecord(entry, 'completion.json', completionSchema, true);
+ if (completion && !launch) throw refused();
+ return { ...record, state: completion ? 'exited' : launch ? 'launched' : 'unresolved',
+ ...(launch ?? {}), ...(completion ? { completion } : {}) };
+ });
+ };
+ return { reserve, read };
+}
+
+export const reserveDatabaseWriter = (...args) => createDatabaseWriterRegistry().reserve(...args);
diff --git a/server/lib/databaseWriterRegistry.test.js b/server/lib/databaseWriterRegistry.test.js
new file mode 100644
index 0000000000..949deaf72c
--- /dev/null
+++ b/server/lib/databaseWriterRegistry.test.js
@@ -0,0 +1,145 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+import { spawn, spawnSync } from 'node:child_process';
+import { createDatabaseWriterRegistry } from './databaseWriterRegistry.js';
+import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
+import { spawnDetached } from './detachedSpawn.js';
+
+const context = vi.hoisted(() => ({ data: undefined, setupBarrier: null }));
+vi.mock('./paths.js', async original => {
+ const actual = await original();
+ return { ...actual, PATHS: new Proxy(actual.PATHS, {
+ get: (target, key) => key === 'data' ? (context.data ?? target[key]) : target[key],
+ }) };
+});
+vi.mock('./fileUtils.js', async original => {
+ const actual = await original();
+ return { ...actual, ensureDir: async (...args) => {
+ if (context.setupBarrier) await context.setupBarrier;
+ return actual.ensureDir(...args);
+ } };
+});
+const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };
+const target = { ...source, mode: 'docker', port: 5561 };
+let root;
+let registry;
+let journal;
+let handles;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'writer-inventory-'));
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+ context.data = join(root, 'data');
+ context.setupBarrier = null;
+ registry = createDatabaseWriterRegistry(context.data);
+ journal = createDatabaseMaintenanceJournal(context.data);
+ handles = [];
+});
+afterEach(async () => {
+ context.setupBarrier = null;
+ for (const { handle, done } of handles) {
+ if (handle.exitCode === null && handle.signalCode === null) handle.kill('SIGKILL');
+ await done;
+ }
+ rmSync(root, { recursive: true, force: true });
+});
+function observe(handle) {
+ const done = new Promise(resolve => {
+ handle.once('close', (code, signal) => resolve({ code, signal }));
+ handle.once('error', error => resolve({ error }));
+ });
+ handles.push({ handle, done });
+ return done;
+}
+
+describe('durable detached launch admission', () => {
+ it('lists a paused launch before the fence and refuses it when setup resumes', async () => {
+ let release;
+ context.setupBarrier = new Promise(resolve => { release = resolve; });
+ const ran = join(root, 'ran');
+ const pending = spawnDetached(process.execPath, ['-e', `require('fs').writeFileSync(${JSON.stringify(ran)},'bad')`], {
+ controlDir: join(root, 'control'), pollMs: 10,
+ });
+ const [reserved] = registry.read();
+ expect(reserved.state).toBe('unresolved');
+ journal.begin({ source, target });
+ release();
+ const handle = await pending;
+ const result = await observe(handle);
+ expect(result.error?.code).toBe('DATABASE_MAINTENANCE');
+ expect(() => readFileSync(ran)).toThrow();
+ expect(registry.read()).toEqual([reserved]);
+ expect(() => journal.assertAdmission()).toThrow();
+ });
+
+ it('retains launched and completion evidence after caller-requested control cleanup', async () => {
+ const controlDir = join(root, 'control');
+ const handle = await spawnDetached(process.execPath, ['-e', 'process.exit(7)'], {
+ controlDir, cleanup: true, pollMs: 10,
+ });
+ expect(registry.read()[0]).toMatchObject({ state: 'launched', pid: handle.pid, controlDir });
+ expect(await observe(handle)).toEqual({ code: 7, signal: null });
+ expect(registry.read()[0]).toMatchObject({ state: 'exited', pid: handle.pid,
+ completion: { code: 7, signal: null } });
+ expect(Object.keys(registry.read()[0]).sort()).toEqual([
+ 'completion', 'controlDir', 'createdAt', 'id', 'pid', 'processGroup', 'state', 'version',
+ ]);
+ });
+
+ it('rejects an already-fenced launch without touching its control directory', async () => {
+ journal.begin({ source, target });
+ const controlDir = join(root, 'control');
+ mkdirSync(controlDir);
+ writeFileSync(join(controlDir, 'pid'), '123');
+ const handle = await spawnDetached(process.execPath, ['-e', 'process.exit(0)'], { controlDir });
+ expect((await observe(handle)).error?.code).toBe('DATABASE_MAINTENANCE');
+ expect(readFileSync(join(controlDir, 'pid'), 'utf8')).toBe('123');
+ expect(registry.read()).toEqual([]);
+ });
+
+ it('reports bounded operator diagnostics without publishing local identities or claiming quiescence', () => {
+ registry.reserve(join(root, 'private-control'));
+ const cli = new URL('../../scripts/database-maintenance.mjs', import.meta.url);
+ const result = spawnSync(process.execPath, [fileURLToPath(cli), 'writers'], {
+ encoding: 'utf8', env: { ...process.env, PORTOS_DATA_ROOT: root }, timeout: 10000,
+ });
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({ unresolved: 1, launched: 0, exited: 0, quiescenceVerified: false });
+ expect(result.stdout).not.toContain(root);
+ });
+
+ it('fails inventory closed on interrupted publication instead of omitting an unknown writer', () => {
+ registry.reserve(join(root, 'control'));
+ const [record] = registry.read();
+ writeFileSync(join(context.data, 'database-writers', record.id, 'launch.json'), '{');
+ expect(() => registry.read()).toThrow(/incomplete/);
+ });
+
+ it.each([[source, target], [target, source]])('keeps another process inventoried across maintenance admission', async (from, to) => {
+ const registryUrl = new URL('./databaseWriterRegistry.js', import.meta.url).href;
+ const code = `import {createDatabaseWriterRegistry} from ${JSON.stringify(registryUrl)};
+ const reservation=createDatabaseWriterRegistry(${JSON.stringify(context.data)}).reserve(${JSON.stringify(join(root, 'process-control'))});
+ process.stdout.write('reserved\\n');
+ process.stdin.once('data',()=>{try {reservation.assertLaunchAllowed();process.exit(2);} catch {process.exit(0);}});`;
+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: ['pipe', 'pipe', 'pipe'] });
+ const exited = new Promise((resolve, reject) => { child.once('close', resolve); child.once('error', reject); });
+ try {
+ await new Promise((resolve, reject) => {
+ child.stdout.once('data', resolve);
+ child.once('error', reject);
+ child.once('exit', code => reject(new Error(`reservation process exited ${code}`)));
+ });
+ expect(registry.read()).toHaveLength(1);
+ expect(registry.read()[0].state).toBe('unresolved');
+ journal.begin({ source: from, target: to });
+ child.stdin.end('continue');
+ expect(await exited).toBe(0);
+ expect(registry.read()[0].state).toBe('unresolved');
+ } finally {
+ if (child.exitCode === null) child.kill('SIGKILL');
+ await exited;
+ }
+ });
+});
diff --git a/server/lib/detachedSpawn.bootstrap.test.js b/server/lib/detachedSpawn.bootstrap.test.js
index 8dfba8202e..526882862d 100644
--- a/server/lib/detachedSpawn.bootstrap.test.js
+++ b/server/lib/detachedSpawn.bootstrap.test.js
@@ -1,3 +1,8 @@
+// Lifecycle-specific suite; durable admission has its own subprocess contract.
+vi.mock('./databaseWriterRegistry.js', () => ({ reserveDatabaseWriter: () => ({
+ assertLaunchAllowed() {}, launched() {}, completed() {},
+}) }));
+
import { EventEmitter } from 'events';
import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
import { join } from 'path';
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 741e5c5a64..293b2b69c8 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -62,6 +62,7 @@ import { ensureDir, sleep } from './fileUtils.js';
import { safeChildProcessOptions } from './processEnv.js';
import { quoteForShell } from './shellCd.js';
import { withSpawnCwdEnv } from './spawnCwd.js';
+import { reserveDatabaseWriter } from './databaseWriterRegistry.js';
const execFileAsync = promisify(execFile);
@@ -547,6 +548,20 @@ export async function spawnDetached(bin, args = [], {
// `kill` reports false until the supervisor records a PID, so a setup failure
// (below) still returns a usable handle.
const handle = createDetachedHandle({ killProcessGroup });
+ // 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) {
+ setImmediate(() => handle.emit('error', err));
+ return handle;
+ }
+ const recordCompletion = (code, signal) => {
+ try { writer.completed(code, signal); } catch {
+ // Missing evidence is unresolved, never synthesized into quiescence.
+ console.error('❌ Could not persist detached writer completion evidence');
+ }
+ };
+ handle.once('close', recordCompletion);
const pidFile = join(controlDir, 'pid');
const exitFile = join(controlDir, 'exit');
@@ -586,6 +601,10 @@ export async function spawnDetached(bin, args = [], {
// writes two control files before it spawns, so it can fail with a rejection
// too; route that into the same slot rather than letting it reject
// spawnDetached, for the reason ensureControlDir above spells out.
+ try { writer.assertLaunchAllowed(); } catch (err) {
+ setImmediate(() => handle.emit('error', err));
+ return handle;
+ }
let launcherSpawnError = null;
let launcherExit = null;
const launcher = isWindows
@@ -653,6 +672,13 @@ export async function spawnDetached(bin, args = [], {
};
await awaitPid();
+ if (handle.pid !== null) {
+ 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');
+ }
+ }
if (isWindows && launchError) {
// Persist cancellation before returning or scheduling cleanup. A supervisor
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 10859ea5f9..8c1159b1b0 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -1,3 +1,8 @@
+// Lifecycle-specific suite; durable admission has its own subprocess contract.
+vi.mock('./databaseWriterRegistry.js', () => ({ reserveDatabaseWriter: () => ({
+ assertLaunchAllowed() {}, launched() {}, completed() {},
+}) }));
+
import { describe, it, expect, afterEach, vi } from 'vitest';
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
@@ -363,6 +368,7 @@ describe('spawnDetached', () => {
const heartbeat = join(controlDir, 'heartbeat');
// A stand-in for portos-server: it spawns the job and then just stays alive.
const spawnerPath = join(controlDir, 'spawner.mjs');
+ await writeFile(join(controlDir, '.portos-disposable-root'), '');
await writeFile(spawnerPath, [
`import { spawnDetached } from ${JSON.stringify(pathToFileURL(join(import.meta.dirname, 'detachedSpawn.js')).href)};`,
'await spawnDetached(process.execPath, [',
@@ -374,7 +380,9 @@ describe('spawnDetached', () => {
'setInterval(() => {}, 1000);',
].join('\n'));
- const spawner = spawn(process.execPath, [spawnerPath], { stdio: 'ignore' });
+ const spawner = spawn(process.execPath, [spawnerPath], {
+ stdio: 'ignore', env: { ...process.env, PORTOS_DATA_ROOT: controlDir },
+ });
const pidFile = join(controlDir, 'pid');
const readPid = async () => Number.parseInt(await readFile(pidFile, 'utf8').catch(() => ''), 10);
expect(await waitUntil(async () => Number.isFinite(await readPid()))).toBe(true);
diff --git a/server/lib/index.js b/server/lib/index.js
index 6dfea5ac19..5a7f50971a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -749,3 +749,5 @@ export * from './styleSourcePrompt.js';
export * from './messageBrowserIdentity.js';
export * from './databaseMaintenanceJournal.js';
+
+export * from './databaseWriterRegistry.js';