Skip to content

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

fix(backup): admit audio replacement of recorded videos

[._.]/ Adam Eivyf39f132bea2a
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 6d19395391..5dde93123d 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -102,6 +102,8 @@ Admission inventory (`withBackupAssetPublication`):
| 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 |
+| Pipeline audio mux (music, voice, generated cues, silent strip), including Creative Director stitch/final assembly | Covered (#9982 partial): encoding runs outside admission; replacement of the already-recorded video and rollback hold the lease. CD final/rough-cut rows only reference the existing history entry |
+| Music Video Making-of export (`makingOf.js`, `makingOfVisuals.js`) | Reference-only: reads existing assets and transforms buffers for the ZIP response; no durable file or row writes |
| 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.js
index 636c589751..a25c47cbc3 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -69,6 +69,27 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/creativeDirector/completionHook.js',
],
},
+ {
+ // Creative Director audio passes replace a video already named by history.
+ // Each mux encodes outside admission and leases only installation/rollback.
+ id: 'pipeline-audio-mux-installation',
+ status: 'admitted',
+ modules: ['services/pipeline/audioMux.js'],
+ },
+ {
+ // Final/rough-cut rows name the existing timeline history entry; these
+ // callers' audio replacements are admitted by the shared mux helpers.
+ id: 'creative-director-cut-settlement',
+ status: 'reference-only',
+ modules: ['services/creativeDirector/stitchRunner.js', 'services/creativeDirector/videoAssembly.js'],
+ },
+ {
+ // Reads existing assets, transforms in buffers, returns a ZIP response.
+ // No durable file or row is written by either making-of module.
+ id: 'music-video-making-of-export',
+ status: 'reference-only',
+ modules: ['services/musicVideo/makingOf.js', 'services/musicVideo/makingOfVisuals.js'],
+ },
{ id: 'music-video-production-settlement', status: 'reference-only', modules: ['services/musicVideo/productionService.js'] },
{ id: 'sprite-animation-completion', status: 'admitted', modules: ['services/sprites/localAnimationJobHook.js'] },
{ id: 'music-library-import-and-deletion', status: 'admitted', modules: ['services/pipeline/musicLibrary.js'] },
diff --git a/server/services/creativeDirector/stitchRunner.test.js b/server/services/creativeDirector/stitchRunner.test.js
index ce762d9c3b..ed06fead1d 100644
--- a/server/services/creativeDirector/stitchRunner.test.js
+++ b/server/services/creativeDirector/stitchRunner.test.js
@@ -95,6 +95,7 @@ vi.mock('../../lib/childProcess.js', async () => {
});
const { runStitch } = await import('./stitchRunner.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
beforeEach(async () => {
updateProjectCalls.length = 0;
@@ -146,3 +147,19 @@ describe('runStitch — audio mux is best-effort', () => {
expect(await readdir(VIDEOS_DIR)).toEqual([FINAL_ENTRY.filename]);
});
});
+
+it('keeps the recorded video and final-cut settlement behind an active backup cut', async () => {
+ ffmpegWritesOutput = true;
+ const release = await acquireBackupSnapshotCut();
+ const work = runStitch('cd-1');
+ try {
+ await vi.waitFor(async () => expect((await readdir(VIDEOS_DIR)).some(name => name.includes('.silent.'))).toBe(true));
+ expect(await readFile(join(VIDEOS_DIR, FINAL_ENTRY.filename), 'utf8')).toBe(EPISODE_BYTES);
+ expect(cdProject.status).toBe('stitching');
+ expect(cdProject.finalVideoId).toBeUndefined();
+ } finally { release(); }
+ await work;
+ expect(cdProject).toMatchObject({ finalVideoId: FINAL_ENTRY.id, status: 'complete' });
+ expect(await readFile(join(VIDEOS_DIR, FINAL_ENTRY.filename), 'utf8')).toBe(MUXED_BYTES);
+ expect(await readdir(VIDEOS_DIR)).toEqual([FINAL_ENTRY.filename]);
+});
diff --git a/server/services/pipeline/audioMux.backupAdmission.test.js b/server/services/pipeline/audioMux.backupAdmission.test.js
new file mode 100644
index 0000000000..7070c45eb8
--- /dev/null
+++ b/server/services/pipeline/audioMux.backupAdmission.test.js
@@ -0,0 +1,112 @@
+/** Real mux installation against synthetic files and the real snapshot cut. */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot } from '../../lib/mockPathsDataRoot.js';
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+let encoded;
+let installed;
+let releaseInstall;
+let missingOutput;
+let bypassAdmission;
+let encodedInsideLease;
+
+vi.mock('../../lib/backupSnapshotBoundary.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, withBackupAssetPublication: work => bypassAdmission ? work() : actual.withBackupAssetPublication(work) };
+});
+vi.mock('../../lib/ffmpeg.js', async importOriginal => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ findFfmpeg: async () => 'synthetic-ffmpeg',
+ hasAudioStream: async () => false,
+ runFfmpegProcess: async ({ args }) => {
+ const { holdsBackupAssetPublication } = await import('../../lib/backupSnapshotBoundary.js');
+ encodedInsideLease = holdsBackupAssetPublication();
+ if (!missingOutput) await writeFile(args.at(-1), 'muxed');
+ encoded.resolve();
+ return { ok: true };
+ },
+ installEncodedVideo: async (...args) => {
+ const result = await actual.installEncodedVideo(...args);
+ installed.resolve();
+ await releaseInstall.promise;
+ return result;
+ },
+ };
+});
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+const { muxMusicBed, muxVoLines, muxCueBed, muxStripAudio } = await import('./audioMux.js');
+const settle = () => new Promise(resolve => setImmediate(resolve));
+const root = () => lazyTempDataRoot('portos-audio-mux-backup-');
+const video = () => join(root(), 'videos', 'episode.mp4');
+const audio = () => join(root(), 'audio.wav');
+const capture = async () => ({ row: { filename: 'episode.mp4' }, bytes: await readFile(video(), 'utf8') });
+const before = { row: { filename: 'episode.mp4' }, bytes: 'original' };
+const after = { row: { filename: 'episode.mp4' }, bytes: 'muxed' };
+const writers = [
+ { name: 'music bed', run: () => muxMusicBed(video(), { musicPath: audio() }) },
+ { name: 'voice overlay', run: () => muxVoLines(video(), { voLines: [{ path: audio(), offsetSec: 0 }] }) },
+ { name: 'generated cues', run: () => muxCueBed(video(), { cues: [{ path: audio(), startSec: 0, endSec: 2 }] }) },
+ { name: 'silent strip', run: () => muxStripAudio(video()) },
+];
+beforeEach(async () => {
+ encoded = deferred(); installed = deferred(); releaseInstall = deferred();
+ missingOutput = false; bypassAdmission = false; encodedInsideLease = null;
+ await rm(root(), { recursive: true, force: true });
+ await mkdir(join(root(), 'videos'), { recursive: true });
+ await writeFile(video(), 'original');
+ await writeFile(audio(), 'synthetic audio');
+});
+afterAll(cleanupTempDataRoots);
+
+describe.each(writers)('$name backup publication', ({ run }) => {
+ it('encodes outside admission but preserves the named video throughout an open cut', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const work = run();
+ try {
+ await encoded.promise;
+ await settle();
+ expect(encodedInsideLease).toBe(false);
+ expect(await capture()).toEqual(before);
+ } finally { release(); releaseInstall.resolve(); }
+ expect((await work).ok).toBe(true);
+ expect(await capture()).toEqual(after);
+ expect(await readdir(join(root(), 'videos'))).toEqual(['episode.mp4']);
+ });
+
+ it('drains the installation before granting a cut, including failed-install cleanup', async () => {
+ missingOutput = true;
+ const work = run();
+ await installed.promise;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady).toBe(false);
+ } finally { releaseInstall.resolve(); }
+ expect((await work).ok).toBe(false);
+ const release = await cut;
+ try {
+ expect(await capture()).toEqual(before);
+ expect(await readdir(join(root(), 'videos'))).toEqual(['episode.mp4']);
+ } finally { release(); }
+ });
+});
+
+it('the unadmitted negative control replaces the named file during the same cut', async () => {
+ bypassAdmission = true;
+ const release = await acquireBackupSnapshotCut();
+ const work = muxStripAudio(video());
+ try {
+ await installed.promise;
+ expect(await capture()).toEqual(after);
+ } finally { release(); releaseInstall.resolve(); }
+ await work;
+});
diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.js
index 2d1ac541e5..9f02910c60 100644
--- a/server/services/pipeline/audioMux.js
+++ b/server/services/pipeline/audioMux.js
@@ -40,8 +40,13 @@ import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { PATHS } from '../../lib/fileUtils.js';
import { findFfmpeg, runFfmpegProcess, hasAudioStream, safeUnder, installEncodedVideo } from '../../lib/ffmpeg.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { statMusicTrack } from './musicLibrary.js';
+// Mux callers can name an already-published history entry. Encoding stays outside
+// backup admission; each in-place installation (including rollback) takes the
+// lease so a file copy cannot race the replacement of those named bytes.
+
// 0.5 ≈ -6 dB — quiet enough to sit under dialogue once VO mixing lands
// (4d.2), but not so quiet the user wonders if it's there.
const DEFAULT_MUSIC_GAIN = 0.5;
@@ -151,7 +156,7 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAU
// silent original intact rather than a half-written video. A failed install
// rolls back and degrades to "bed skipped" rather than throwing out of the
// caller's stitch (#7237); see the failure-handling note at the top.
- const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'music bed');
+ const installed = await withBackupAssetPublication(() => installEncodedVideo(tmpOut, inputVideoPath, 'music bed'));
if (!installed.ok) return installed;
return { ok: true };
}
@@ -306,7 +311,7 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nul
await unlink(tmpOut).catch(() => {});
return result;
}
- const installed = await withInstall(() => installEncodedVideo(tmpOut, inputVideoPath, 'VO mux'));
+ const installed = await withBackupAssetPublication(() => withInstall(() => installEncodedVideo(tmpOut, inputVideoPath, 'VO mux')));
if (!installed.ok) return installed;
return { ok: true, lineCount: placed.length, ducked: !!usableMusic, clipAudio };
}
@@ -503,7 +508,7 @@ export async function muxCueBed(inputVideoPath, { cues = [], voLines = [], music
await unlink(tmpOut).catch(() => {});
return result;
}
- const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'cue bed');
+ const installed = await withBackupAssetPublication(() => installEncodedVideo(tmpOut, inputVideoPath, 'cue bed'));
if (!installed.ok) return installed;
return { ok: true, cueCount: placedCues.length, ducked: placedVo.length > 0, clipAudio };
}
@@ -537,7 +542,7 @@ export async function muxStripAudio(inputVideoPath, { signal } = {}) {
await unlink(tmpOut).catch(() => {});
return result;
}
- const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'silent strip');
+ const installed = await withBackupAssetPublication(() => installEncodedVideo(tmpOut, inputVideoPath, 'silent strip'));
if (!installed.ok) return installed;
return { ok: true };
}