Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(pipeline): mux music bed into CD episode stitch
[._.]/ Adam Eivy543a4836336e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 67bf7736fb..48408a18d9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,24 @@## Added+- **Pipeline audio stage: music bed muxed into the episode video (Phase 4d).**+ When the Creative Director stitch step finishes the timeline render, a+ second ffmpeg pass overlays the issue's `stages.audio.music.trackFilename`+ as a looped-and-cut music bed (`-stream_loop -1 -shortest`, `-c:v copy`,+ default -6 dB gain). The pass is best-effort: a missing ffmpeg, missing+ music file, or non-zero exit logs and leaves the silent stitch in place+ rather than blocking the whole project. The link runs through a new+ `sourceIssueId` back-pointer on the CD project (set at create time in+ `episodeVideo.js`, validated by the create Zod schema). Per-temp-UUID+ output paths keep a future parallel-stitch scenario from racing on the+ destination filename. VO line muxing (per-scene timed dialogue + music+ ducking) is deferred to 4d.2 in PLAN.md once the gap-between-lines+ heuristic has real-world testing. Touches: new+ `server/services/pipeline/audioMux.js` + tests, `server/lib/validation.js`+ (schema parity), `server/services/creativeDirector/local.js`,+ `server/services/creativeDirector/stitchRunner.js`,+ `server/services/pipeline/episodeVideo.js` + tests.+- **Pipeline audio stage: background-music upload + shared library + picker(Phase 4c).** The audio stage now carries an optional music track alongsidethe VO lines, with three new routes: `POSTdiff --git a/PLAN.md b/PLAN.mdindex eb584b1935..b53d3ae6dd 100644--- a/PLAN.md+++ b/PLAN.md@@ -239,10 +239,12 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx- [ ] **Extract migration scaffolding into `data/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.- [ ] **Shots-aware scene-output-contract partial.** `data.sample/prompts/stages/pipeline-extract-scenes.md` now inlines the JSON output contract (with `shots[]`) instead of using `{{> scene-output-contract }}`. If a third shots-using stage ever appears (or a top-level scene field gets added), the partial and the inlined copy in extract-scenes will drift. Split into composable partials (`_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md`) when that third caller materializes — until then the inline copy is the smaller risk.- [ ] **Voice picker on character cards (Pipeline Audio 4b follow-up).** AudioStage renders fine without it (per-line render falls through to the project default voice), but binding `character.voiceId` today requires hand-editing JSON or PATCHing the universe canon. The picker should live on `CanonCard` (`client/src/components/pipeline/CanonCard.jsx`) when `kind === 'character'`: chip with current voice id, dropdown reading `/api/pipeline/tts/voices`, audition button that fetches `/api/pipeline/tts/preview` and plays inline, and a Save handler that PATCHes the universe canon entry (`updateUniverseCharacter` — needs to exist in `apiUniverseBuilder.js`). Same picker re-usable on a per-line override in `AudioStage.jsx`. Local OSS (Kokoro/Piper) always included; 3rd-party engines surface through the same merged list.-- [ ] **Pipeline Audio — music generation + mux (Phase 4c.2 / 4d).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c (user-upload + library + picker) **shipped 2026-05-16**. Remaining:+- [ ] **Pipeline Audio — music generation + VO mux (Phase 4c.2 / 4d.2).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c (user-upload + library + picker) **shipped 2026-05-16**; 4d music-bed mux **shipped 2026-05-16**. Remaining:- **4c.2: Local OSS music generation.** MusicGen via a Python sidecar mirroring the image-gen wiring; new `'gen'` source on `stages.audio.music`. Plug into the same `listMusicLibrary` so generated tracks appear alongside uploads. Investigation needed first: pick a generator. MusicGen-MLX is local but bounded ~30s without sliding-window stitching; AudioLDM2 is older; Suno is the cleanest UX but commercial. ~150 LOC for the AudioStage button + queue routing once the generator is picked.- **4c.3: 3rd-party music engine stubs.** Same UI affordance as the VO engines — once 4c.2 lands the abstraction, 3rd-party engines plug in as sibling sources.- - **4d: Mux VO + music into the episode-video CD stitch.** Extend `server/services/creativeDirector/stitchRunner.js` to read `stages.audio.lines[].audioFilename` + `stages.audio.music.trackFilename` from the source issue and emit a second ffmpeg pass that overlays them onto the per-clip video. Timing: VO tied to scene/dialogue order; music as a full-episode bed at configurable gain. New project-level `audioMode: 'per-clip' | 'silent' | 'pipeline'` ('pipeline' reads from the audio stage); 'per-clip' stays default for back-compat.+ - **4d.2: VO line muxing into the CD stitch.** Today's mux only lays the music bed; per-line VO is unmixed. Walk `storyboards.scenes[].dialogue` to map each audio line to a scene, compute scene-start offsets from the per-clip durations (already in `buildTimelineClips`), then build an ffmpeg filter_complex that places each line at `sceneStart + lineOffsetInScene` and ducks the music bed underneath. Open question worth real-world testing: gap-between-lines heuristic (fixed 800ms? scene-length-aware? based on prose pacing?). Touch sites: `server/services/pipeline/audioMux.js` (extend `muxMusicBed` to `muxPipelineAudio` or add a sibling export), `server/services/creativeDirector/stitchRunner.js#maybeMuxPipelineAudio` (compute timing from `clips[]` + storyboards mapping).+- [ ] **Lift `runFfmpegProcess({ args, signal, stderrTailBytes }) → { ok, reason }` into `server/lib/ffmpeg.js`.** Three call sites today share the spawn → stderr-tail → close → SIGTERM-on-abort pattern: `audioMux.js#runFfmpeg`, `server/lib/ffmpeg.js#upscaleVideo2x`, `server/lib/ffmpeg.js#optimizeForStreaming`. `videoTimeline/local.js` has a fourth variant with per-line broadcast that complicates a full migration — leave that one local. The two simpler call sites collapse to one-liners. Surfaced from /simplify on Phase 4d.+- [ ] **AbortSignal listener cleanup in `audioMux.js#runFfmpeg`.** Today the `signal.addEventListener('abort', kill, { once: true })` is never removed on normal completion. Only a leak if the same `AbortController` is reused across many calls — the stitch step doesn't yet pass a signal, so this is theoretical. Fix when wiring real cancellation: capture the handler ref + `signal.removeEventListener('abort', handler)` in both `close` and `error` paths. Surfaced from /simplify on Phase 4d.- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })` helper in `server/lib/fileUtils.js`.** Three call sites today follow the same readdir + filter-by-extension + stat-per-entry shape: `server/services/loras.js#listLoras` (sidecar reads), `server/services/imageGen/local.js#listGallery` (civitai-aware fields), `server/services/pipeline/musicLibrary.js#listMusicLibrary`. Each carries domain-specific per-entry mapping, so the shared helper takes a `mapEntry(dirent, statResult) → entry|null` callback. Saves ~15 LOC at each site plus a single fix-point for future "use `readdir(withFileTypes:true)` to skip the stat when only `.isFile()` is needed" optimization. Surfaced from the /simplify pass on Phase 4c.- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3976e17921..a0c4b80ad4 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -941,6 +941,10 @@ export const creativeDirectorProjectCreateSchema = z.object({// (videoGen one-offs still default to enabled.)disableAudio: z.boolean().optional().default(true),autoAcceptScenes: z.boolean().optional().default(false),+ // Optional back-pointer to the pipeline issue that spawned this project,+ // used by the stitch step to mix in audio-stage music. Bare CD projects+ // (no pipeline origin) leave this null.+ sourceIssueId: z.string().min(1).max(64).nullable().optional(),});// Update is restricted to a few editable fields. modelId / aspectRatio /diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex b8daf34b71..a41ad58af1 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -42,7 +42,7 @@ export async function getProject(id) {return all.find((p) => p.id === id) || null;}-export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = true, autoAcceptScenes = false }) {+export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = true, autoAcceptScenes = false, sourceIssueId = null }) {const id = `cd-${randomUUID()}`;const now = new Date().toISOString();@@ -65,6 +65,11 @@ export async function createProject({ name, aspectRatio, quality, modelId, targeuserStory,disableAudio,autoAcceptScenes,+ // Optional back-pointer to the pipeline issue that spawned this project.+ // The stitch step uses it to look up `stages.audio.music` and mix it+ // into the final cut. Bare CD projects (no pipeline origin) leave this+ // null and skip the audio-mux pass.+ sourceIssueId,collectionId: collection.id,timelineProjectId: null,finalVideoId: null,diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsindex d630dd1ac2..a8d58959cc 100644--- a/server/services/creativeDirector/stitchRunner.js+++ b/server/services/creativeDirector/stitchRunner.js@@ -11,6 +11,7 @@* make. We removed the previous `stitch` agent task entirely.*/+import { join } from 'path';import {createProject as createTimelineProject,updateProject as updateTimelineProject,@@ -22,6 +23,9 @@ import { loadHistory } from '../videoGen/local.js';import { addItem as addCollectionItem } from '../mediaCollections.js';import { buildTimelineClips } from './orchestrator.js';import { getProject, updateProject } from './local.js';+import { getIssue } from '../pipeline/issues.js';+import { muxMusicBed, resolveMusicTrackPath } from '../pipeline/audioMux.js';+import { PATHS } from '../../lib/fileUtils.js';const FINAL_RENDER_POLL_MS = 3000;const FINAL_RENDER_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes — concat is fast but be generous on big projects.@@ -103,6 +107,9 @@ export async function runStitch(projectId) {return;}+ // Best-effort music-bed overlay (Phase 4d) — must not block the stitch.+ await maybeMuxPipelineAudio(project, finalEntry);+await updateProject(projectId, {finalVideoId: finalEntry.id,status: 'complete',@@ -125,3 +132,24 @@ export async function runStitch(projectId) {function sleep(ms) {return new Promise((r) => setTimeout(r, ms));}++async function maybeMuxPipelineAudio(project, finalEntry) {+ if (!project?.sourceIssueId) return;+ const issue = await getIssue(project.sourceIssueId).catch(() => null);+ if (!issue) {+ console.log(`⚠️ CD stitch mux: source issue ${project.sourceIssueId.slice(0, 8)} not found — skipping`);+ return;+ }+ const musicFilename = issue.stages?.audio?.music?.trackFilename;+ const musicPath = await resolveMusicTrackPath(musicFilename);+ if (!musicPath) return;++ const videoPath = join(PATHS.videos, finalEntry.filename);+ console.log(`🎵 CD stitch mux: overlaying ${musicFilename} onto ${finalEntry.filename}`);+ const result = await muxMusicBed(videoPath, { musicPath });+ if (result.ok) {+ console.log(`✅ CD stitch mux: music bed applied to ${finalEntry.filename}`);+ } else {+ console.log(`⚠️ CD stitch mux: music bed skipped (${result.reason}) — keeping silent output`);+ }+}diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.jsnew file mode 100644index 0000000000..95d9ed2d41--- /dev/null+++ b/server/services/pipeline/audioMux.js@@ -0,0 +1,116 @@+/**+ * Pipeline audio mux — second-pass overlay of pipeline-stage audio onto the+ * already-stitched episode video.+ *+ * Phase 4d v1 covers **background-music bedding**: stripping the timeline's+ * silent track and laying the user-picked music file underneath the video at+ * a configurable gain. The music loops to fill the video length and is cut+ * to match the video duration. VO line muxing (4d.2) lands on top of this+ * same module — the helper signature already accepts `voLines` for that.+ *+ * Failure handling: this is a value-add overlay, not a correctness gate. If+ * the mux pass throws (ffmpeg missing, malformed audio, etc.), callers+ * should log and leave the silent video in place — graceful degradation+ * beats blocking the whole stitch on an optional cosmetic step.+ */++import { spawn } from 'child_process';+import { join } from 'path';+import { rename, unlink } from 'fs/promises';+import { existsSync } from 'fs';+import { randomUUID } from 'crypto';+import { PATHS } from '../../lib/fileUtils.js';+import { findFfmpeg } from '../../lib/ffmpeg.js';+import { statMusicTrack } from './musicLibrary.js';++// 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;++/**+ * Resolve a library music filename to its absolute path on disk, or null+ * when the file is missing / the filename fails validation. Graceful+ * degradation: callers should fall through to the silent video.+ */+export async function resolveMusicTrackPath(trackFilename) {+ const entry = await statMusicTrack(trackFilename).catch(() => null);+ return entry ? join(PATHS.music, entry.filename) : null;+}++/**+ * Mix a music bed onto `inputVideoPath`, replacing the file in place.+ * Returns `{ ok: true }` on success, `{ ok: false, reason }` on failure.+ * `musicGain` is a linear amplitude (1.0 = full volume); default ~-6 dB.+ */+export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAULT_MUSIC_GAIN, signal } = {}) {+ if (!inputVideoPath || !existsSync(inputVideoPath)) {+ return { ok: false, reason: 'input video missing' };+ }+ if (!musicPath || !existsSync(musicPath)) {+ return { ok: false, reason: 'music track missing' };+ }+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not on PATH' };++ // UUID suffix keeps parallel mux passes against the same file from+ // racing on the temp output — single-instance today, but the cost of+ // the UUID is one stack alloc.+ const tmpOut = `${inputVideoPath}.muxing.${randomUUID()}.mp4`;+ const args = [+ '-i', inputVideoPath,+ '-stream_loop', '-1',+ '-i', musicPath,+ '-filter_complex', `[1:a]volume=${Number(musicGain).toFixed(3)},aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo[bed]`,+ '-map', '0:v',+ '-map', '[bed]',+ '-c:v', 'copy',+ '-c:a', 'aac',+ '-b:a', '192k',+ '-shortest',+ '-movflags', '+faststart',+ '-y',+ tmpOut,+ ];++ const result = await runFfmpeg(ffmpeg, args, { signal });+ if (!result.ok) {+ await unlink(tmpOut).catch(() => {});+ return result;+ }+ // Rename only after ffmpeg confirms success — a crashed mux pass leaves+ // the silent original intact rather than a half-written video.+ await rename(tmpOut, inputVideoPath);+ return { ok: true };+}++function runFfmpeg(bin, args, { signal } = {}) {+ return new Promise((resolve) => {+ const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });+ let stderrTail = '';+ const STDERR_TAIL_MAX = 2000;+ proc.stderr.on('data', (chunk) => {+ stderrTail += chunk.toString();+ if (stderrTail.length > STDERR_TAIL_MAX) {+ stderrTail = stderrTail.slice(-STDERR_TAIL_MAX);+ }+ });+ proc.on('error', (err) => resolve({ ok: false, reason: `spawn failed: ${err.message}` }));+ proc.on('close', (code, sig) => {+ if (sig === 'SIGTERM' || sig === 'SIGKILL') {+ resolve({ ok: false, reason: `cancelled (${sig})` });+ return;+ }+ if (code !== 0) {+ const tail = stderrTail.split(/\r?\n/).slice(-4).join(' | ');+ resolve({ ok: false, reason: `ffmpeg exit ${code}: ${tail}` });+ return;+ }+ resolve({ ok: true });+ });+ if (signal) {+ signal.addEventListener('abort', () => proc.kill('SIGTERM'), { once: true });+ }+ });+}++export { DEFAULT_MUSIC_GAIN };diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsnew file mode 100644index 0000000000..ee8e8ac114--- /dev/null+++ b/server/services/pipeline/audioMux.test.js@@ -0,0 +1,174 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdir, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const TEST_HOME = join(tmpdir(), `portos-audiomux-test-${process.pid}-${Date.now()}`);+const FAKE_MUSIC_DIR = join(TEST_HOME, 'music');++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, music: FAKE_MUSIC_DIR },+ };+});++const findFfmpegMock = vi.fn();+vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: (...a) => findFfmpegMock(...a),+}));++// Capture spawn so the test asserts the ffmpeg args without actually+// running ffmpeg. The mock returns a fake child-process object that fires+// 'close' immediately with the configured exit code.+const spawnCalls = [];+let mockExitCode = 0;+let mockStderr = '';+vi.mock('child_process', async () => {+ const actual = await vi.importActual('child_process');+ const fs = await import('fs/promises');+ return {+ ...actual,+ spawn: (bin, args, _opts) => {+ spawnCalls.push({ bin, args });+ const listeners = {};+ const proc = {+ stderr: { on: (event, cb) => { if (event === 'data') cb(Buffer.from(mockStderr)); } },+ on: (event, cb) => { listeners[event] = cb; },+ kill: () => {},+ };+ // The real ffmpeg writes to args[args.length - 1] then exits. Mock+ // that side effect on the success path so the subsequent rename in+ // muxMusicBed has a file to move.+ Promise.resolve().then(async () => {+ if (mockExitCode === 0) {+ const outPath = args[args.length - 1];+ await fs.writeFile(outPath, Buffer.from('muxed')).catch(() => {});+ }+ listeners.close?.(mockExitCode, null);+ });+ return proc;+ },+ };+});++const { muxMusicBed, resolveMusicTrackPath, DEFAULT_MUSIC_GAIN } = await import('./audioMux.js');++beforeEach(async () => {+ spawnCalls.length = 0;+ mockExitCode = 0;+ mockStderr = '';+ findFfmpegMock.mockReset();+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});+ await mkdir(FAKE_MUSIC_DIR, { recursive: true });+});++afterEach(async () => {+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});+});++describe('resolveMusicTrackPath', () => {+ it('returns the absolute path when the file exists in PATHS.music', async () => {+ await writeFile(join(FAKE_MUSIC_DIR, 'theme.mp3'), Buffer.from('m'));+ expect(await resolveMusicTrackPath('theme.mp3')).toBe(join(FAKE_MUSIC_DIR, 'theme.mp3'));+ });++ it('returns null when the filename is missing or empty', async () => {+ expect(await resolveMusicTrackPath(null)).toBeNull();+ expect(await resolveMusicTrackPath('')).toBeNull();+ expect(await resolveMusicTrackPath(' ')).toBeNull();+ });++ it('returns null when the file is not present on disk (graceful degradation)', async () => {+ expect(await resolveMusicTrackPath('ghost.mp3')).toBeNull();+ });++ it('blocks path-traversal even if the stage record is stale', async () => {+ expect(await resolveMusicTrackPath('../etc/passwd')).toBeNull();+ expect(await resolveMusicTrackPath('subdir/foo.mp3')).toBeNull();+ expect(await resolveMusicTrackPath('foo\\bar.mp3')).toBeNull();+ });+});++describe('muxMusicBed', () => {+ it('returns ok:false when ffmpeg is not on PATH (graceful degradation)', async () => {+ findFfmpegMock.mockResolvedValue(null);+ const video = join(TEST_HOME, 'v.mp4');+ const music = join(FAKE_MUSIC_DIR, 'm.mp3');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(music, Buffer.from('mus'));+ const result = await muxMusicBed(video, { musicPath: music });+ expect(result).toEqual({ ok: false, reason: 'ffmpeg not on PATH' });+ expect(spawnCalls).toHaveLength(0);+ });++ it('returns ok:false when the input video is missing', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const result = await muxMusicBed(join(TEST_HOME, 'nope.mp4'), { musicPath: 'whatever' });+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('input video missing');+ expect(spawnCalls).toHaveLength(0);+ });++ it('returns ok:false when the music file is missing', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'v.mp4');+ await writeFile(video, Buffer.from('vid'));+ const result = await muxMusicBed(video, { musicPath: join(TEST_HOME, 'ghost.mp3') });+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('music track missing');+ expect(spawnCalls).toHaveLength(0);+ });++ it('builds an ffmpeg invocation that loops music, copies video, swaps audio', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'v.mp4');+ const music = join(FAKE_MUSIC_DIR, 'm.mp3');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(music, Buffer.from('mus'));++ const result = await muxMusicBed(video, { musicPath: music, musicGain: 0.3 });+ expect(result).toEqual({ ok: true });+ expect(spawnCalls).toHaveLength(1);+ const { args } = spawnCalls[0];+ expect(args).toContain('-stream_loop');+ expect(args).toContain('-shortest');+ expect(args).toContain('-c:v');+ expect(args[args.indexOf('-c:v') + 1]).toBe('copy');+ // The filter complex applies the user-set gain (formatted to 3 dp).+ const filterIdx = args.indexOf('-filter_complex');+ expect(filterIdx).toBeGreaterThan(-1);+ expect(args[filterIdx + 1]).toMatch(/volume=0\.300/);+ // Output path is a uniquely-suffixed `.muxing.<uuid>.mp4` — the rename+ // swaps it over the input on success.+ expect(args[args.length - 1]).toMatch(new RegExp(`^${video.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')}\\.muxing\\.[0-9a-f-]+\\.mp4$`));+ });++ it('uses DEFAULT_MUSIC_GAIN when caller omits musicGain', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'v.mp4');+ const music = join(FAKE_MUSIC_DIR, 'm.mp3');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(music, Buffer.from('mus'));++ await muxMusicBed(video, { musicPath: music });+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];+ expect(filter).toContain(`volume=${DEFAULT_MUSIC_GAIN.toFixed(3)}`);+ });++ it('returns ok:false with stderr tail on non-zero exit', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ mockExitCode = 1;+ mockStderr = 'Stream specifier matches no streams.\nlast line of stderr';+ const video = join(TEST_HOME, 'v.mp4');+ const music = join(FAKE_MUSIC_DIR, 'm.mp3');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(music, Buffer.from('mus'));++ const result = await muxMusicBed(video, { musicPath: music });+ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/ffmpeg exit 1/);+ expect(result.reason).toContain('last line of stderr');+ });+});diff --git a/server/services/pipeline/episodeVideo.js b/server/services/pipeline/episodeVideo.jsindex 3c6e0f4a58..202ac70ea0 100644--- a/server/services/pipeline/episodeVideo.js+++ b/server/services/pipeline/episodeVideo.js@@ -157,6 +157,7 @@ export async function startEpisodeVideoForIssue(issueId, options = {}) {userStory: issue.stages?.prose?.output || null,disableAudio: true,autoAcceptScenes: true,+ sourceIssueId: issueId,});await setCDTreatment(project.id, treatment);diff --git a/server/services/pipeline/episodeVideo.test.js b/server/services/pipeline/episodeVideo.test.jsindex 4ada46a995..b3b16d8eae 100644--- a/server/services/pipeline/episodeVideo.test.js+++ b/server/services/pipeline/episodeVideo.test.js@@ -253,6 +253,7 @@ describe('pipeline episodeVideo helper', () => {expect(cdCreated).toHaveLength(1);expect(cdCreated[0].autoAcceptScenes).toBe(true);expect(cdCreated[0].disableAudio).toBe(true);+ expect(cdCreated[0].sourceIssueId).toBe(issue.id);expect(cdTreatments).toHaveLength(1);expect(cdTreatments[0].treatment.scenes).toHaveLength(2);const refreshed = await issuesSvc.getIssue(issue.id);