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: serialize database maintenance coordinator stages (#8816)
[._.]/ Adam Eivy18015b363ddd
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 20df96d64c..00da7df334 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -113,9 +113,11 @@ recorded endpoints, and the running pool before cutover.### Database maintenance journal-`data/database-maintenance/operation.json` is `file-primary`, machine-local recovery state: it must be readable before PostgreSQL, including while either backend is unavailable. Its enclosing directory is the admission fence. The versioned record contains an operation UUID, accepted stage, timestamp, and explicit source/target connection identities; it contains no password, token, or application records. It is never federated and has no reference seed. Missing state is idle; an incomplete, malformed, unreadable, or newer-version operation stays fenced. No install migration is needed for an initially absent operation.+`data/database-maintenance/operation.json` is `file-primary`, machine-local recovery state: it must be readable before PostgreSQL, including while either backend is unavailable. Its enclosing directory is the admission fence. The versioned record contains an operation UUID, lifecycle stage, timestamp, and explicit source/target connection identities; it contains no password, token, or application records. It is never federated and has no reference seed. Missing state is idle; an incomplete, malformed, unreadable, or newer-version operation stays fenced. No install migration is needed for an initially absent operation.-A cancelled 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.+Coordinator ownership and cancellation share one exclusive durable claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, ownership token, and expected previous stage. Per-stage claims serialize even concurrent calls with the same token. Interrupted claims are never stolen on a timer or inferred PID death, and every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. No lifecycle coordinator or ownership-recovery command is exposed yet.++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.## `asset-file-db-indexed` — bytes on disk, metadata in DBdiff --git a/server/lib/README.md b/server/lib/README.mdindex d12fd3f34c..8581a32b3f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -766,4 +766,4 @@ 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` | Durable cross-process database admission fence and immutable accepted-operation journal; source-only cancellation archives the operation. |+| `databaseMaintenanceJournal.js` | Durable cross-process database admission fence and operation journal with exclusive coordinator ownership and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex 470f854a13..04c9467070 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -13,10 +13,12 @@ const endpointSchema = z.object({user: z.string().min(1).max(63),}).strict();+const stages = ['accepted', 'quiescing', 'exporting', 'importing', 'committing', 'verifying', 'verified'];+const journalSchema = z.object({version: z.literal(1),id: z.string().uuid(),- stage: z.literal('accepted'),+ stage: z.enum(stages),createdAt: z.string().datetime(),source: endpointSchema,target: endpointSchema,@@ -109,6 +111,41 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return record;};+ // One durable owner for the operation's entire lifetime. Never infer that an+ // owner is dead from a PID or elapsed time; interrupted ownership needs an+ // explicit recovery protocol before another process may advance the journal.+ const acquireCoordinator = (id) => {+ assertNotRealDataWrite(activeDir, 'database maintenance ownership');+ const current = read();+ if (!current || current.id !== id || current.stage !== 'accepted') throw databaseMaintenanceError();+ const token = randomUUID();+ writeDurableExclusive(join(activeDir, 'cancel-' + id + '.claim'), { id, token });+ syncDirectory(activeDir);+ const owned = read();+ if (!owned || owned.id !== id || owned.stage !== 'accepted') throw databaseMaintenanceError();+ return token;+ };++ const transition = (id, token, expectedStage, nextStage) => {+ assertNotRealDataWrite(activeDir, 'database maintenance transition');+ const current = read();+ if (!current || current.id !== id || current.stage !== expectedStage+ || stages.indexOf(nextStage) !== stages.indexOf(expectedStage) + 1) throw databaseMaintenanceError();+ const ownerPath = join(activeDir, 'cancel-' + id + '.claim');+ if (!lstatSync(ownerPath).isFile()) throw databaseMaintenanceError();+ const owner = JSON.parse(readFileSync(ownerPath, 'utf8'));+ if (typeof token !== 'string' || owner.id !== id || owner.token !== token) throw databaseMaintenanceError();+ // Exclusive per-stage publication also serializes two calls by the owner.+ // A crash before rename leaves a pending file and fails closed on retry.+ writeDurableExclusive(join(activeDir, 'stage-' + expectedStage + '.claim'), { id });+ const pending = join(activeDir, 'stage-' + expectedStage + '.pending');+ const next = journalSchema.parse({ ...current, stage: nextStage });+ writeDurableExclusive(pending, next);+ renameSync(pending, recordPath);+ syncDirectory(activeDir);+ return next;+ };+const cancel = (id, source) => {assertNotRealDataWrite(activeDir, 'database maintenance cancel');// A per-operation exclusive cancellation claim prevents two cancellations@@ -136,7 +173,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {return { id, stage: 'cancelled' };};- return { isFenced, assertAdmission, read, begin, cancel };+ return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition };}const journal = createDatabaseMaintenanceJournal();diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.jsindex cd6a7e6109..82fb2aaa43 100644--- a/server/lib/databaseMaintenanceJournal.test.js+++ b/server/lib/databaseMaintenanceJournal.test.js@@ -52,6 +52,55 @@ describe('persistent database maintenance boundary', () => {expect(journal.read()).toEqual(record);});+ it('fences cancellation and competing coordinators through every durable stage', () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ expect(() => journal.acquireCoordinator(operation.id)).toThrow();+ expect(() => journal.cancel(operation.id, source)).toThrow();+ 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']) {+ 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)});`);+ expect(result.status, result.stderr).toBe(0);+ expect(journal.read()).toEqual({ ...operation, stage: next });+ expect(() => journal.transition(operation.id, token, stage, next)).toThrow();+ 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.+ expect(() => journal.cancel(operation.id, source)).toThrow();+ });++ it('publishes a stage once when two processes share the coordinator token', async () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ const code = `import { createDatabaseMaintenanceJournal } from ${JSON.stringify(moduleUrl)};+ const j = createDatabaseMaintenanceJournal(${JSON.stringify(data)});+ try { j.transition(${JSON.stringify(operation.id)}, ${JSON.stringify(token)}, 'accepted', 'quiescing'); }+ catch { process.exitCode = 1; }`;+ const run = () => new Promise(resolve => {+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: 'ignore' });+ child.once('close', code => resolve(code));+ });+ expect((await Promise.all([run(), run()])).sort()).toEqual([0, 1]);+ expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });+ expect(() => journal.assertAdmission()).toThrow();+ });++ it('preserves the fence and prior stage after interrupted stage publication', () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ writeFileSync(join(data, 'database-maintenance', 'stage-accepted.claim'), '{}');+ expect(() => journal.transition(operation.id, token, 'accepted', 'quiescing')).toThrow();+ expect(journal.read()).toEqual(operation);+ expect(() => journal.cancel(operation.id, source)).toThrow();+ expect(journal.isFenced()).toBe(true);+ });+it('blocks a fresh database process, boot graphs, and agent admission while preserving journal identity', () => {const operation = journal.begin({ source, target });// No real pg connection is possible, even if an admission regression occurs.