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: keep catalog media, attachments and mood board imports whole across backups (#9982)
[._.]/ Adam Eivy2042b987a341
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex d5bf446ef4..6f36a20d0b 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -88,7 +88,9 @@ Admission inventory (`withBackupAssetPublication`):| Image-to-3D mesh completion and AR export (`imageTo3d/models.js`) | Covered (#9982 partial): the runner writes `model.glb` outside admission and only the row that marks it ready takes the lease; the AR export's file write and the row stamping it are one lease || Image-to-3D record deletion (`imageTo3d/models.js`) | Reference-only: the row is soft-deleted before the render directory is removed || Rigging and animation retarget (`rigging/autoSkin.js`, `rigging/retarget.js`) | Covered (#9982 partial): the pair is published into its own directory and verified outside admission; the row that first names it takes the lease |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, code animation, peer and share imports, attachments and catalog media, mood boards, archive and document imports |+| Catalog ingredient media and voice-memo scraps, imported round reference audio, Persistent Mind screenshots and songbook attachments (`catalogMedia.js`, `catalogIngestSources.js`, `roundReferenceAudioImport.js`, `persistentMindAttachments.js`, `routes/brainSongbook.js`) | Covered (#9982 partial): the row that first names a landed file takes the lease; the file-backed Persistent Mind and songbook records hold it through their deletions too |+| Mood board re-hosting, Pinterest and X imports, frame extraction and collages (`moodBoard/*.js`) | Covered (#9982 partial): downloads and renders run outside admission; the board row that first names them, and each in-place rewrite of a URL-keyed download, take the lease |+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, code animation, peer and share imports, archive and document imports || Durable replacement/deletion owners not yet classified | Outstanding (#9982) || Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) || Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |@@ -193,6 +195,22 @@ its own directory and only the row naming it takes the lease. Deleted works andmodels keep their directories until tombstone GC or the render settles, aftertheir rows stopped naming them.+Catalog uploads and voice memos, a voice-memo scrap and an imported round+reference audio land their file first; the row that first names it commits+under the lease, so transcription, extraction and the yt-dlp download stay+outside. Persistent Mind screenshot records and songbook attachment lists live+in `data/` files, which one rsync pass copies at a different moment than the+bytes, so their deletions hold the lease from the unlink through the record+write, and a songbook upload holds it from the byte write. The Persistent+Mind's expired-upload sweep, which runs before each message and upload, skips+its pass while a cut is pending instead of delaying them. Mood board downloads,+frame extraction and collage rendering run outside admission; the board row that+first names the result commits under the lease. Re-hosted, Pinterest and X+downloads are keyed by their source URL and rewrite the file in place on a+repeat, so that write takes the lease too. Removing a board item or a board+removes no bytes. A row that fails after its file landed leaves an unreferenced+file, as before.+**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventorieseach durable owner as `admitted`, `reference-only` or `outstanding`, and itstest fails when an `admitted` entry stops taking the lease or a module thatdiff --git a/server/lib/README.md b/server/lib/README.mdindex f90df78da0..8ab3a2bf32 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -626,7 +626,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `backupAssetOwners.js` | `BACKUP_ASSET_OWNERS` inventories every durable file-plus-row owner as `admitted`, `reference-only`, or `outstanding`; `backupAssetConsistency()` derives the consistency a backup snapshot may claim (`global` only when nothing is outstanding, otherwise `admitted-owners` with the outstanding ids). Its test keeps admitted entries and `withBackupAssetPublication` call sites in step. |-| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; `runOutsideBackupAssetPublication(work)` lets a synchronous event fan-out give each listener its own lease; `holdsBackupAssetPublication()` tells a writer whether it runs inside an active lease. |+| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; `runOutsideBackupAssetPublication(work)` lets a synchronous event fan-out give each listener its own lease; `holdsBackupAssetPublication()` tells a writer whether it runs inside an active lease; `backupSnapshotCutPending()` lets optional housekeeping defer instead of waiting out a cut. || `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. || `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. || `browserConfig.js` | Shared `browserExecutablePath` resolution for managed and owned render browsers, plus custom path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex d5a571a9f3..2669657104 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -195,6 +195,35 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'admitted',modules: ['services/rigging/autoSkin.js', 'services/rigging/retarget.js'],},+ {+ // Catalog ingredient media and voice-memo scraps, and an imported round+ // reference audio: the file lands first and the row that first names it+ // commits under the lease. Persistent Mind screenshots and songbook+ // attachments keep their records in data/ files that one rsync pass copies+ // apart from the bytes, so each holds the lease from its first byte change+ // (or, for an upload, the record write) through the record. Committing a+ // voice-memo scrap to an ingredient names bytes the admitted scrap already+ // named, and detaching catalog media removes no bytes.+ id: 'attachments-and-catalog-media',+ status: 'admitted',+ modules: [+ 'services/persistentMindAttachments.js', 'routes/brainSongbook.js', 'services/catalogMedia.js',+ 'services/catalogIngestSources.js', 'services/roundReferenceAudioImport.js',+ ],+ },+ {+ // Re-hosted images, Pinterest and X imports, extracted frames and collages:+ // downloads and renders run outside admission, and the board row that first+ // names them commits under the lease. URL- and pin-keyed downloads rewrite+ // their file in place, so that write takes the lease too. Removing an item+ // or a board removes no bytes.+ id: 'mood-board-imports',+ status: 'admitted',+ modules: [+ 'services/moodBoard/collage.js', 'services/moodBoard/pinterest.js', 'services/moodBoard/privatePinterest.js',+ 'services/moodBoard/xPost.js', 'services/moodBoard/localize.js', 'services/moodBoard/index.js',+ ],+ },// Classified by a code sweep (#9982) but still outside admission. Each entry// names the modules whose file-plus-record workflows are not wrapped yet, so a// continuation can take one and move it up. Entries are per domain, not per@@ -253,24 +282,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze(['services/sharing/peerSyncAssets.js', 'services/sharing/importer.js', 'services/sharing/peerMediaLibrarySync.js',],},- {- // Persistent Mind screenshot attachments, songbook attachments, catalog- // ingredient media and voice memos, and round reference audio.- id: 'attachments-and-catalog-media',- status: 'outstanding',- modules: [- 'services/persistentMindAttachments.js', 'routes/brainSongbook.js', 'services/catalogMedia.js',- 'services/catalogIngestSources.js', 'services/roundReferenceAudioImport.js',- ],- },- {- id: 'mood-board-imports',- status: 'outstanding',- modules: [- 'services/moodBoard/collage.js', 'services/moodBoard/pinterest.js', 'services/moodBoard/privatePinterest.js',- 'services/moodBoard/xPost.js', 'services/moodBoard/localize.js',- ],- },{// ChatGPT archive import and memory-asset deletion, YouTube ingest, and the// digital twin and genome document stores.diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex 62cb3cec8f..22cf6dd782 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -67,6 +67,14 @@ export function holdsBackupAssetPublication() {return publicationScope.getStore()?.active === true;}+/**+ * Whether a backup cut is requested or active. Optional housekeeping that would+ * otherwise wait out the whole snapshot can defer to its next pass instead.+ */+export function backupSnapshotCutPending() {+ return cutRequested || cutActive;+}+/** Wait for already admitted workflows to settle, or reject when they do not. */async function awaitDrain(timeoutMs) {let timer;diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.jsindex c12d086d2d..d12f3e48e1 100644--- a/server/routes/brainSongbook.js+++ b/server/routes/brainSongbook.js@@ -34,6 +34,7 @@ import { applySongPractice } from '../lib/songPractice.js';import * as brainStorage from '../services/brainStorage.js';import { importSongFromUrl } from '../services/brainSongbookImport.js';import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import {pathExists, PATHS, sanitizeFilename, isPathInsideDir,SONGBOOK_ATTACHMENT_EXTENSIONS, saveBase64Upload, serveLocalFile,@@ -165,11 +166,23 @@ router.post('/:id/practice', asyncHandler(async (req, res) => {// ATTACHMENTS// =============================================================================+// Song records and their attachment bytes are both files under data/brain, so+// one backup rsync pass copies them at different moments. Each attachment+// mutation holds the backup lease (#9982) from its first byte change through+// the record write, so a snapshot never pairs a record with bytes from the+// other side of that change.+// POST /:id/attachments — base64 upload; writes bytes + appends meta to recordrouter.post('/:id/attachments', asyncHandler(async (req, res) => {const song = await getSongOr404(req.params.id);const { filename, data, label } = validateRequest(songAttachmentUploadSchema, req.body);+ const { saved, attachment } = await withBackupAssetPublication(() => saveSongAttachment(song.id, { filename, data, label }));+ console.log(`🎸 Song attachment saved: ${saved.filename} (${saved.size} bytes)`);+ res.status(201).json({ attachment });+}));++async function saveSongAttachment(songId, { filename, data, label }) {const saved = await saveBase64Upload(songbookDir(), { filename, data }, {allowedExtensions: SONGBOOK_ATTACHMENT_EXTENSIONS,maxBytes: MAX_ATTACHMENT_SIZE,@@ -186,13 +199,11 @@ router.post('/:id/attachments', asyncHandler(async (req, res) => {// a concurrent upload/delete or a peer-sync apply landing between the read// above and this write would otherwise be clobbered (and win LWW). requireSong// 404s the mid-request tombstone race instead of 201-ing meta never persisted.- requireSong(await brainStorage.updateWith('songs', song.id, (fresh) => ({+ requireSong(await brainStorage.updateWith('songs', songId, (fresh) => ({attachments: [...(Array.isArray(fresh.attachments) ? fresh.attachments : []), attachment],})));-- console.log(`🎸 Song attachment saved: ${saved.filename} (${saved.size} bytes)`);- res.status(201).json({ attachment });-}));+ return { saved, attachment };+}// GET /:id/attachments — synced meta + machine-local presencerouter.get('/:id/attachments', asyncHandler(async (req, res) => {@@ -224,15 +235,17 @@ router.delete('/:id/attachments/:filename', asyncHandler(async (req, res) => {// Filter against the FRESH record inside the store write lock (updateWith) so// a concurrent upload/peer-sync apply isn't clobbered; requireSong 404s the// mid-request tombstone race instead of TypeError-ing on a null record.- const updated = requireSong(await brainStorage.updateWith('songs', song.id, (fresh) => ({- attachments: (Array.isArray(fresh.attachments) ? fresh.attachments : [])- .filter((a) => a.filename !== safeFilename),- })));-- // Bytes may legitimately be absent on this machine (meta synced from a peer).- if (await pathExists(filepath)) {- await unlinkGuarded(filepath);- }+ const updated = await withBackupAssetPublication(async () => {+ const next = requireSong(await brainStorage.updateWith('songs', song.id, (fresh) => ({+ attachments: (Array.isArray(fresh.attachments) ? fresh.attachments : [])+ .filter((a) => a.filename !== safeFilename),+ })));+ // Bytes may legitimately be absent on this machine (meta synced from a peer).+ if (await pathExists(filepath)) {+ await unlinkGuarded(filepath);+ }+ return next;+ });console.log(`🗑️ Song attachment deleted: ${safeFilename}`);res.json({ success: true, filename: safeFilename, attachments: updated.attachments });diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsindex 4f9587701a..9bf03b575e 100644--- a/server/routes/brainSongbook.test.js+++ b/server/routes/brainSongbook.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';-import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';+import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync, readFileSync, readdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { createHash } from 'crypto';@@ -36,9 +36,15 @@ vi.mock('../services/brainSongbookImport.js', () => ({importSongFromUrl: vi.fn(),}));+vi.mock('../lib/databaseMaintenanceJournal.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertDatabaseAdmission: () => {},+}));+import * as brainStorage from '../services/brainStorage.js';import { importSongFromUrl } from '../services/brainSongbookImport.js';import songbookRoutes from './brainSongbook.js';+import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });@@ -578,4 +584,54 @@ describe('Brain SongBook routes', () => {expect(res.status).toBe(404);});});++ // Song records and attachment bytes are separate files under data/brain, so a+ // backup rsync pass copies them at different moments (#9982). Each attachment+ // mutation therefore waits out a held cut before touching either.+ describe('attachment mutations and a backup cut', () => {+ const settle = () => new Promise((resolve) => setTimeout(resolve, 50));++ it('writes neither the bytes nor the record of an upload until the cut releases', async () => {+ brainStorage.getById.mockResolvedValue(baseSong());+ mockUpdateWith(baseSong());+ const uploaded = () => (existsSync(songbookDir()) ? readdirSync(songbookDir()) : [])+ .filter((name) => name.endsWith('-cut-held.txt'));+ const release = await acquireBackupSnapshotCut();+ let pending;+ try {+ pending = request(app)+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)+ .send({ filename: 'cut-held.txt', data: Buffer.from('example').toString('base64'), label: '' })+ .then((res) => res);+ await settle();+ expect(uploaded()).toEqual([]);+ expect(brainStorage.updateWith).not.toHaveBeenCalled();+ } finally {+ release();+ }+ expect((await pending).status).toBe(201);+ expect(uploaded()).toHaveLength(1);+ });++ it('keeps both the record entry and the bytes of a deletion until the cut releases', async () => {+ mkdirSync(songbookDir(), { recursive: true });+ const filepath = join(songbookDir(), 'cccccccc-held.txt');+ writeFileSync(filepath, 'keep me');+ const meta = { filename: 'cccccccc-held.txt', label: '', mime: 'text/plain', size: 7, sha256: 'c'.repeat(64) };+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [meta] }));+ mockUpdateWith(baseSong({ attachments: [meta] }));+ const release = await acquireBackupSnapshotCut();+ let pending;+ try {+ pending = request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/cccccccc-held.txt`).then((res) => res);+ await settle();+ expect(brainStorage.updateWith).not.toHaveBeenCalled();+ expect(existsSync(filepath)).toBe(true);+ } finally {+ release();+ }+ expect((await pending).status).toBe(200);+ expect(existsSync(filepath)).toBe(false);+ });+ });});diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.jsindex 427a30a40a..e4649e6f5d 100644--- a/server/services/catalogIngestSources.js+++ b/server/services/catalogIngestSources.js@@ -33,6 +33,7 @@ import { navigateToUrlPinned } from './browserService.js';import { lookup } from 'dns/promises';import { PATHS, ensureDir, safeJSONParse, writeFileGuarded } from '../lib/fileUtils.js';import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';// Cap fetched/transcribed bodies at the scrap column boundary (the Zod// rawText max). A runaway page or a multi-hour memo can't blow past the DB.@@ -54,10 +55,13 @@ const clampText = (s) => (typeof s === 'string' ? s.slice(0, RAW_TEXT_MAX) : '')* how they PRODUCE rawText / title / metadata; this codifies the "one pipeline"* contract the module header describes. `log` receives the created scrap.*/-async function createScrapAndExtract({ title, rawText, sourceKind, metadata, providerOverride, log }) {+async function createScrapAndExtract({ title, rawText, sourceKind, metadata, providerOverride, log, namesNewAsset = false }) {// Chunk long pastes identically to the textarea flow — createChunkedScrap// returns the PARENT scrap; extraction budgets its complete text for the selected model.- const scrap = await catalogDB.createChunkedScrap({ title, rawText, sourceKind, metadata });+ const createScrap = () => catalogDB.createChunkedScrap({ title, rawText, sourceKind, metadata });+ // A scrap that first names bytes written just before it commits under the+ // backup lease (#9982); the extraction that follows stays outside it.+ const scrap = await (namesNewAsset ? withBackupAssetPublication(createScrap) : createScrap());const draft = await extractIngredientsForScrap({ scrapId: scrap.id, providerOverride });if (log) console.log(log(scrap));return { scrap, draft };@@ -225,6 +229,7 @@ export async function ingestFromVoice(sourceKind: 'voice-memo',metadata: { mediaKey, mimeType },providerOverride,+ namesNewAsset: true,log: (s) => `🎙️ Catalog voice ingest: ${mediaKey} → scrap ${s.id} (${transcript.length} chars)`,});return { scrap, draft, mediaKey };diff --git a/server/services/catalogMedia.js b/server/services/catalogMedia.jsindex 3769ce12bc..b953624fed 100644--- a/server/services/catalogMedia.js+++ b/server/services/catalogMedia.js@@ -17,6 +17,7 @@ import { join } from 'path';import { ensureDir, PATHS, atomicWrite, resolveImageInputPath } from '../lib/fileUtils.js';import { extractPngGenerationMetadata, normalizeGenerationMetadata } from '../lib/pngMetadata.js';import { ServerError } from '../lib/errorHandler.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { getIngredient, attachMedia } from './catalogDB.js';import { readImageSidecar, saveUploadedGalleryImage } from './imageGen/local.js';import { transcribe } from './voice/stt.js';@@ -92,6 +93,11 @@ async function persistLibraryFile(buffer, dir, ext) {return filename;}+// The media row first names bytes written just before it, so it commits under+// the backup lease (#9982): a cut copies files before it dumps rows, and a row+// that waits out the cut can only name a file the copy already took.+const attachUnderLease = (attachMediaFn, ...args) => withBackupAssetPublication(() => attachMediaFn(...args));+async function requireIngredient(getIngredientFn, ingredientId) {const ingredient = await getIngredientFn(ingredientId);if (!ingredient) throw new ServerError('Ingredient not found', { status: 404 });@@ -129,7 +135,7 @@ export async function uploadIngredientMediaFile(const metadata = hasMetadata(saved?.metadata) ? saved.metadata : sourceMetadata;const mediaKey = saved.filename;console.log(`📎 Catalog media upload: image ${mediaKey} → ingredient ${ingredientId}`);- return attachMediaFn(ingredientId, mediaKey, classified.kind, mediaAttachOptions({ ...meta, metadata }));+ return attachUnderLease(attachMediaFn, ingredientId, mediaKey, classified.kind, mediaAttachOptions({ ...meta, metadata }));}const buffer = Buffer.from(dataBase64, 'base64');@@ -137,7 +143,7 @@ export async function uploadIngredientMediaFile(const dir = classified.category === 'audio' ? PATHS.audio : PATHS.videos;const mediaKey = await persistFileFn(buffer, dir, classified.ext);console.log(`📎 Catalog media upload: ${classified.kind} ${mediaKey} → ingredient ${ingredientId} (${(buffer.length / 1024).toFixed(0)}KB, ${filename || 'unnamed'})`);- return attachMediaFn(ingredientId, mediaKey, classified.kind, mediaAttachOptions(meta));+ return attachUnderLease(attachMediaFn, ingredientId, mediaKey, classified.kind, mediaAttachOptions(meta));}/**@@ -167,6 +173,6 @@ export async function recordIngredientVoiceMemo(const ext = AUDIO_EXT[(mimeType || '').toLowerCase().split(';')[0].trim()] || 'wav';const mediaKey = await persistFileFn(buffer, PATHS.audio, ext);console.log(`🎙️ Catalog voice memo: ${mediaKey} → ingredient ${ingredientId} (${transcript.length} chars)`);- const media = await attachMediaFn(ingredientId, mediaKey, 'audio', mediaAttachOptions({ role, caption: transcript || null }));+ const media = await attachUnderLease(attachMediaFn, ingredientId, mediaKey, 'audio', mediaAttachOptions({ role, caption: transcript || null }));return { media, transcript };}diff --git a/server/services/catalogMediaBackupAdmission.test.js b/server/services/catalogMediaBackupAdmission.test.jsnew file mode 100644index 0000000000..815ae81cac--- /dev/null+++ b/server/services/catalogMediaBackupAdmission.test.js@@ -0,0 +1,124 @@+/**+ * Catalog media, voice-memo scraps and imported round reference audio against a+ * backup cut (#9982). Each writes its file first and then commits the row that+ * first names it. A cut copies files before it dumps rows, so the row commit+ * takes the lease: a row held behind a cut can only name bytes the copy took,+ * and the file write and slow work (transcription, extraction, download) stay+ * outside it.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../lib/databaseMaintenanceJournal.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertDatabaseAdmission: () => {},+}));+vi.mock('./catalogDB.js', () => ({ getIngredient: vi.fn(), attachMedia: vi.fn(), createChunkedScrap: vi.fn() }));+vi.mock('./catalogExtraction.js', () => ({ extractIngredientsForScrap: vi.fn() }));+vi.mock('./voice/stt.js', () => ({ transcribe: vi.fn() }));+vi.mock('./browserService.js', () => ({ navigateToUrlPinned: vi.fn() }));+vi.mock('./rounds.js', () => ({ attachReferenceAudio: vi.fn() }));+vi.mock('../lib/safeUrlFetch.js', () => ({ assertPublicHttpUrl: vi.fn(async () => {}) }));+vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(), closeJobAfterDelay: vi.fn() }));+vi.mock('./ytdlpAudioImport.js', () => ({+ resolveYtDlpBinaries: vi.fn(async () => ({ ytDlp: '/mock/yt-dlp', ffmpeg: '/mock/ffmpeg' })),+ downloadAudioToTempMp3: vi.fn(async () => ({ outcome: 'ok', title: 'Example Clip', outPath: '/mock/tmp/clip.mp3' })),+ cleanupYtDlpTemp: vi.fn(async () => {}),+}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ importFileToUploads: vi.fn(async () => ({ filename: 'ab12cd34-Example_Clip.mp3' })),+}));++const catalogDB = await import('./catalogDB.js');+const { extractIngredientsForScrap } = await import('./catalogExtraction.js');+const { attachReferenceAudio } = await import('./rounds.js');+const { importFileToUploads } = await import('../lib/fileUtils.js');+const { uploadIngredientMediaFile, recordIngredientVoiceMemo } = await import('./catalogMedia.js');+const { ingestFromVoice } = await import('./catalogIngestSources.js');+const { startReferenceAudioImport } = await import('./roundReferenceAudioImport.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');++const settle = () => new Promise((resolve) => setTimeout(resolve, 50));+const AUDIO = Buffer.from('example-audio-bytes').toString('base64');++/**+ * Start a workflow while a cut is held, assert what it may already have done+ * (`whileHeld`), then release the cut and resolve with the workflow result.+ */+async function runAcrossCut(start, whileHeld) {+ const release = await acquireBackupSnapshotCut();+ let pending;+ try {+ pending = start();+ await settle();+ whileHeld();+ } finally {+ release();+ }+ return pending;+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ catalogDB.getIngredient.mockResolvedValue({ id: 'ing-example' });+ catalogDB.attachMedia.mockImplementation(async (_id, mediaKey) => ({ mediaKey }));+ catalogDB.createChunkedScrap.mockResolvedValue({ id: 'scrap-example' });+ extractIngredientsForScrap.mockResolvedValue({ ingredients: [] });+ attachReferenceAudio.mockResolvedValue(true);+});++describe('catalog media rows and a backup cut', () => {+ const persistFileFn = vi.fn(async () => 'upload-example.webm');++ it.each([+ ['an uploaded file', () => uploadIngredientMediaFile(+ { ingredientId: 'ing-example', dataBase64: AUDIO, mimeType: 'audio/webm' },+ { persistFileFn },+ )],+ ['a recorded voice memo', () => recordIngredientVoiceMemo(+ { ingredientId: 'ing-example', audioBase64: AUDIO, mimeType: 'audio/webm' },+ { persistFileFn, transcribeFn: async () => ({ text: 'example memo' }) },+ )],+ ])('holds the media row for %s until the cut releases', async (_name, start) => {+ await runAcrossCut(start, () => {+ expect(persistFileFn).toHaveBeenCalled();+ expect(catalogDB.attachMedia).not.toHaveBeenCalled();+ });+ expect(catalogDB.attachMedia).toHaveBeenCalledWith('ing-example', 'upload-example.webm', 'audio', expect.any(Object));+ });++ it('holds a voice-memo scrap naming its audio, and extracts only after it commits', async () => {+ const persistFn = vi.fn(async () => 'voice-memo-example.wav');+ const result = await runAcrossCut(+ () => ingestFromVoice({ audioBase64: AUDIO }, { persistFn, transcribeFn: async () => ({ text: 'example memo' }) }),+ () => {+ expect(persistFn).toHaveBeenCalled();+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();+ },+ );+ expect(result).toMatchObject({ mediaKey: 'voice-memo-example.wav' });+ expect(catalogDB.createChunkedScrap).toHaveBeenCalledWith(expect.objectContaining({+ metadata: expect.objectContaining({ mediaKey: 'voice-memo-example.wav' }),+ }));+ expect(extractIngredientsForScrap).toHaveBeenCalledWith(expect.objectContaining({ scrapId: 'scrap-example' }));+ });+});++describe('imported round reference audio and a backup cut', () => {+ it('lands the file but holds the reference row that names it until the cut releases', async () => {+ let finished;+ const done = new Promise((resolve) => { finished = resolve; });+ attachReferenceAudio.mockImplementation(async () => { finished(); return true; });++ await runAcrossCut(+ () => startReferenceAudioImport('https://example.com/clip', { roundId: 'round-example', referenceId: 'ref-example' }),+ () => {+ expect(importFileToUploads).toHaveBeenCalled();+ expect(attachReferenceAudio).not.toHaveBeenCalled();+ },+ );+ await done;+ expect(attachReferenceAudio).toHaveBeenCalledWith('round-example', 'ref-example', 'ab12cd34-Example_Clip.mp3');+ });+});diff --git a/server/services/moodBoard/backupAdmission.test.js b/server/services/moodBoard/backupAdmission.test.jsnew file mode 100644index 0000000000..22c6a6f7f6--- /dev/null+++ b/server/services/moodBoard/backupAdmission.test.js@@ -0,0 +1,126 @@+/**+ * Mood board imports against a backup cut (#9982). Downloads run outside+ * admission; the board row that first names the downloaded files commits under+ * the lease, so a cut that arrives mid-commit drains it. URL-keyed downloads+ * rewrite their file in place, so that write waits out a held cut too. An item+ * write that names no new bytes never waits on a cut.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../lib/databaseMaintenanceJournal.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertDatabaseAdmission: () => {},+}));+const store = {+ getBoard: vi.fn(),+ appendImportedItems: vi.fn(),+ applyLocalizedItemImages: vi.fn(),+ addBoardItem: vi.fn(),+};+vi.mock('./db.js', () => store);+const net = { fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn() };+vi.mock('../../lib/safeUrlFetch.js', () => net);+vi.mock('../sharing/recordEvents.js', () => ({+ emitRecordUpdated: vi.fn(),+ emitRecordDeleted: vi.fn(),+ autoSubscribeRecordToAllPeers: vi.fn(async () => {}),+}));+const writeFileGuarded = vi.fn(async () => {});+vi.mock('../browserService.js', () => ({ getHealthStatus: vi.fn(), navigateToUrlPinned: vi.fn() }));+vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ PATHS: { images: '/mock/images', videos: '/mock/videos' },+ ensureDir: vi.fn(async () => {}),+ writeFileGuarded: (...args) => writeFileGuarded(...args),+}));++const { importXPost } = await import('./xPost.js');+const { localizeBoardMedia } = await import('./localize.js');+const { addBoardItem } = await import('./index.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');++const settle = () => new Promise((resolve) => setTimeout(resolve, 50));+const JPEG_BYTES = Buffer.from([0xff, 0xd8, 0xff, 0x00]);+const BOARD_ID = 'mb-example';+const POST_URL = 'https://x.com/example/status/42';+const REMOTE_IMAGE = 'https://cdn.example.com/pin.jpg';++/** Pauses the row commit under test until released. */+let hold;+const held = (result) => async (...args) => {+ await hold?.();+ return typeof result === 'function' ? result(...args) : result;+};++/**+ * Pause a workflow at its row commit, request a cut, and prove the cut waits+ * for that commit to settle before it is granted.+ */+async function expectCutDrainsCommit(start) {+ let reachedCommit;+ const reached = new Promise((resolve) => { reachedCommit = resolve; });+ let finishCommit;+ const commitDone = new Promise((resolve) => { finishCommit = resolve; });+ hold = async () => { reachedCommit(); await commitDone; };++ const pending = start();+ await reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });+ try {+ await settle();+ expect(cutReady, 'cut granted while a row naming new bytes was committing').toBe(false);+ } finally {+ finishCommit();+ (await cut)();+ }+ return pending;+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ hold = null;+ net.fetchPublicBinary.mockResolvedValue({ buffer: JPEG_BYTES, contentType: 'image/jpeg' });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({ photos: [{ url: 'https://pbs.example.com/a.jpg' }] }));+ store.getBoard.mockResolvedValue({ id: BOARD_ID, items: [{ id: 'mbi-remote', type: 'image', imageUrl: REMOTE_IMAGE }] });+ store.appendImportedItems.mockImplementation(held((_id, imported) => ({ board: { id: BOARD_ID }, added: imported.length })));+ store.applyLocalizedItemImages.mockImplementation(held((_id, replacements) => ({ board: { id: BOARD_ID }, changed: replacements.length })));+ store.addBoardItem.mockImplementation(held((_id, item) => ({ id: 'mbi-new', ...item })));+});++describe('mood board imports and a backup cut', () => {+ it('holds an X post download and its board append behind a held cut', async () => {+ const release = await acquireBackupSnapshotCut();+ let pending;+ try {+ pending = importXPost(BOARD_ID, { url: POST_URL });+ await settle();+ expect(net.fetchPublicBinary).toHaveBeenCalled();+ expect(writeFileGuarded).not.toHaveBeenCalled();+ expect(store.appendImportedItems).not.toHaveBeenCalled();+ } finally {+ release();+ }+ await expect(pending).resolves.toMatchObject({ added: 1 });+ expect(writeFileGuarded).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['an X post import', () => importXPost(BOARD_ID, { url: POST_URL })],+ ['re-hosting a board', () => localizeBoardMedia(BOARD_ID)],+ ['adding a remote image item', () => addBoardItem(BOARD_ID, { type: 'image', imageUrl: REMOTE_IMAGE, caption: 'Example' })],+ ])('drains a cut behind the row commit for %s', async (_name, start) => {+ await expectCutDrainsCommit(start);+ });++ it('commits an item that names no downloaded bytes while a cut is held', async () => {+ const release = await acquireBackupSnapshotCut();+ try {+ await expect(addBoardItem(BOARD_ID, { type: 'text', text: 'Example note' })).resolves.toMatchObject({ id: 'mbi-new' });+ } finally {+ release();+ }+ expect(net.fetchPublicBinary).not.toHaveBeenCalled();+ });+});diff --git a/server/services/moodBoard/collage.js b/server/services/moodBoard/collage.jsindex 321e203702..61087112ee 100644--- a/server/services/moodBoard/collage.js+++ b/server/services/moodBoard/collage.js@@ -21,6 +21,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, atomicWrite } from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess, probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';import { assetBasename } from '../../lib/localImageFilename.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { boardItemLocalImage, squareGridDims, frameSampleTimes } from './logic.js';import * as store from './db.js';@@ -106,7 +107,8 @@ export async function extractItemFrames(boardId, itemId, { count }) {source: `frame:${file}#${i + 1}of${count}`,caption: item.caption ? `${item.caption} (frame ${i + 1}/${count})` : `Frame ${i + 1}/${count} of ${file}`,}));- const { board: next, added } = await store.appendImportedItems(boardId, imported);+ // The append first names the frame files, so it commits under the backup lease (#9982).+ const { board: next, added } = await withBackupAssetPublication(() => store.appendImportedItems(boardId, imported));if (added) emitRecordUpdated('moodBoard', boardId);console.log(`🎞️ Mood board ${boardId}: extracted ${names.length} frame(s) from ${file}, added ${added}`);return { board: next, added, frames: names };@@ -195,13 +197,12 @@ export async function composeBoardCollage(boardId, { framesPerVideo, addFramesToconst filename = `board-collage-${boardId.replace(/[^A-Za-z0-9]/g, '').slice(0, 12)}-${Date.now()}.jpg`;await atomicWrite(join(PATHS.images, filename), jpeg);- let nextBoard = board;- if (imported.length) {- const res = await store.appendImportedItems(boardId, imported);- nextBoard = res.board;- if (res.added) emitRecordUpdated('moodBoard', boardId);- }- nextBoard = await store.updateBoard(boardId, { collageImageRef: filename });+ // The frame items and the collage ref first name files written above, so+ // both commit under one backup lease (#9982).+ const nextBoard = await withBackupAssetPublication(async () => {+ if (imported.length) await store.appendImportedItems(boardId, imported);+ return store.updateBoard(boardId, { collageImageRef: filename });+ });emitRecordUpdated('moodBoard', boardId);console.log(`🧩 Mood board ${boardId}: collage ${cols}x${rows} (${composites.length} cells, ${skipped} skipped) → ${filename}`);return { filename, url: `/data/images/${filename}`, width, height, cols, rows, cells: composites.length, skipped, board: nextBoard };diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex d250552ee7..55e3ea387c 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -18,6 +18,7 @@import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import * as store from './db.js';import { localizeImageUrl } from './localize.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';// Read paths + federation entry points pass straight through to the store. The// asset-manifest filename resolver lives in logic.js (pure) and is re-exported@@ -168,15 +169,21 @@ async function withLocalImage(input) {return input.imageUrl ? { ...input, imageUrl: await localizeImageUrl(input.imageUrl) } : input;}+// A row that first names an image re-hosted just now commits under the backup+// lease (#9982); every other item write stays outside it.+const commitItem = (rehosted, commit) => (rehosted ? withBackupAssetPublication(commit) : commit());+export async function addBoardItem(id, itemInput) {const resolved = await resolveGalleryItemCaption(itemInput);- const item = await store.addBoardItem(id, await withLocalImage(resolved));+ const localized = await withLocalImage(resolved);+ const item = await commitItem(localized?.imageUrl !== resolved?.imageUrl, () => store.addBoardItem(id, localized));emitRecordUpdated('moodBoard', id);return item;}export async function updateBoardItem(id, itemId, patch) {- const item = await store.updateBoardItem(id, itemId, patch?.imageUrl ? { ...patch, imageUrl: await localizeImageUrl(patch.imageUrl) } : patch);+ const localized = patch?.imageUrl ? { ...patch, imageUrl: await localizeImageUrl(patch.imageUrl) } : patch;+ const item = await commitItem(localized?.imageUrl !== patch?.imageUrl, () => store.updateBoardItem(id, itemId, localized));emitRecordUpdated('moodBoard', id);return item;}diff --git a/server/services/moodBoard/localize.js b/server/services/moodBoard/localize.jsindex 1afd7969fa..62aab794f3 100644--- a/server/services/moodBoard/localize.js+++ b/server/services/moodBoard/localize.js@@ -17,6 +17,7 @@ import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, detectImageFormat, writeFileGuarded } from '../../lib/fileUtils.js';import { fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { externalImageItems, isExternalImageUrl } from './logic.js';import * as store from './db.js';@@ -40,7 +41,9 @@ async function downloadExternalImage(url) {if (!fmt) return null;const filename = `board-${createHash('sha1').update(url.trim()).digest('hex').slice(0, 16)}${fmt.ext}`;await ensureDir(PATHS.images);- await writeFileGuarded(join(PATHS.images, filename), res.buffer);+ // URL-keyed, so a repeat rewrites bytes a board may already name: hold the+ // backup lease (#9982) so the in-place write never overlaps a snapshot.+ await withBackupAssetPublication(() => writeFileGuarded(join(PATHS.images, filename), res.buffer));return `/data/images/${filename}`;}@@ -71,7 +74,8 @@ export async function localizeBoardMedia(boardId) {}}- const { board: next, changed } = await store.applyLocalizedItemImages(boardId, replacements);+ // The swap first names the downloaded files, so it commits under the lease.+ const { board: next, changed } = await withBackupAssetPublication(() => store.applyLocalizedItemImages(boardId, replacements));if (changed) emitRecordUpdated('moodBoard', boardId);console.log(`🖼️ Mood board ${boardId}: re-hosted ${changed} external image(s)${failed ? `, ${failed} failed` : ''}`);return { board: next, localized: changed, failed };diff --git a/server/services/moodBoard/pinterest.js b/server/services/moodBoard/pinterest.jsindex 40fb2f8549..ae0b217117 100644--- a/server/services/moodBoard/pinterest.js+++ b/server/services/moodBoard/pinterest.js@@ -22,6 +22,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, detectImageFormat, writeFileGuarded } from '../../lib/fileUtils.js';import { normalizePinterestFeedUrl, parsePinterestRss } from '../../lib/pinterestFeed.js';import { fetchPublicText, fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { MAX_ITEMS_PER_BOARD } from './logic.js';import * as store from './db.js';@@ -56,7 +57,9 @@ export async function downloadPinImage({ pinUrl, imageUrl, imageUrlOriginal }) {const fmt = detectImageFormat(res.buffer);if (!fmt) return null;const filename = `pinterest-${createHash('sha1').update(pinUrl).digest('hex').slice(0, 16)}${fmt.ext}`;- await writeFileGuarded(join(PATHS.images, filename), res.buffer);+ // Pin-keyed, so a re-download rewrites bytes a board may already name: hold+ // the backup lease (#9982) so the in-place write never overlaps a snapshot.+ await withBackupAssetPublication(() => writeFileGuarded(join(PATHS.images, filename), res.buffer));return `/data/images/${filename}`;}@@ -149,7 +152,10 @@ export async function syncPinterestBoard(boardId) {// Pass the feed we actually fetched so the locked append aborts if the user// unlinked / repointed the board while downloads ran (fetch is outside the lock).const syncedAt = new Date().toISOString();- const { board: nextBoard, added, aborted } = await store.appendPinterestItems(boardId, imported, { syncedAt, expectedFeedUrl: feedUrl });+ // The append first names the downloaded pins, so it commits under the lease.+ const { board: nextBoard, added, aborted } = await withBackupAssetPublication(+ () => store.appendPinterestItems(boardId, imported, { syncedAt, expectedFeedUrl: feedUrl }),+ );if (aborted) {console.log(`📌 Pinterest sync: board ${boardId} aborted — link changed mid-sync`);return { board: nextBoard, added: 0, feedCount: pins.length, aborted: true };diff --git a/server/services/moodBoard/privatePinterest.js b/server/services/moodBoard/privatePinterest.jsindex 6cf196a9cd..24f2ff3c32 100644--- a/server/services/moodBoard/privatePinterest.js+++ b/server/services/moodBoard/privatePinterest.js@@ -9,6 +9,7 @@import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir } from '../../lib/fileUtils.js';import { isBlockedIngestHost } from '../../lib/catalogValidation.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { normalizePinterestFeedUrl } from '../../lib/pinterestFeed.js';import { getHealthStatus, navigateToUrlPinned } from '../browserService.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';@@ -231,7 +232,8 @@ export async function importPrivatePinterestBoard(boardId, { url }) {});}- const { board: nextBoard, added } = await store.appendImportedItems(boardId, imported);+ // The append first names the downloaded pins, so it commits under the backup lease (#9982).+ const { board: nextBoard, added } = await withBackupAssetPublication(() => store.appendImportedItems(boardId, imported));if (added > 0) emitRecordUpdated('moodBoard', boardId);return { board: nextBoard, added, found, skipped: Math.max(0, found - added) };}diff --git a/server/services/moodBoard/xPost.js b/server/services/moodBoard/xPost.jsindex 1a0260b0b5..eea5d2a515 100644--- a/server/services/moodBoard/xPost.js+++ b/server/services/moodBoard/xPost.js@@ -22,6 +22,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, detectImageFormat, detectVideoFormat, writeFileGuarded } from '../../lib/fileUtils.js';import { parseXPostUrl, buildSyndicationUrl, extractXPostMedia } from '../../lib/xPostMedia.js';import { fetchPublicText, fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { MAX_ITEMS_PER_BOARD } from './logic.js';import * as store from './db.js';@@ -41,14 +42,16 @@ function fingerprint(canonicalUrl, tag) {// Download an image (photo or video poster) into data/images/, sniffing the// format from bytes (never trusting Content-Type) — same posture as Pinterest's-// downloadPinImage. Returns the served path, or null on any failure.+// downloadPinImage. Returns the served path, or null on any failure. Both+// downloads are post-keyed, so a re-import rewrites bytes a board may already+// name: each write holds the backup lease (#9982) so it never overlaps a snapshot.async function downloadImage(url, canonicalUrl, tag) {const res = await fetchPublicBinary(url, { timeoutMs: FETCH_TIMEOUT_MS, headers: MEDIA_HEADERS, maxBytes: MAX_IMAGE_BYTES });if (!res?.buffer?.length) return null;const fmt = detectImageFormat(res.buffer);if (!fmt) return null;const filename = `x-${fingerprint(canonicalUrl, tag)}${fmt.ext}`;- await writeFileGuarded(join(PATHS.images, filename), res.buffer);+ await withBackupAssetPublication(() => writeFileGuarded(join(PATHS.images, filename), res.buffer));return `/data/images/${filename}`;}@@ -61,7 +64,7 @@ async function downloadVideo(url, canonicalUrl) {const res = await fetchPublicBinary(url, { timeoutMs: VIDEO_TIMEOUT_MS, headers: MEDIA_HEADERS, maxBytes: MAX_VIDEO_BYTES });if (!res?.buffer?.length || !detectVideoFormat(res.buffer)) return null;const filename = `x-${fingerprint(canonicalUrl, 'video')}.mp4`;- await writeFileGuarded(join(PATHS.videos, filename), res.buffer);+ await withBackupAssetPublication(() => writeFileGuarded(join(PATHS.videos, filename), res.buffer));return filename;}@@ -144,7 +147,8 @@ export async function importXPost(boardId, { url }) {});}- const { board: nextBoard, added } = await store.appendImportedItems(boardId, imported);+ // The append first names the downloaded media, so it commits under the lease.+ const { board: nextBoard, added } = await withBackupAssetPublication(() => store.appendImportedItems(boardId, imported));emitRecordUpdated('moodBoard', boardId);console.log(`🐦 X post import: board ${boardId} +${added} item(s) from ${canonicalUrl}`);return { board: nextBoard, added };diff --git a/server/services/persistentMindAttachments.js b/server/services/persistentMindAttachments.jsindex 7aeffadbe0..99a3366fa3 100644--- a/server/services/persistentMindAttachments.js+++ b/server/services/persistentMindAttachments.js@@ -26,6 +26,7 @@ import {unlinkGuarded,writeFileGuarded,} from '../lib/fileUtils.js';+import { backupSnapshotCutPending, withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { loadState, saveState, withStateLock } from './cosState.js';import { isUpdateInProgress } from './updateChecker.js';@@ -210,8 +211,12 @@ export const resolveMessageAttachments = async (mind, attachmentIds, messageId)return { attachments };};+// Every caller either records an image written just before it or removes image+// bytes before dropping the record that names them. The CoS state file and the+// screenshots are copied at different moments of one backup rsync pass, so the+// whole mutation holds the backup lease (#9982), taken before the state lock.async function mutateMindAttachments(mutator) {- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const root = await loadState();const mind = normalizePersistentMindState(root.persistentMind);const result = await mutator(mind, root);@@ -219,11 +224,14 @@ async function mutateMindAttachments(mutator) {root.persistentMind = normalizePersistentMindState(next);await saveState(root);return { state: root.persistentMind, value: result?.value };- });+ }));}/** Remove expired or invalid unclaimed files in one bounded maintenance pass. */export async function cleanupPersistentMindAttachments({ now = Date.now() } = {}) {+ // Housekeeping only (message sends and uploads run it first): defer the pass+ // to the next call rather than make them wait out a backup cut.+ if (backupSnapshotCutPending()) return { success: true, removed: 0, examined: 0, deferred: true };const result = await mutateMindAttachments(async (mind) => {let examined = 0;let removed = 0;diff --git a/server/services/persistentMindSupervisor.attachments.test.js b/server/services/persistentMindSupervisor.attachments.test.jsindex 8e1223a9c8..a578fb4862 100644--- a/server/services/persistentMindSupervisor.attachments.test.js+++ b/server/services/persistentMindSupervisor.attachments.test.js@@ -30,6 +30,11 @@ vi.mock('./cosState.js', () => ({isDaemonRunning: vi.fn(() => true),}));+vi.mock('../lib/databaseMaintenanceJournal.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertDatabaseAdmission: () => {},+}));+vi.mock('./updateChecker.js', () => ({isUpdateInProgress: vi.fn(() => mocks.updateInProgress),}));@@ -101,6 +106,7 @@ vi.mock('./persistentMindImageCapability.js', () => ({const supervisor = await import('./persistentMindSupervisor.js');const attachmentsService = await import('./persistentMindAttachments.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');const PNG = Buffer.from('example-png-bytes');const uploadRecord = (overrides = {}) => ({@@ -369,6 +375,55 @@ describe('persistent mind image attachment lifecycle', () => {expect(mocks.root.persistentMind.pendingAttachments).toHaveLength(1);});+ // The CoS state file and the screenshots are copied at different moments of+ // one backup rsync pass (#9982), so neither the upload record nor a deletion+ // may change either store while a cut is held.+ it('records an upload and removes a pending image only after a backup cut releases', async () => {+ // State writes are not serialized by the mocked lock, so hold one mutation per cut.+ const acrossCut = async (start, whileHeld) => {+ const release = await acquireBackupSnapshotCut();+ let pending;+ try {+ pending = start();+ await new Promise((resolve) => setTimeout(resolve, 50));+ whileHeld();+ } finally {+ release();+ }+ return pending;+ };++ const uploaded = await acrossCut(+ () => supervisor.createPersistentMindAttachment({ filename: 'diagram.png', data: 'encoded-image' }),+ () => expect(mocks.root.persistentMind.pendingAttachments).toEqual([]),+ );+ expect(uploaded).toMatchObject({ success: true });+ const { attachmentId } = uploaded.attachment;+ mocks.unlink.mockClear();++ const deleted = await acrossCut(+ () => supervisor.deletePersistentMindAttachment(attachmentId),+ () => {+ expect(mocks.unlink).not.toHaveBeenCalled();+ expect(mocks.root.persistentMind.pendingAttachments.map((item) => item.attachmentId)).toEqual([attachmentId]);+ },+ );+ expect(deleted).toEqual({ success: true, attachmentId });+ expect(mocks.root.persistentMind.pendingAttachments).toEqual([]);+ });++ it('defers the cleanup pass, rather than waiting, while a backup cut is held', async () => {+ mocks.root.persistentMind.pendingAttachments = [uploadRecord({ expiresAt: new Date(Date.now() - 1_000).toISOString() })];+ const release = await acquireBackupSnapshotCut();+ try {+ await expect(supervisor.cleanupPersistentMindAttachments()).resolves.toMatchObject({ removed: 0, deferred: true });+ } finally {+ release();+ }+ expect(mocks.unlink).not.toHaveBeenCalled();+ await expect(supervisor.cleanupPersistentMindAttachments()).resolves.toMatchObject({ removed: 1 });+ });+it('reaps an expired unindexed upload marker and its image without scanning durable assets', async () => {const now = Date.parse('2026-08-27T00:00:00.000Z');mocks.readdir.mockResolvedValue([diff --git a/server/services/roundReferenceAudioImport.js b/server/services/roundReferenceAudioImport.jsindex 474f209168..4d94769cf3 100644--- a/server/services/roundReferenceAudioImport.js+++ b/server/services/roundReferenceAudioImport.js@@ -21,6 +21,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from 'import { killWithEscalation } from '../lib/killWithEscalation.js';import { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } from './ytdlpAudioImport.js';import { attachReferenceAudio } from './rounds.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';// Reference performances are short clips — bound resource use so a mistyped// link to a long archive/livestream can't download + transcode unbounded.@@ -122,9 +123,11 @@ export async function startReferenceAudioImport(url, { roundId = null, referenceconst { filename } = await importFileToUploads(outPath, `${title || 'Reference Audio'}.mp3`);// A failed attach must not turn a finished download into an error frame:- // the file is in uploads and the client can still attach it on Save.+ // the file is in uploads and the client can still attach it on Save. The+ // round row first names the imported file, so it commits under the backup+ // lease (#9982): a row that waits out a cut names only bytes it copied.const attached = roundId && referenceId- ? await attachReferenceAudio(roundId, referenceId, filename).catch((err) => {+ ? await withBackupAssetPublication(() => attachReferenceAudio(roundId, referenceId, filename)).catch((err) => {console.error(`❌ Reference-audio import ${shortId(jobId)} could not attach ${filename}: ${err?.message || err}`);return false;})