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(backup): drain digital twin enrichment and peer document publication
[._.]/ Adam Eivy161aca0214c0
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 8b497eb551..6d19395391 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -98,7 +98,7 @@ Admission inventory (`withBackupAssetPublication`):| Peer asset, draft-body and bible pulls, share bucket asset import and the peer library sweep (`sharing/peerSyncAssets.js`, `importer.js`, `peerMediaLibrarySync.js`) | Covered (#9982 partial): downloads run outside admission; the write that lands the bytes with its sidecar, poster and `media_assets` row, the draft or bible replacement, the bucket's asset copy and the sweep's index rebuild each take the lease || ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease || YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease |-| Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion |+| Digital twin documents, enrichment answers/lists, peer document sync and genome upload/delete (`digital-twin-documents.js`, `digital-twin-enrichment.js`, `digital-twin-sync.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion; enrichment provider work stays outside, while peer sync holds the lease from its meta merge through tombstone reaping and document copying || Derived media index (`mediaAssetIndex/`) | Rebuilt: `media_assets` rows are excluded from snapshot dumps; database restore rebuilds atomically from disk before reopening admission, and relevant file restores refresh the mirror || Explicit file purge (`dataManager.js`, `routes/uploads.js`, `routes/attachments.js`) | Covered: single and bulk deletions hold one lease. These operator-directed removals may intentionally leave external references; admission prevents a snapshot from interleaving with the removal, not from preserving that already-deleted state || Image generation completion, upscale/clean tails, variants and sketch pairs (`imageGen/*.js`, `mediaSketches.js`) | Covered (#9982 partial): provider output publication through sidecar and cleanup takes one lease; remote replacement and variant/sketch rewrites restore previous files on failure |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex f422947b6b..636c589751 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -370,7 +370,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([// workflow.id: 'digital-twin-documents-and-genome',status: 'admitted',- modules: ['services/digital-twin-documents.js', 'services/genome.js'],+ modules: ['services/digital-twin-documents.js', 'services/digital-twin-enrichment.js', 'services/digital-twin-sync.js', 'services/genome.js'],},{// Explicit file cleanup can leave external references by design, but onediff --git a/server/services/digital-twin-enrichment.js b/server/services/digital-twin-enrichment.jsindex 607b136d5f..d3b68119d8 100644--- a/server/services/digital-twin-enrichment.js+++ b/server/services/digital-twin-enrichment.js@@ -1,4 +1,6 @@-import { readFile, writeFile } from 'fs/promises';+import { readFile } from 'fs/promises';+import { atomicWrite } from '../lib/fileUtils.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { existsSync } from 'fs';import { join } from 'path';import { getActiveProvider, getProviderById } from './providers.js';@@ -140,7 +142,9 @@ export async function generateEnrichmentQuestion(category, providerOverride, mod};}-async function processScaleAnswer(data) {+const processScaleAnswer = data => withBackupAssetPublication(() => processScaleAnswerLeased(data));++async function processScaleAnswerLeased(data) {const { category, question, scaleValue, scaleQuestionId } = data;const config = ENRICHMENT_CATEGORIES[category];if (!config) throw new Error(`Unknown enrichment category: ${category}`);@@ -207,7 +211,7 @@ async function processScaleAnswer(data) {} else {existingContent = `# ${config.label}\n\n`;}- await writeFile(targetPath, existingContent + '\n' + formattedContent);+ await atomicWrite(targetPath, existingContent + '\n' + formattedContent);// Record scale answerif (!meta.enrichment.scaleQuestionsAnswered) meta.enrichment.scaleQuestionsAnswered = {};@@ -276,6 +280,12 @@ export async function processEnrichmentAnswer(data) {}}+ // Provider work finishes before admission; only the durable publication drains.+ return withBackupAssetPublication(() => persistEnrichmentAnswer(category, config, formattedContent));+}++async function persistEnrichmentAnswer(category, config, formattedContent) {+ await ensureSoulDir();// Append to target documentconst targetPath = join(DIGITAL_TWIN_DIR, config.targetDoc);let existingContent = '';@@ -286,7 +296,7 @@ export async function processEnrichmentAnswer(data) {existingContent = `# ${config.label}\n\n`;}- await writeFile(targetPath, existingContent + '\n' + formattedContent);+ await atomicWrite(targetPath, existingContent + '\n' + formattedContent);// Update metaconst meta = await loadMeta();@@ -496,7 +506,10 @@ Respond in JSON format:/*** Save analyzed list content to document*/-export async function saveEnrichmentListDocument(category, content, items) {+export const saveEnrichmentListDocument = (category, content, items) =>+ withBackupAssetPublication(() => saveEnrichmentListDocumentLeased(category, content, items));++async function saveEnrichmentListDocumentLeased(category, content, items) {const config = ENRICHMENT_CATEGORIES[category];if (!config) {throw new Error(`Unknown enrichment category: ${category}`);@@ -505,7 +518,7 @@ export async function saveEnrichmentListDocument(category, content, items) {await ensureSoulDir();const targetPath = join(DIGITAL_TWIN_DIR, config.targetDoc);- await writeFile(targetPath, content);+ await atomicWrite(targetPath, content);// Update metaconst meta = await loadMeta();diff --git a/server/services/digital-twin-publication.test.js b/server/services/digital-twin-publication.test.jsnew file mode 100644index 0000000000..622ad5803b--- /dev/null+++ b/server/services/digital-twin-publication.test.js@@ -0,0 +1,117 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++const state = vi.hoisted(() => ({ beforeWrite: null, beforeUnlink: null, provider: null, runProvider: null }));+const root = await mkdtemp(join(tmpdir(), 'digital-twin-publication-'));+vi.mock('../lib/fileUtils.js', async original => {+ const actual = await original();+ return { ...actual, PATHS: { ...actual.PATHS, digitalTwin: root },+ atomicWrite: async (path, data) => { await state.beforeWrite?.(path); return actual.atomicWrite(path, data); } };+});+vi.mock('fs/promises', async original => {+ const actual = await original();+ return { ...actual, unlink: async path => { await state.beforeUnlink?.(path); return actual.unlink(path); } };+});+vi.mock('./providers.js', () => ({ getActiveProvider: async () => state.provider, getProviderById: async () => state.provider }));+vi.mock('./promptService.js', () => ({ buildPrompt: async () => 'example prompt' }));+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => state.runProvider(...args) }));+vi.mock('./digital-twin-context.js', () => ({ getDigitalTwinForPrompt: async () => '' }));+vi.mock('./digital-twin-analysis.js', () => ({ generateGapRecommendations: () => [] }));+vi.mock('../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission() {} }));++const { processEnrichmentAnswer, saveEnrichmentListDocument } = await import('./digital-twin-enrichment.js');+const { applyDigitalTwinRemote } = await import('./digital-twin-sync.js');+const { DEFAULT_META, cache } = await import('./digital-twin-meta.js');+const { ENRICHMENT_CATEGORIES } = await import('./digital-twin-constants.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');+const turn = () => new Promise(resolve => setImmediate(resolve));+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };+const document = filename => ({ id: 'example-document', filename, title: 'Example', category: 'core', enabled: true,+ priority: 50, weight: 5, createdAt: '2026-01-01T00:00:00.000Z' });+async function seed(meta = {}) { await writeFile(join(root, 'meta.json'), JSON.stringify({ ...structuredClone(DEFAULT_META), ...meta })); }+async function snapshot() {+ const entries = await Promise.all((await readdir(root)).map(async name => [name, await readFile(join(root, name), 'utf8')]));+ const files = Object.fromEntries(entries);+ return { files, meta: JSON.parse(files['meta.json']) };+}+async function verifyDrains(work, reached, finish, verify) {+ await reached;+ let acquired = false;+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });+ try { await turn(); expect(acquired, 'snapshot must wait for the complete document/meta pair').toBe(false); }+ finally { finish(); }+ await work;+ const release = await cut;+ try { await verify(await snapshot()); } finally { release(); }+}++beforeEach(async () => {+ state.beforeWrite = null; state.beforeUnlink = null; state.provider = null; state.runProvider = null;+ cache.meta.data = null; cache.meta.timestamp = 0;+ await rm(root, { recursive: true, force: true }); await mkdir(root);+ await seed();+});+afterAll(async () => { await rm(root, { recursive: true, force: true }); });++describe('enrichment document publication', () => {+ it.each(['answer', 'scale', 'list'])('drains the %s document rewrite through the saved metadata', async kind => {+ const reached = deferred(); const finish = deferred();+ state.beforeWrite = async path => { if (path.endsWith('meta.json')) { reached.resolve(); await finish.promise; } };+ const category = kind === 'list' ? 'favorite_books' : kind === 'scale' ? 'personality_assessments' : 'core_memories';+ const filename = ENRICHMENT_CATEGORIES[category].targetDoc;+ const work = kind === 'list'+ ? saveEnrichmentListDocument(category, '# Example books\n', [{ title: 'Example book' }])+ : processEnrichmentAnswer({ category, question: 'Example question?', answer: 'Example answer',+ ...(kind === 'scale' ? { questionType: 'scale', scaleValue: 4, scaleQuestionId: 'bf-o-1' } : {}) });+ await verifyDrains(work, reached.promise, finish.resolve, ({ files, meta }) => {+ expect(files[filename]).toContain('Example');+ expect(meta.documents).toEqual(expect.arrayContaining([expect.objectContaining({ filename })]));+ expect(meta.enrichment.questionsAnswered[category]).toBe(1);+ });+ });++ it('allows a snapshot while the provider is pending, then holds its publication outside that cut', async () => {+ const reached = deferred(); const finish = deferred();+ state.provider = { id: 'example', defaultModel: 'example-model' };+ state.runProvider = async () => { reached.resolve(); await finish.promise; return { text: '# Example provider answer' }; };+ const work = processEnrichmentAnswer({ category: 'core_memories', question: 'Example?', answer: 'Example' });+ await reached.promise;+ const release = await acquireBackupSnapshotCut();+ try {+ finish.resolve(); await turn();+ expect((await snapshot()).meta.documents).toEqual([]);+ expect(await readdir(root)).toEqual(['meta.json']);+ } finally { release(); }+ await work;+ expect((await snapshot()).files['MEMORIES.md']).toContain('Example provider answer');+ });+});++describe('peer document sync publication', () => {+ it('drains the meta-first merge through the missing markdown copy', async () => {+ const reached = deferred(); const finish = deferred();+ state.beforeWrite = async path => { if (path.endsWith('EXAMPLE.md')) { reached.resolve(); await finish.promise; } };+ const work = applyDigitalTwinRemote({ meta: { documents: [document('EXAMPLE.md')] }, documents: { 'EXAMPLE.md': '# Example body' } });+ await verifyDrains(work, reached.promise, finish.resolve, ({ files, meta }) => {+ expect(meta.documents).toEqual(expect.arrayContaining([expect.objectContaining({ filename: 'EXAMPLE.md' })]));+ expect(files['EXAMPLE.md']).toBe('# Example body');+ });+ });++ it('keeps the merged tombstone and reaping in the same drained cut', async () => {+ await seed({ documents: [document('EXAMPLE.md')] });+ await writeFile(join(root, 'EXAMPLE.md'), '# Old example');+ const reached = deferred(); const finish = deferred();+ state.beforeUnlink = async path => { if (path.endsWith('EXAMPLE.md')) { reached.resolve(); await finish.promise; } };+ const deletedAt = new Date().toISOString();+ const work = applyDigitalTwinRemote({ meta: { documents: [], deletedDocuments: [{ filename: 'EXAMPLE.md', deletedAt }] },+ documents: { 'EXAMPLE.md': '# Stale peer copy' } });+ await verifyDrains(work, reached.promise, finish.resolve, ({ files, meta }) => {+ expect(meta.documents).toEqual([]);+ expect(meta.deletedDocuments).toEqual([{ filename: 'EXAMPLE.md', deletedAt }]);+ expect(files['EXAMPLE.md']).toBeUndefined();+ });+ });+});diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex d1c55aa86c..e5d7d6a476 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';/*** Digital Twin Sync*@@ -930,19 +931,22 @@ export async function applyDigitalTwinRemote(remoteData) {// derivedAt; taste also preserves the newest user-triggered AI interpretation.count += await applyMerge(TASTE_OBSERVED_FILE, remoteData.tasteObserved, mergeTasteObserved);count += await applyMerge(CHRONOTYPE_OBSERVED_FILE, remoteData.chronotypeObserved, mergeChronotypeObserved);- // Meta BEFORE documents: applyMeta()'s loadMeta() rebuilds meta from a disk- // .md scan when no meta.json exists, creating DEFAULT document entries. If the- // peer's .md files were written first, that rebuild would manufacture default- // entries and mergeMeta's add-only policy would then keep them, discarding the- // sender's real document metadata (title/category/priority/weight). Merging- // meta first preserves the sender's entries; the files are written after.- count += await applyMeta(remoteData.meta);- // Delete tombstones (#3530) gate both directions of the document apply: reap- // local files a peer's delete covers, and skip re-writing anything this- // machine deleted. Read AFTER applyMeta so the merged tombstone list is on disk.- const suppressed = await readSuppressedDocuments();- count += await reapTombstonedDocuments(suppressed);- count += await applyDocuments(remoteData.documents, suppressed);+ count += await withBackupAssetPublication(async () => {+ // Meta BEFORE documents: applyMeta()'s loadMeta() rebuilds meta from a disk+ // .md scan when no meta.json exists, creating DEFAULT document entries. If the+ // peer's .md files were written first, that rebuild would manufacture default+ // entries and mergeMeta's add-only policy would then keep them, discarding the+ // sender's real document metadata (title/category/priority/weight). Merging+ // meta first preserves the sender's entries; the files are written after.+ let documentCount = await applyMeta(remoteData.meta);+ // Delete tombstones (#3530) gate both directions of the document apply: reap+ // local files a peer's delete covers, and skip re-writing anything this+ // machine deleted. Read AFTER applyMeta so the merged tombstone list is on disk.+ const suppressed = await readSuppressedDocuments();+ documentCount += await reapTombstonedDocuments(suppressed);+ documentCount += await applyDocuments(remoteData.documents, suppressed);+ return documentCount;+ });if (isPlainObject(remoteData.autobiography)) {// stories only — config (prompt schedule) is intentionally machine-local.diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex 55fe72159c..09b8e1de89 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -1090,7 +1090,7 @@ Forgets the budget and recommends lodging that exceeds it.expect(result.category).toBe('core_memories');expect(result.targetDoc).toBe('MEMORIES.md');// Should write to the document file and save meta- expect(writeFile).toHaveBeenCalled();+ expect(atomicWrite).toHaveBeenCalledWith(expect.stringContaining('MEMORIES.md'), expect.stringContaining('My first coding project.'));});it('should throw for unknown category', async () => {@@ -1117,7 +1117,7 @@ Forgets the budget and recommends lodging that exceeds it.});// Should write with header since file didn't exist- const docWriteCall = writeFile.mock.calls.find(c => c[0].includes('MEMORIES.md'));+ const docWriteCall = atomicWrite.mock.calls.find(c => c[0].includes('MEMORIES.md'));expect(docWriteCall).toBeTruthy();expect(docWriteCall[1]).toContain('# Core Memories');});