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
fix: compact exited writer records without implying quiescence (#8850)
[._.]/ Adam Eivy135b66c7f89b
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 358dfb5f6c..f532692aa6 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -124,9 +124,9 @@ There is deliberately no PID-death, elapsed-time, or force recovery. A launch inFor 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.+`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. **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.+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.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/server/lib/README.md b/server/lib/README.mdindex e7c2afa124..f90a0b22de 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -768,4 +768,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |+| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations with completed launches compacted into a durable unresolved-history marker; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. Completion is evidence, never descendant-quiescence authority. |diff --git a/server/lib/databaseWriterRegistry.js b/server/lib/databaseWriterRegistry.jsindex ef7eb4d016..48ae6196a6 100644--- a/server/lib/databaseWriterRegistry.js+++ b/server/lib/databaseWriterRegistry.js@@ -1,4 +1,4 @@-import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync, linkSync, rmSync } from 'node:fs';import { isAbsolute, join, resolve } from 'node:path';import { randomUUID } from 'node:crypto';import { z } from 'zod';@@ -14,6 +14,8 @@ 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 retirementSchema = z.object({ version: z.literal(1) }).strict();+const RETIRED_EXITS = 'unreconciled-exits.json';const refused = () => new Error('Detached writer inventory is incomplete or unreadable; maintenance must remain fenced.');function syncDirectory(directory) {@@ -47,6 +49,9 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {// Reject already-fenced callers without creating records. This check is an// optimization only: the check AFTER durable publication closes the race.journal.assertAdmission();+ // A corrupt aggregate cannot accept further launches whose completion+ // would only create more unretirable records. Missing history is normal.+ readRecord(directory, RETIRED_EXITS, retirementSchema, true);mkdirSync(directory, { recursive: true, mode: 0o700 });syncDirectory(dataDir);const record = reservationSchema.parse({ version: 1, id: randomUUID(),@@ -62,7 +67,22 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {return {assertLaunchAllowed,launched: pid => publish(entry, 'launch.json', launchSchema.parse({ pid })),- completed: (code, signal) => publish(entry, 'completion.json', completionSchema.parse({ code, signal })),+ completed: (code, signal) => {+ publish(entry, 'completion.json', completionSchema.parse({ code, signal }));+ // Missing launch identity stays unresolved and retains its details.+ readRecord(entry, 'launch.json', launchSchema);+ // An exit does not prove descendant termination. Compact completed+ // details into a persistent UNKNOWN-history marker, never into absence.+ // Publish fully fsynced bytes atomically, and sync the parent BEFORE+ // deletion. Competing completions share one immutable marker.+ publish(entry, 'retirement.json', { version: 1 });+ try { linkSync(join(entry, 'retirement.json'), join(directory, RETIRED_EXITS)); }+ catch (err) { if (err.code !== 'EEXIST') throw err; }+ readRecord(directory, RETIRED_EXITS, retirementSchema);+ syncDirectory(directory);+ rmSync(entry, { recursive: true });+ syncDirectory(directory);+ },};};const read = () => {@@ -74,7 +94,9 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {if (err.code === 'ENOENT') return [];throw refused();}- return names.sort().map(name => {+ const retired = names.includes(RETIRED_EXITS);+ if (retired) readRecord(directory, RETIRED_EXITS, retirementSchema);+ const writers = names.filter(name => name !== RETIRED_EXITS).sort().map(name => {if (!z.string().uuid().safeParse(name).success) throw refused();const entry = join(directory, name);if (!lstatSync(entry).isDirectory()) throw refused();@@ -86,6 +108,10 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {return { ...record, state: completion ? 'exited' : launch ? 'launched' : 'unresolved',...(launch ?? {}), ...(completion ? { completion } : {}) };});+ // Keep this in the inventory itself so a consumer cannot accidentally read+ // only current launch rows and mistake a compacted history for an empty set.+ if (retired) writers.push({ state: 'unresolved', kind: 'retired-exits' });+ return writers;};return { reserve, read };}diff --git a/server/lib/databaseWriterRegistry.test.js b/server/lib/databaseWriterRegistry.test.jsindex 949deaf72c..60274ad508 100644--- a/server/lib/databaseWriterRegistry.test.js+++ b/server/lib/databaseWriterRegistry.test.js@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { fileURLToPath } from 'node:url';@@ -74,18 +74,40 @@ describe('durable detached launch admission', () => {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,+ it('compacts repeated completed launches into durable unknown history after control cleanup', async () => {+ for (let index = 0; index < 3; index += 1) {+ const controlDir = join(root, `control-${index}`);+ const handle = await spawnDetached(process.execPath, ['-e', 'process.exit(7)'], {+ controlDir, cleanup: true, pollMs: 10,+ });+ expect(registry.read()).toContainEqual(expect.objectContaining({ state: 'launched', pid: handle.pid, controlDir }));+ expect(await observe(handle)).toEqual({ code: 7, signal: null });+ expect(registry.read()).toEqual([{ state: 'unresolved', kind: 'retired-exits' }]);+ }+ // A fresh reader sees the same warning after restart; no per-exit files+ // accumulate and no control path or PID is inferred to be safe to kill.+ expect(createDatabaseWriterRegistry(context.data).read()).toEqual([{ state: 'unresolved', kind: 'retired-exits' }]);+ expect(readdirSync(join(context.data, 'database-writers'))).toEqual(['unreconciled-exits.json']);+ });++ it.each(['history', 'launch'])('retains launch details when %s evidence cannot support safe compaction', async (missing) => {+ const finish = join(root, 'finish');+ const handle = await spawnDetached(process.execPath, ['-e',+ `const t=setInterval(()=>{if(require('fs').existsSync(${JSON.stringify(finish)})){clearInterval(t);}},10);`], {+ controlDir: join(root, 'control'), 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',- ]);+ const [record] = registry.read();+ // Simulate corrupt/interrupted retirement publication. It must never turn+ // the known launch into absence even though its child completes normally.+ if (missing === 'history') mkdirSync(join(context.data, 'database-writers', 'unreconciled-exits.json'));+ else unlinkSync(join(context.data, 'database-writers', record.id, 'launch.json'));+ const done = observe(handle);+ writeFileSync(finish, '');+ expect(await done).toEqual({ code: 0, signal: null });+ expect(JSON.parse(readFileSync(join(context.data, 'database-writers', record.id, 'reservation.json'), 'utf8')).id).toBe(record.id);+ expect(JSON.parse(readFileSync(join(context.data, 'database-writers', record.id, 'completion.json'), 'utf8'))).toEqual({ code: 0, signal: null });+ expect(() => registry.read()).toThrow(/incomplete/);+ if (missing === 'history') expect(() => registry.reserve(join(root, 'next-control'))).toThrow(/incomplete/);});it('rejects an already-fenced launch without touching its control directory', async () => {