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 Music Video performance repair, MIDI transcription and autonomous Suno song whole across backups (#9982)
Adam Eivy6716de318b1c
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 809c913507..c7b7d2f01e 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -82,7 +82,8 @@ Admission inventory (`withBackupAssetPublication`):| LoRA training and deployed LoRAs: trained-adapter registration, checkpoint promotion over the deployed adapter, the promoted-checkpoint preview copy, the progress row naming trainer-written samples and checkpoints, run deletion, and LoRA deletion from the LoRA manager or Media Models (`loraTraining/index.js`, `loras.js`) | Covered (#9982 partial): registration and promotion hold one lease from the adapter write through the run row and dataset flag; Civitai and Hugging Face installs admit the sidecar that first names the already-linked weights || Music Video final and excerpt renders, publishing-kit builds and composition document versions (`musicVideo/render.js`, `musicVideo/excerptRender.js`, `musicVideo/publishKit.js`, `musicVideo/compositionDocument.js`) | Covered (#9982 partial): the encoder or import writes the files in place; the history entry and project row that first name them commit under one lease || Music Video excerpt deletion (`musicVideo/excerptService.js`) | Reference-only: the project row drops the excerpt before its unreferenced video and contact sheet are unlinked |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, Music Video performance repair, MIDI transcription and autonomous Suno song, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports |+| Music Video performance repair, MIDI transcription and the autonomous Suno song (`musicVideo/performanceRepair.js`, `audioMidiTranscription.js`, `musicVideo/autonomousService.js`) | Covered (#9982 partial): the boundary frame or `.mid` is written first; the row that first names it (repair revision, project MIDI pointer, track render) commits under one lease, and a declined MIDI result is unlinked inside it |+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, 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) |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 47a1691c9b..078bdeb177 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -128,6 +128,27 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'reference-only',modules: ['services/musicVideo/excerptService.js'],},+ {+ // The repair's boundary frame is written in place, then the revision row+ // that names it commits under the lease.+ id: 'music-video-performance-repair',+ status: 'admitted',+ modules: ['services/musicVideo/performanceRepair.js'],+ },+ {+ // The .mid copy, the project row that names it and the discard unlink are+ // one workflow; the sidecar runs outside admission.+ id: 'music-video-midi-transcription',+ status: 'admitted',+ modules: ['services/audioMidiTranscription.js'],+ },+ {+ // The Suno M4A reaches the music library through its admitted import; the+ // track row that first names it commits under the lease.+ id: 'music-video-autonomous-song',+ status: 'admitted',+ modules: ['services/musicVideo/autonomousService.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@@ -143,16 +164,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze(['services/sprites/animationTrackWorkflow.js',],},- {- // Performance repair's boundary frame, MIDI transcription and the- // autonomous Suno song, where the file is written in place.- id: 'music-video-render-and-record-owners',- status: 'outstanding',- modules: [- 'services/musicVideo/performanceRepair.js', 'services/audioMidiTranscription.js',- 'services/musicVideo/autonomousSuno.js', 'services/musicVideo/autonomousService.js', 'routes/musicVideo.js',- ],- },{// Local, cloud and federated finalize, derived clips (stitch, upscale,// timeline, HTML composition, Blender), poster replacement, upload and download.diff --git a/server/services/audioMidiTranscription.backupAdmission.test.js b/server/services/audioMidiTranscription.backupAdmission.test.jsnew file mode 100644index 0000000000..5bdbe38356--- /dev/null+++ b/server/services/audioMidiTranscription.backupAdmission.test.js@@ -0,0 +1,90 @@+/**+ * MIDI transcription against a backup cut (#9982). The sidecar writes its+ * output outside admission; the copy into the destination directory, the row+ * `onComplete` commits to name it, and the discard unlink are one workflow, so+ * a cut can never copy the directory without the file that a dumped row names.+ */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { existsSync } from 'node:fs';+import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++vi.mock('../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));+vi.mock('../lib/pythonSetup.js', async (importOriginal) => ({+ ...(await importOriginal()),+ isMuscriptorRuntimeReady: vi.fn(async () => true),+ resolveMuscriptorPython: vi.fn(() => 'python3'),+}));+vi.mock('./hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));+vi.mock('../lib/sidecarProcess.js', () => ({+ runSidecarProcess: vi.fn(async ({ args }) => {+ await writeFile(args[args.indexOf('--output') + 1], 'synthetic midi');+ return { ok: true, stdout: 'RESULT' };+ }),+ parseSidecarResult: vi.fn(() => ({ notes: 1 })),+}));++const { startMidiTranscription } = await import('./audioMidiTranscription.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');++const dirs = [];+afterAll(() => Promise.all(dirs.map(dir => rm(dir, { recursive: true, force: true }))));++const settleSeveral = () => new Promise(resolve => setTimeout(resolve, 100));++async function scratch() {+ const dir = await mkdtemp(join(tmpdir(), 'portos-midi-admission-'));+ dirs.push(dir);+ const audioPath = join(dir, 'song.wav');+ await writeFile(audioPath, 'synthetic audio');+ const destDir = join(dir, 'dest');+ return { audioPath, destDir };+}++describe('MIDI transcription backup admission', () => {+ it('copies the .mid and commits its row only after a cut is released', async () => {+ const { audioPath, destDir } = await scratch();+ const onComplete = vi.fn(async () => ({}));+ const release = await acquireBackupSnapshotCut();+ try {+ await startMidiTranscription({ audioPath, destDir, onComplete });+ await settleSeveral();+ expect(onComplete).not.toHaveBeenCalled();+ expect(existsSync(destDir) ? await readdir(destDir) : []).toEqual([]);+ release();+ await vi.waitFor(() => expect(onComplete).toHaveBeenCalledOnce());+ expect(await readdir(destDir)).toHaveLength(1);+ } finally {+ release();+ }+ });++ it('drains a cut behind a transcription that is committing its row, then removes a declined file inside the lease', async () => {+ const { audioPath, destDir } = await scratch();+ let enteredRow;+ const entered = new Promise(resolve => { enteredRow = resolve; });+ let finishRow;+ const rowDone = new Promise(resolve => { finishRow = resolve; });+ await startMidiTranscription({+ audioPath,+ destDir,+ onComplete: async () => { enteredRow(); await rowDone; return { discarded: true, reason: 'audio source changed' }; },+ });+ await entered;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try {+ await settleSeveral();+ expect(cutReady, 'cut acquired while the .mid row was still committing').toBe(false);+ finishRow();+ const release = await cut;+ // The declined file was unlinked inside the lease, so the cut sees neither it nor a row.+ expect(await readdir(destDir)).toEqual([]);+ release();+ } finally {+ finishRow();+ (await cut)();+ }+ });+});diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.jsindex 7675369ce5..e8e7591bcd 100644--- a/server/services/audioMidiTranscription.js+++ b/server/services/audioMidiTranscription.js@@ -28,6 +28,7 @@ import { unlink } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { tmpdir } from 'os';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { PATHS, shortId, importFileToDir } from '../lib/fileUtils.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { MUSCRIPTOR_MODELS } from '../lib/muscriptorModels.js';@@ -224,8 +225,15 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri}broadcastSse(job, { type: 'progress', stage: 'importing' });- const { filename } = await importFileToDir(tempOut, `${outputName}.mid`, destDir);- const extra = (await onComplete?.({ filename, model: resolvedModel })) || {};+ // The .mid copy, the row that names it and the discard unlink are one+ // backup-admitted workflow (#9982): a snapshot never dumps a row for a+ // file its copy missed, nor copies a file whose row was just declined.+ const { filename, extra } = await withBackupAssetPublication(async () => {+ const imported = await importFileToDir(tempOut, `${outputName}.mid`, destDir);+ const result = (await onComplete?.({ filename: imported.filename, model: resolvedModel })) || {};+ if (result.discarded) await unlink(join(destDir, imported.filename)).catch(() => {});+ return { filename: imported.filename, extra: result };+ });// `onComplete` may decline the result (`discarded: true` — e.g. the music// video's audio source changed mid-run, so this .mid is of the OLD@@ -233,7 +241,6 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri// orphaned file and tell the client it was discarded, not "ready".if (extra.discarded) {console.log(`🗑️ MIDI transcription ${shortId(jobId)} discarded — ${extra.reason || 'stale result'}`);- await unlink(join(destDir, filename)).catch(() => {});broadcastSse(job, { type: 'complete', discarded: true, model: resolvedModel });return;}diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex eb6570b860..44e6a43e7c 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -63,6 +63,7 @@ import {normalizeSunoOptions,sunoSongFields,} from '../../lib/musicVideoAutonomous.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';@@ -379,7 +380,9 @@ const STAGES = {title: fields.title, concept: run.brief.prompt, lyrics: fields.lyrics, prompt: fields.style,});const durationSec = await deps.probeDuration(song.filename);- await deps.attachAudio(track.id, song.filename, { source: 'suno', prompt: fields.style, lyrics: fields.lyrics, durationSec });+ // The imported M4A is already durable; the track row that first names it+ // commits under a backup lease (#9982).+ await withBackupAssetPublication(() => deps.attachAudio(track.id, song.filename, { source: 'suno', prompt: fields.style, lyrics: fields.lyrics, durationSec }));// Linking the track seeds the project's timed lyric cues from the track lyrics.await deps.updateProject(project.id, { trackId: track.id });return { output: { trackId: track.id, sunoSongIds: song.songIds } };diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex d0fb900954..2bf70d7ab3 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -126,6 +126,21 @@ describe('startAutonomousVideo', () => {expect(doubles.attachAudio).toHaveBeenCalledWith('track-1', 'music-song-a.mp3', expect.objectContaining({ source: 'suno', durationSec: 187 }));});+ it('names the imported Suno song on its track only after a backup cut is released (#9982)', async () => {+ const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+ const release = await acquireBackupSnapshotCut();+ try {+ await service.startAutonomousVideo({ prompt: 'a courier crosses a rainy city' });+ await vi.waitFor(() => expect(calls).toContain('probe'));+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(doubles.attachAudio).not.toHaveBeenCalled();+ release();+ await vi.waitFor(() => expect(doubles.attachAudio).toHaveBeenCalledOnce());+ } finally {+ release();+ }+ });+it.each([{ mediaMode: 'code-images', explicit: true },{ mediaMode: 'code-images-video', explicit: false },diff --git a/server/services/musicVideo/performanceRepair.js b/server/services/musicVideo/performanceRepair.jsindex 27db5f67e8..0ac6365ec5 100644--- a/server/services/musicVideo/performanceRepair.js+++ b/server/services/musicVideo/performanceRepair.js@@ -6,6 +6,7 @@ import { randomUUID } from 'crypto';import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { join } from 'path';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { findFfmpeg, probeVideoStreamInfo, runFfmpegProcess, safeUnder } from '../../lib/ffmpeg.js';@@ -112,8 +113,10 @@ export async function startPerformanceRepair(projectId, sceneId, input) {await unlink(output).catch(() => {});throw refuse('Review needed: the accepted boundary frame could not be extracted');}- return mutateProjectRecord(projectId, (current) => {+ // ffmpeg wrote the boundary frame in place; the row that first names it+ // commits under a backup lease (#9982). A refused commit unlinks the frame.+ return withBackupAssetPublication(() => mutateProjectRecord(projectId, (current) => {if (basis(current) !== basis(project)) throw refuse('The project changed during frame preparation — review it again', 'PERFORMANCE_REPAIR_STALE');return startPerformanceRepairOnProject(current, sceneId, input, filename, referenceFrameSec);- }).catch(async (error) => { await unlink(output).catch(() => {}); throw error; });+ })).catch(async (error) => { await unlink(output).catch(() => {}); throw error; });}