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(music-video): intercut edit pass — cut on the song's energy and sung words from existing footage
[._.]/ Adam Eivy08955056a9fc
diff --git a/client/src/components/musicVideo/TypographyPanel.jsx b/client/src/components/musicVideo/TypographyPanel.jsxindex 52587778b2..2d45026f5d 100644--- a/client/src/components/musicVideo/TypographyPanel.jsx+++ b/client/src/components/musicVideo/TypographyPanel.jsx@@ -11,6 +11,8 @@ const TEMPLATES = [['fade', 'Fade'], ['rise', 'Rise'], ['typewriter', 'Typewriteconst PLACEMENTS = [['lower', 'Lower'], ['center', 'Center'], ['upper', 'Upper']];const EMPHASES = [['subtitle', 'Subtitle'], ['hero', 'Hero']];const FONTS = [['sans', 'Sans'], ['serif', 'Serif'], ['mono', 'Mono']];+// #9290: one cut per planned shot, or intercut on energy and sung words.+const CUTTING = [['scene', 'One cut per shot'], ['intercut', 'Intercut on the song']];/*** Composition manifest editor (#8984): switch the final render between plain@@ -52,6 +54,12 @@ export default function TypographyPanel({ project, onEditLocal, onSave }) {{RENDER_STYLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></div>+ <div>+ <label htmlFor="mv-typo-cutting" className="block text-port-text-muted mb-0.5" title="Intercut re-cuts each shot on the song's energy and sung words, reusing cutaway footage — no extra generation.">Cutting</label>+ <select id="mv-typo-cutting" value={composition.cutting || 'scene'} onChange={(e) => replace({ cutting: e.target.value })} className={inputCls}>+ {CUTTING.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div><div><label htmlFor="mv-typo-font" className="block text-port-text-muted mb-0.5">Font</label><select id="mv-typo-font" value={composition.style.font} onChange={(e) => replace({ style: { ...composition.style, font: e.target.value } })} className={inputCls}>diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 1d99115c02..761dcc1a00 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |+| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex d71deef783..b398c90eea 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -271,6 +271,8 @@ export const musicVideoLyricsAlignSchema = z.object({// folder under data/music-video/<projectId>/composition/) seeked over the// song; see services/musicVideo/compositionDocument.js and documentRender.js.export const MUSIC_VIDEO_COMPOSITION_MODES = ['concat', 'composed', 'code', 'document'];+// #9290: 'scene' cuts once per planned shot; 'intercut' re-cuts on section energy and sung words.+export const MUSIC_VIDEO_CUTTING_MODES = ['scene', 'intercut'];// Shipped starting points a project can copy into its document folder.export const MUSIC_VIDEO_DOCUMENT_TEMPLATES = ['layered'];export const MUSIC_VIDEO_DOCUMENT_SOURCES = ['zip', 'directory', 'template'];@@ -350,6 +352,7 @@ export const musicVideoCompositionOverlaySchema = z.object({export const musicVideoCompositionSchema = z.object({version: z.literal(1).optional(),mode: z.enum(MUSIC_VIDEO_COMPOSITION_MODES).optional(),+ cutting: z.enum(MUSIC_VIDEO_CUTTING_MODES).optional(),textCues: z.array(musicVideoTextCueSchema).max(1000).optional(),style: z.object({color: z.string().regex(/^#[0-9a-f]{6}$/i, 'color is #rrggbb').optional(),diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.jsindex 25a17fc215..55424743e5 100644--- a/server/services/musicVideo/composition.js+++ b/server/services/musicVideo/composition.js@@ -20,6 +20,7 @@ import { randomUUID } from 'crypto';import { trimTo } from '../../lib/textUtils.js';import {MUSIC_VIDEO_COMPOSITION_MODES as COMPOSITION_MODES,+ MUSIC_VIDEO_CUTTING_MODES as CUTTING_MODES,MUSIC_VIDEO_DOCUMENT_DIRECTORY,MUSIC_VIDEO_DOCUMENT_SOURCES,MUSIC_VIDEO_TYPOGRAPHY_EMPHASES as TYPOGRAPHY_EMPHASES,@@ -140,6 +141,8 @@ export function normalizeComposition(input) {font: pick(style.font, TYPOGRAPHY_FONTS, 'sans'),},posterSec: toTime(input.posterSec),+ // Absent until chosen (#9290): the autopilot plan picks 'intercut' for an undecided project.+ ...(CUTTING_MODES.includes(input.cutting) ? { cutting: input.cutting } : {}),// Absent unless a code video was actually stored, so a composed manifest// stays the shape peers and clones already compare....(codeVideo ? { codeVideo } : {}),@@ -149,6 +152,15 @@ export function normalizeComposition(input) {};}+/**+ * #9290: the project with `cutting` defaulted for an autopilot production run+ * (intercut) unless the director already chose how it cuts.+ */+export function withAutopilotCutting(project) {+ if (!project || project.composition?.cutting) return project;+ return { ...project, composition: normalizeComposition({ ...(project.composition || {}), cutting: 'intercut' }) };+}+/*** `next` (a normalized manifest, or null) carrying `stored`'s document pointer* instead of whatever `next` holds: only the import routes set the pointer.diff --git a/server/services/musicVideo/intercut.js b/server/services/musicVideo/intercut.jsnew file mode 100644index 0000000000..46f4769829--- /dev/null+++ b/server/services/musicVideo/intercut.js@@ -0,0 +1,182 @@+/**+ * Music Video — intercut edit pass (#9290).+ *+ * The shot plan ties every cut to one generated clip, so cutting faster used+ * to mean paying for more clips. A reference analysis of a viral AI music+ * video (#9289) found ~2.6x our cut rate from ~the same per-frame motion: its+ * pace comes from the EDIT — shots of 1–4 beats in high-energy sections,+ * cuts on sung words, and A/B intercuts that reuse footage.+ *+ * This pass re-cuts the resolved clip list at render time without generating+ * anything:+ *+ * - each section gets a target shot length from its energy rank (the+ * loudest quarter of the song cuts every 2 beats, the quietest every 8);+ * - a footage or still shot longer than ~1.3 targets is split; a cut prefers a sung+ * word's onset (snapped to the half-beat grid when close), else the+ * half-beat nearest the target;+ * - pieces alternate between the host shot — which keeps its continuous+ * time, so a lip-synced performance stays in sync — and a partner cutaway+ * from the same section (else the nearest one), played from the part of+ * its take the edit never showed (its tail after its own out-point);+ * - performance clips are never partners: a sung take only matches the song+ * at its own time. Stills and cards pass through untouched.+ *+ * Pure and deterministic. Every piece reads inside its source (a looping+ * source may wrap); the output tiles exactly the same timeline as the input.+ */++const EPS = 1e-6;+const MIN_PIECE_SEC = 0.4;+const WORD_SNAP_SEC = 0.08;+// Energy rank (0 = quietest section, 1 = loudest) → shot length in beats.+const TIERS = Object.freeze([[0.75, 2], [0.4, 3], [0.15, 4], [0, 8]]);++const round3 = (n) => Math.round(n * 1000) / 1000;+const finite = (n) => typeof n === 'number' && Number.isFinite(n);++/** Seconds per beat: the analysis BPM, else the median beat gap; null without either. */+function beatPeriod(bpm, beats) {+ if (finite(bpm) && bpm > 0) return 60 / bpm;+ const gaps = [];+ for (let i = 1; i < beats.length; i += 1) if (beats[i] > beats[i - 1]) gaps.push(beats[i] - beats[i - 1]);+ if (!gaps.length) return null;+ gaps.sort((a, b) => a - b);+ return gaps[Math.floor(gaps.length / 2)];+}++/** Each section's energy as a 0..1 rank among the song's sections. */+function sectionRanks(sections) {+ const valid = sections.filter((s) => finite(s?.startSec) && finite(s?.endSec) && s.endSec > s.startSec);+ const energies = valid.map((s) => (finite(s.energy) ? s.energy : 0));+ const sorted = [...energies].sort((a, b) => a - b);+ return valid.map((s, i) => {+ const e = energies[i];+ const below = sorted.filter((x) => x < e).length;+ return { startSec: s.startSec, endSec: s.endSec, rank: sorted.length > 1 ? below / (sorted.length - 1) : 0.5, index: i };+ });+}++const tierBeats = (rank) => TIERS.find(([min]) => rank >= min - EPS)[1];++function sectionAt(ranked, t) {+ return ranked.find((s) => t >= s.startSec - EPS && t < s.endSec - EPS) || ranked[ranked.length - 1] || null;+}++/**+ * Cut times strictly inside (t0, t1) for a target piece length: word onsets+ * (snapped to the half-beat grid when within WORD_SNAP_SEC) are preferred+ * within half a beat of the ideal cut; otherwise the half-beat nearest it.+ */+function cutTimes(t0, t1, target, halfGrid, onsets, period) {+ const cuts = [];+ const minPiece = Math.max(MIN_PIECE_SEC, period * 0.75);+ let from = t0;+ while (t1 - from > target * 1.3) {+ const ideal = from + target;+ const window = period / 2;+ const ok = (t) => t - from >= minPiece - EPS && t1 - t >= minPiece - EPS;+ let pick = null;+ let best = Infinity;+ for (const w of onsets) {+ if (w < ideal - window || w > ideal + window || !ok(w)) continue;+ const snapped = nearest(halfGrid, w);+ const at = snapped != null && Math.abs(snapped - w) <= WORD_SNAP_SEC ? snapped : w;+ if (ok(at) && Math.abs(at - ideal) < best) { best = Math.abs(at - ideal); pick = at; }+ }+ if (pick == null) {+ const g = nearest(halfGrid, ideal);+ pick = g != null && Math.abs(g - ideal) <= window && ok(g) ? g : ideal;+ if (!ok(pick)) break;+ }+ cuts.push(round3(pick));+ from = pick;+ }+ return cuts;+}++function nearest(sorted, t) {+ if (!sorted.length) return null;+ let lo = 0;+ let hi = sorted.length - 1;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (sorted[mid] < t) lo = mid + 1; else hi = mid;+ }+ const a = sorted[lo];+ const b = lo > 0 ? sorted[lo - 1] : a;+ return Math.abs(a - t) <= Math.abs(b - t) ? a : b;+}++/**+ * Re-cut `clips` (the snapped, coverage-checked render list, in timeline+ * order). `scenes` supply each clip's shot mode; `sections` (with `energy`),+ * `beats`/`bpm` and sung `words` (`[{ startSec }]`) drive the pacing.+ * Returns a new clip list; the input is returned as-is when there is no beat+ * grid to cut on.+ */+export function intercutClips(clips, { scenes = [], sections = [], beats = [], bpm = null, words = [] } = {}) {+ const list = Array.isArray(clips) ? clips : [];+ const grid = (Array.isArray(beats) ? beats : []).filter(finite).sort((a, b) => a - b);+ const period = beatPeriod(bpm, grid);+ const ranked = sectionRanks(Array.isArray(sections) ? sections : []);+ if (!period || !grid.length || !ranked.length || !list.length) return list;+ const halfGrid = [];+ for (let i = 0; i < grid.length; i += 1) {+ halfGrid.push(grid[i]);+ halfGrid.push(grid[i] + (i + 1 < grid.length ? (grid[i + 1] - grid[i]) / 2 : period / 2));+ }+ const onsets = (Array.isArray(words) ? words : []).map((w) => w?.startSec).filter(finite).sort((a, b) => a - b);+ const modes = new Map((Array.isArray(scenes) ? scenes : []).map((s) => [s?.sceneId, s?.shotMode]));++ // Place every clip on the timeline.+ let cursor = 0;+ const placed = list.map((clip) => {+ const span = clip.outSec - clip.inSec;+ const entry = { clip, t0: cursor, t1: cursor + span, section: sectionAt(ranked, cursor + span / 2) };+ cursor += span;+ return entry;+ });++ // Partner cutaways: footage that is not a sung performance, each with a+ // read head starting after the part the edit already shows.+ const partners = placed+ .filter(({ clip }) => !clip.layer && clip.videoPath && modes.get(clip.sceneId) !== 'performance' && finite(clip.sourceSec) && clip.sourceSec > MIN_PIECE_SEC)+ .map((p) => ({ ...p, head: p.clip.outSec, start: p.clip.inSec, end: p.clip.inSec + p.clip.sourceSec }));++ function takePartner(host, len) {+ const pool = partners.filter((p) => p.clip.sceneId !== host.clip.sceneId && p.clip.videoPath !== host.clip.videoPath && p.end - p.start >= len - EPS);+ if (!pool.length) return null;+ const sameSection = pool.filter((p) => p.section?.index === host.section?.index);+ const candidates = sameSection.length ? sameSection : pool;+ // Nearest in time, then the one with the most unshown footage left.+ candidates.sort((a, b) => Math.abs(a.t0 - host.t0) - Math.abs(b.t0 - host.t0) || (b.end - b.head) - (a.end - a.head));+ const p = candidates[0];+ if (p.head + len > p.end + EPS) p.head = p.start; // wrap: reuse from the take's start+ const inSec = round3(p.head);+ p.head = inSec + len;+ return { ...p.clip, inSec, outSec: round3(inSec + len), duration: round3(len), loop: false, sourceSec: round3(p.end - inSec), intercutOf: host.clip.sceneId };+ }++ const out = [];+ for (const host of placed) {+ const { clip, t0, t1, section } = host;+ const still = clip.layer === 'still';+ if ((clip.layer && !still) || (!still && !clip.videoPath) || !section) { out.push(clip); continue; }+ const target = tierBeats(section.rank) * period;+ const cuts = cutTimes(t0, t1, target, halfGrid, onsets, period);+ if (!cuts.length) { out.push(clip); continue; }+ const bounds = [t0, ...cuts, t1];+ for (let k = 0; k < bounds.length - 1; k += 1) {+ const a = bounds[k];+ const len = round3(bounds[k + 1] - a);+ const partner = k % 2 === 1 ? takePartner(host, len) : null;+ if (partner) { out.push(partner); continue; }+ if (still) { out.push({ ...clip, inSec: 0, outSec: len, duration: len, sourceSec: len }); continue; }+ // The host keeps its own continuous time (a performance stays in sync).+ const inSec = round3(clip.inSec + (a - t0));+ out.push({ ...clip, inSec, outSec: round3(inSec + len), duration: len, ...(clip.loop === false ? { sourceSec: round3(clip.inSec + (clip.sourceSec ?? clip.duration) - inSec) } : {}) });+ }+ }+ return out;+}diff --git a/server/services/musicVideo/intercut.test.js b/server/services/musicVideo/intercut.test.jsnew file mode 100644index 0000000000..18da76fafe--- /dev/null+++ b/server/services/musicVideo/intercut.test.js@@ -0,0 +1,81 @@+/**+ * Intercut edit pass (#9290): energy-tiered pieces cut on sung words, host+ * shots keep continuous (synced) time, partner pieces come from unshown+ * cutaway footage, and the result tiles the same timeline inside every source.+ */+import { describe, expect, it } from 'vitest';+import { intercutClips } from './intercut.js';++const bpm = 120; // 0.5 s beats+const beats = Array.from({ length: 80 }, (_, i) => i * 0.5);+const footage = (sceneId, inSec, spanSec, sourceSec, extra = {}) => ({+ sceneId, videoPath: `/v/${sceneId}.mp4`, width: 1280, height: 720, fps: 24, inSec, outSec: inSec + spanSec, duration: spanSec, sourceSec, loop: false, ...extra,+});+const sections = [+ { startSec: 0, endSec: 10, energy: 0.2 },+ { startSec: 10, endSec: 20, energy: 0.9 },+ { startSec: 20, endSec: 30, energy: 0.5 },+];+const spanOf = (list) => list.reduce((sum, c) => sum + (c.outSec - c.inSec), 0);++describe('intercutClips (#9290)', () => {+ const scenes = [+ { sceneId: 'quiet', shotMode: 'cutaway' },+ { sceneId: 'perf', shotMode: 'performance' },+ { sceneId: 'b-roll', shotMode: 'cutaway' },+ { sceneId: 'mid', shotMode: 'cutaway' },+ ];+ const clips = [+ footage('quiet', 0, 10, 10),+ footage('perf', 1.5, 6, 6.2), // a sung take, edit in-point 1.5 s+ footage('b-roll', 0, 4, 10), // 6 s of its take never shown+ footage('mid', 0, 10, 10, { loop: true }),+ ];++ it('cuts loud sections faster than quiet ones and keeps the timeline', () => {+ const out = intercutClips(clips, { scenes, sections, beats, bpm });+ expect(spanOf(out)).toBeCloseTo(spanOf(clips), 2);+ const inRange = (a, b) => out.filter((c, i) => { const t = spanOf(out.slice(0, i)); return t >= a - 1e-6 && t < b - 1e-6; });+ const loud = inRange(10, 20).length;+ const quiet = inRange(0, 10).length;+ const middle = inRange(20, 30).length;+ expect(quiet).toBeLessThanOrEqual(3); // 8-beat tier: ~4 s pieces, no partner in its section+ expect(loud).toBeGreaterThanOrEqual(8); // 2-beat tier: ~1 s pieces+ expect(middle).toBeGreaterThan(quiet);+ });++ it('keeps a performance host in sync and never uses it as a partner', () => {+ const out = intercutClips(clips, { scenes, sections, beats, bpm });+ let t = 0;+ for (const c of out) {+ if (c.sceneId === 'perf') expect(c.inSec).toBeCloseTo(1.5 + (t - 10), 3); // host time == song time+ t += c.outSec - c.inSec;+ }+ expect(out.filter((c) => c.sceneId === 'perf' && c.intercutOf)).toHaveLength(0);+ expect(out.some((c) => c.sceneId === 'b-roll' && c.intercutOf === 'perf')).toBe(true);+ });++ it('plays partner pieces from footage the edit never showed, inside the source', () => {+ const out = intercutClips(clips, { scenes, sections, beats, bpm });+ const partnerPieces = out.filter((c) => c.intercutOf);+ expect(partnerPieces.length).toBeGreaterThan(0);+ const bRoll = partnerPieces.filter((c) => c.sceneId === 'b-roll');+ expect(bRoll[0].inSec).toBeGreaterThanOrEqual(4 - 1e-6); // starts after its own out-point+ for (const c of out) {+ if (c.loop === false) expect(c.outSec).toBeLessThanOrEqual(c.inSec + (c.sourceSec ?? 0) + 0.25 + 1e-6);+ }+ });++ it('prefers a sung word onset near the target cut', () => {+ const one = [footage('perf', 0, 4, 4), footage('b-roll', 0, 4, 10)];+ const loudOnly = [{ startSec: 0, endSec: 8, energy: 1 }, { startSec: 8, endSec: 9, energy: 0 }];+ const out = intercutClips(one, { scenes, sections: loudOnly, beats, bpm, words: [{ startSec: 1.13 }] });+ expect(out[0].outSec - out[0].inSec).toBeCloseTo(1.13, 2);+ });++ it('passes cards through, and does nothing without a beat grid', () => {+ const card = { sceneId: 'card', layer: 'card', inSec: 0, outSec: 12, duration: 12, cardText: 'X', cardColor: '#000000' };+ expect(intercutClips([card], { scenes, sections, beats, bpm })).toEqual([card]);+ expect(intercutClips(clips, { scenes, sections, beats: [], bpm: null })).toBe(clips);+ });+});diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex f85688eeff..07c191d340 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -26,6 +26,7 @@ import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';+import { withAutopilotCutting } from './composition.js';import {attachProductionReview,cancelProductionOnProject,@@ -302,7 +303,9 @@ export async function startProduction(projectId, { directive, pool: requested, lawait requireProject(projectId);const pool = normalizeProductionPool(requested);await assertPoolEligible(pool, await deps.loadEnv());- const out = await mutateProjectRecord(projectId, (current) => startProductionOnProject(current, {+ // The autopilot cuts on the song (#9290) unless the director chose how it+ // cuts — set before the run captures its creative-setup basis.+ const out = await mutateProjectRecord(projectId, (current) => startProductionOnProject(withAutopilotCutting(current), {directive, pool, limits, reviewer, processId: PROCESS_ID, pricing: poolPricing(pool, current),}));console.log(`🎬 Music Video production ${short(out.run.id)} started: ${out.run.pool.length} allowed route(s), ≤${out.run.limits.maxGenerations} generations, ≤${out.run.limits.maxReviewAttempts} reviews`);diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 64197506a3..c1c6359935 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -202,6 +202,17 @@ describe('music video production run (#9066)', () => {expect(dispatch).toHaveBeenCalledTimes(1);});+ it('has the autopilot cut on the song unless the director chose how it cuts (#9290)', async () => {+ seedProject({ scenes: [], castAndSets: { status: 'skipped' } });+ planProject.mockResolvedValue({ scenesAdded: 0 });+ await start();+ expect(store.get('mv-example').composition.cutting).toBe('intercut');++ seedProject({ scenes: [], castAndSets: { status: 'skipped' }, composition: { mode: 'composed', cutting: 'scene', textCues: [] } });+ await start();+ expect(store.get('mv-example').composition.cutting).toBe('scene');+ });+it('runs the Cast & Sets check-in before the plan and waits for the director in review mode', async () => {seedProject({ scenes: [], visualSpec: { references: [] } });startCastAndSets.mockImplementation(async (projectId, { productionRunId }) => {diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex e77cfc8e54..59fd923a18 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -46,6 +46,7 @@ import { assertCurrentPerformanceTakes } from './performanceShot.js';import { ensureInstanceId } from '../instanceIdentity.js';import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';import { projectSoundBed } from './soundBed.js';+import { intercutClips } from './intercut.js';// Per-project render mutex (keyed by projectId so two projects can render in// parallel; same-project re-entry returns 409 with the live jobId for re-attach).@@ -363,7 +364,12 @@ const evenPx = (n) => Math.max(2, Math.round(n / 2) * 2);// card is a solid colour the typography layer writes its text over. On the// frame grid every section is cut to an exact frame count.function sectionChain(c, input, { canonW, canonH, fps, frames, frameGrid }) {- const trim = frameGrid ? `trim=end_frame=${frames}` : `trim=start=${c.inSec}:end=${c.outSec}`;+ // On the frame grid a footage in-point (a performance edit, an intercut+ // piece #9290) is a start frame; stills and cards always start at 0.+ const startFrame = !c.layer && c.inSec > 0 ? Math.round(c.inSec * fps) : 0;+ const trim = frameGrid+ ? (startFrame > 0 ? `trim=start_frame=${startFrame}:end_frame=${startFrame + frames}` : `trim=end_frame=${frames}`)+ : `trim=start=${c.inSec}:end=${c.outSec}`;if (c.layer === 'card') {return `color=c=0x${c.cardColor.slice(1)}:s=${canonW}x${canonH}:r=${fps},setsar=1,format=yuv420p,${trim},setpts=PTS-STARTPTS`;}@@ -576,17 +582,28 @@ export async function planMusicVideoRender(project) {const rawClips = await resolveSceneClips(project, { layered: composed });const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);const beats = project.audioAnalysis?.beats;- const clips = beatSnapClips(rawClips, beats, { scenes: project.scenes });+ const snapped = beatSnapClips(rawClips, beats, { scenes: project.scenes });// #8964: a new (non-looping) shot must never silently repeat footage to// fill its span. Refuse the render and name the shots that need a trim,// a continuation, a replacement clip, or an explicit loop.- const shortfalls = findCoverageShortfalls(clips);+ const shortfalls = findCoverageShortfalls(snapped);if (shortfalls.length > 0) {throw new ServerError(`${shortfalls.length} shot${shortfalls.length === 1 ? ' is' : 's are'} longer than ${shortfalls.length === 1 ? 'its' : 'their'} source clip — trim, continue, replace, or loop ${shortfalls.length === 1 ? 'it' : 'them'} before rendering`,{ status: 422, code: 'INSUFFICIENT_CLIP_COVERAGE', context: { shortfalls, resolutions: COVERAGE_RESOLUTIONS } },);}+ // #9290: an intercut project re-cuts the covered shots on the song's energy+ // and sung words, reusing cutaway footage — no extra generation.+ const clips = project.composition?.cutting === 'intercut'+ ? intercutClips(snapped, {+ scenes: project.scenes,+ sections: project.audioAnalysis?.sections,+ beats,+ bpm: project.audioAnalysis?.bpm,+ words: (project.lyricCues || []).flatMap((cue) => (Array.isArray(cue?.words) ? cue.words : [])),+ })+ : snapped;const soundBed = await resolveSoundBedPath(project);return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };}diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex edaebbda0c..4194fbc406 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -406,3 +406,17 @@ describe('resolveMasterAudioPath', () => {await expect(resolveMasterAudioPath({ trackId: 't1' })).rejects.toMatchObject({ status: 404, code: 'AUDIO_MISSING' });});});++describe('frame-grid in-points (#9290)', () => {+ it('starts a footage piece at its in-point on the frame grid, and a still or zero in-point at frame 0', () => {+ const clips = [+ { sceneId: 'a', videoPath: '/v/a.mp4', width: 1280, height: 720, fps: 24, inSec: 2, outSec: 3, duration: 1, sourceSec: 4, loop: false },+ { sceneId: 'b', videoPath: '/v/b.mp4', width: 1280, height: 720, fps: 24, inSec: 0, outSec: 1, duration: 1, sourceSec: 4, loop: false },+ { sceneId: 'c', layer: 'card', inSec: 0, outSec: 1, duration: 1, cardText: 'X', cardColor: '#000000' },+ ];+ const { args } = buildMusicVideoFfmpegArgs(clips, '/a/song.wav', '/o/out.mp4');+ const graph = args[args.indexOf('-filter_complex') + 1];+ expect(graph).toContain('trim=start_frame=48:end_frame=72');+ expect(graph).toContain('trim=end_frame=24');+ });+});