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: snap auto-planned music-video cuts to the beat grid instead of asserting beatAligned (#4664)
[._.]/ Adam Eivy230557c6a0f4
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.jsindex c4b7c48250..deb0ad8a94 100644--- a/server/services/musicVideo/audioAnalysis.js+++ b/server/services/musicVideo/audioAnalysis.js@@ -709,3 +709,180 @@ export async function analyzeAudioFileManual(audioPath, { bpm, offsetSec = 0 },if (!decoded) return null;return buildManualAnalysis(decoded.samples, decoded.sampleRate, { bpm, offsetSec });}++// --- Section → beat-grid snapping (#4664) -----------------------------------+//+// `segmentSections` above cuts on energy-novelty WINDOW edges+// (`SECTION_WINDOW_SEC` multiples) — it never consults the beat grid the same+// analysis produces. The autonomous planner used to stamp `beatAligned: true`+// on those spans anyway, which `render.js#beatSnapClips` reads as "the director+// already snapped this, honor it exactly" — so the claim actively suppressed+// the live snap that would have fixed the cut. `snapSectionsToGrid` makes the+// flag earn itself: snap the section edges to the grid here, and report per+// section whether that section's own edges actually landed on it.++// Snap tolerance as a fraction of one beat period. Half a beat is the natural+// bound: no time can sit further than half a period from SOME beat, so a+// planned cut lands on the grid for essentially any edge (only one sitting+// exactly on the midpoint between two beats is ambiguous, and is left alone).+// Being tempo-relative is the point — ~0.43s at 70 BPM, ~0.17s at 180 BPM. A+// fixed constant (render.js uses 0.12s for its trim-only snap) would silently+// stop snapping at fast tempos and over-shoot at slow ones.+const SNAP_TOLERANCE_BEAT_FRACTION = 0.5;+// Used only when the grid is too sparse to measure a period (a single beat).+const SNAP_FALLBACK_TOLERANCE_SEC = 0.12;+// A snap is refused rather than squeezing a section below this. Real sections+// arrive at MIN_SECTION_SEC or longer and edges move by well under a beat, so+// this is a guard for hand-built/legacy analyses, not a normal path.+const MIN_SNAPPED_SECTION_SEC = 1;+// Two times closer than this are the same landmark — also the slack for calling+// an UNMOVED edge "already on the grid".+const GRID_EPS = 0.005;++const round3 = (t) => Number(t.toFixed(3));++/** Ascending, finite, non-negative times only. */+function sortedGrid(times) {+ return (Array.isArray(times) ? times : [])+ .filter((t) => typeof t === 'number' && Number.isFinite(t) && t >= 0)+ .sort((a, b) => a - b);+}++/** Median gap between consecutive grid times, or null when unmeasurable. */+function medianInterval(times) {+ if (times.length < 2) return null;+ const gaps = [];+ for (let i = 1; i < times.length; i++) gaps.push(times[i] - times[i - 1]);+ gaps.sort((a, b) => a - b);+ const mid = Math.floor(gaps.length / 2);+ const median = gaps.length % 2 === 1 ? gaps[mid] : (gaps[mid - 1] + gaps[mid]) / 2;+ return median > 0 ? median : null;+}++/** Nearest grid time to `target`, or null when the nearest is beyond tolerance. */+function nearestWithin(grid, target, toleranceSec) {+ let best = null;+ let bestDist = Infinity;+ for (const t of grid) {+ const dist = Math.abs(t - target);+ if (dist < bestDist) { bestDist = dist; best = t; }+ }+ return best != null && bestDist <= toleranceSec ? best : null;+}++/**+ * Tempo-relative snap tolerance. Prefers the beat period; a downbeats-only+ * grid implies 4/4 bars, so its period is quartered back to a beat.+ */+function deriveTolerance(beatGrid, downbeatGrid) {+ const barPeriod = medianInterval(downbeatGrid);+ const beatPeriod = medianInterval(beatGrid) ?? (barPeriod == null ? null : barPeriod / 4);+ return beatPeriod == null+ ? SNAP_FALLBACK_TOLERANCE_SEC+ : beatPeriod * SNAP_TOLERANCE_BEAT_FRACTION;+}++/**+ * Pure: snap a contiguous section map's INTERNAL boundaries onto the analyzed+ * beat grid, and report which sections ended up genuinely aligned.+ *+ * Rules:+ * - Each internal boundary prefers the nearest **downbeat** within tolerance,+ * falls back to the nearest **beat**, and stays put when neither qualifies.+ * - Boundaries are SHARED: moving section i's end moves section i+1's start, so+ * the timeline stays contiguous and gap-free. A non-contiguous input (a gap+ * between two sections — possible in a hand-built/legacy analysis) leaves that+ * boundary alone rather than inventing a shared edge.+ * - The first start and the final end are ANCHORS and never move: they are the+ * track's own edges, where no cut happens.+ * - A snap that would push either neighbouring section below `minSceneSec`, or+ * that would reorder boundaries, is refused — the edge stays put.+ *+ * `beatAligned[i]` is true only when BOTH of section i's own edges sit on the+ * grid (snapped there, or already there) — anchors count, since there is no cut+ * to align. An edge that could not snap therefore reports false, handing that+ * span back to `beatSnapClips`'s live snapping instead of freezing a cut that+ * ignored the grid. A track with NO grid at all is the one exception, and is+ * explained inline below.+ *+ * @param {Array<{startSec:number,endSec:number}>} sections contiguous, ascending+ * @param {{ downbeats?: number[], beats?: number[], toleranceSec?: number, minSceneSec?: number }} [opts]+ * @returns {{ sections: Array<object>, beatAligned: boolean[] }}+ */+export function snapSectionsToGrid(sections, {+ downbeats = [], beats = [], toleranceSec = null, minSceneSec = MIN_SNAPPED_SECTION_SEC,+} = {}) {+ const out = (Array.isArray(sections) ? sections : []).map((s) => ({ ...s }));+ const beatGrid = sortedGrid(beats);+ const downbeatGrid = sortedGrid(downbeats);+ // No grid at all — `analyzePcm` found no usable tempo. Nothing to snap to,+ // and nothing being suppressed either: `beatSnapClips` has no beats to+ // live-snap against, so refusing the flag here would not hand the span back+ // for correction, it would simply DISCARD the planned timeline and render each+ // scene at its raw source-clip length (a 6s clip standing in for a 20s+ // section). The flag's render contract is "an authored span, do not re-derive+ // it", and with no grid there is nothing to re-derive from — so the planned+ // spans stay honored. The dishonesty this helper exists to fix is claiming+ // alignment while a grid EXISTS that the span never consulted.+ if (out.length === 0 || (beatGrid.length === 0 && downbeatGrid.length === 0)) {+ return { sections: out, beatAligned: out.map(() => true) };+ }++ const tolerance = typeof toleranceSec === 'number' && Number.isFinite(toleranceSec) && toleranceSec >= 0+ ? toleranceSec+ : deriveTolerance(beatGrid, downbeatGrid);+ const onGrid = (t) => nearestWithin(downbeatGrid, t, GRID_EPS) != null+ || nearestWithin(beatGrid, t, GRID_EPS) != null;++ // Candidate target for every internal boundary, computed up front so the+ // left-to-right application can bound each snap by where its RIGHT neighbour+ // could still move to (its candidate, or its original position — whichever is+ // further left). Without that bound, two snaps could converge and starve the+ // section between them.+ const original = out.map((s) => s.endSec);+ const shared = out.map((s, i) => i > 0 && Math.abs(s.startSec - out[i - 1].endSec) <= GRID_EPS);+ const candidates = out.map((_, i) => {+ if (i === 0 || !shared[i]) return null;+ const edge = out[i - 1].endSec;+ return nearestWithin(downbeatGrid, edge, tolerance) ?? nearestWithin(beatGrid, edge, tolerance);+ });++ const alignedStart = out.map(() => false);+ const alignedEnd = out.map(() => false);+ // Track anchors: the video starts when the song starts and ends when it ends.+ alignedStart[0] = true;+ alignedEnd[out.length - 1] = true;++ for (let i = 1; i < out.length; i++) {+ if (!shared[i]) {+ alignedEnd[i - 1] = onGrid(out[i - 1].endSec);+ alignedStart[i] = onGrid(out[i].startSec);+ continue;+ }+ const target = candidates[i];+ const prev = out[i - 1].startSec; // already finalized by an earlier pass+ const nextBound = i + 1 < out.length+ ? Math.min(original[i], candidates[i + 1] ?? original[i])+ : out[i].endSec; // final end is an anchor+ // A strictly-positive floor is what refuses a REORDERING snap as well as a+ // too-short one: a caller passing minSceneSec: 0 must still not be able to+ // collapse or invert a section.+ const floor = Math.max(GRID_EPS, minSceneSec);+ const accepted = target != null+ && target - prev >= floor+ && nextBound - target >= floor;+ if (accepted) {+ const snapped = round3(target);+ out[i - 1].endSec = snapped;+ out[i].startSec = snapped;+ alignedEnd[i - 1] = true;+ alignedStart[i] = true;+ } else {+ const aligned = onGrid(out[i - 1].endSec);+ alignedEnd[i - 1] = aligned;+ alignedStart[i] = aligned;+ }+ }++ return { sections: out, beatAligned: out.map((_, i) => alignedStart[i] && alignedEnd[i]) };+}diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.jsindex 831323a203..e963c8dd60 100644--- a/server/services/musicVideo/audioAnalysis.test.js+++ b/server/services/musicVideo/audioAnalysis.test.js@@ -8,6 +8,7 @@ import {decodeAudioToPcm,buildManualAnalysis,buildManualAnalysisFromCached,+ snapSectionsToGrid,ANALYSIS_SAMPLE_RATE,} from './audioAnalysis.js';import { findFfmpeg } from '../../lib/ffmpeg.js';@@ -362,3 +363,162 @@ describe('analyzeAudioFile (ffmpeg decode round-trip)', () => {expect(await analyzeAudioFile('')).toBeNull();});});++// 120 BPM grid: a beat every 0.5s, a downbeat (4/4) every 2s.+function grid120({ durationSec = 40 } = {}) {+ const beats = [];+ for (let t = 0; t <= durationSec + 1e-9; t += 0.5) beats.push(Number(t.toFixed(3)));+ return { beats, downbeats: beats.filter((_, i) => i % 4 === 0) };+}++const spans = (sections) => sections.map((s) => [s.startSec, s.endSec]);++describe('snapSectionsToGrid', () => {+ const { beats, downbeats } = grid120();++ it('snaps an internal boundary to the nearest downbeat and marks both scenes aligned', () => {+ // 18.2 sits 0.2s past the 18.0 downbeat — inside the derived tolerance+ // (half a 0.5s beat period = 0.25s), and closer than the 18.5 beat.+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 18.2 }, { startSec: 18.2, endSec: 30 }],+ { beats, downbeats },+ );+ expect(spans(result.sections)).toEqual([[0, 18], [18, 30]]);+ expect(result.beatAligned).toEqual([true, true]);+ });++ it('falls back to the nearest beat when the nearest downbeat is out of tolerance', () => {+ // 10.3 → downbeat 10.0 is 0.3s away (> 0.25s tolerance); beat 10.5 is 0.2s.+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 10.3 }, { startSec: 10.3, endSec: 30 }],+ { beats, downbeats },+ );+ expect(spans(result.sections)).toEqual([[0, 10.5], [10.5, 30]]);+ expect(result.beatAligned).toEqual([true, true]);+ });++ it('leaves an edge untouched and reports it unaligned when nothing is within tolerance', () => {+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 10.3 }, { startSec: 10.3, endSec: 30 }],+ { beats, downbeats, toleranceSec: 0.05 },+ );+ expect(spans(result.sections)).toEqual([[0, 10.3], [10.3, 30]]);+ expect(result.beatAligned).toEqual([false, false]);+ });++ it('reports an already-on-grid edge as aligned even though nothing moved', () => {+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 12 }, { startSec: 12, endSec: 30 }],+ { beats, downbeats, toleranceSec: 0 },+ );+ expect(spans(result.sections)).toEqual([[0, 12], [12, 30]]);+ expect(result.beatAligned).toEqual([true, true]);+ });++ it('keeps the planned spans honored when the track has no usable tempo', () => {+ // With no grid there is no live snap to hand the span back to — dropping the+ // flag would make render.js#beatSnapClips fall through to each clip's RAW+ // source duration (a 6s clip for a 20s section), throwing away the plan.+ const sections = [{ startSec: 0, endSec: 10.3 }, { startSec: 10.3, endSec: 30 }];+ const result = snapSectionsToGrid(sections, { beats: [], downbeats: [] });+ expect(spans(result.sections)).toEqual([[0, 10.3], [10.3, 30]]);+ expect(result.beatAligned).toEqual([true, true]);+ });++ it('refuses a snap that would push a section below the minimum scene length', () => {+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 10.3 }, { startSec: 10.3, endSec: 30 }],+ { beats, downbeats, minSceneSec: 20 },+ );+ expect(spans(result.sections)).toEqual([[0, 10.3], [10.3, 30]]);+ expect(result.beatAligned).toEqual([false, false]);+ });++ it('never moves the first start or the final end, and keeps the timeline contiguous', () => {+ const result = snapSectionsToGrid(+ [+ { startSec: 0, endSec: 9.4 },+ { startSec: 9.4, endSec: 20.1 },+ { startSec: 20.1, endSec: 29.3 },+ ],+ { beats, downbeats },+ );+ const out = result.sections;+ expect(out[0].startSec).toBe(0);+ expect(out[out.length - 1].endSec).toBe(29.3);+ for (let i = 1; i < out.length; i++) expect(out[i].startSec).toBe(out[i - 1].endSec);+ for (const s of out) expect(s.endSec).toBeGreaterThan(s.startSec);+ });++ it('preserves non-span section fields and does not mutate the input', () => {+ const sections = [{ label: 'Intro', energy: 0.2, startSec: 0, endSec: 10.3 }, { label: 'Drop', energy: 1, startSec: 10.3, endSec: 30 }];+ const result = snapSectionsToGrid(sections, { beats, downbeats });+ expect(sections[0].endSec).toBe(10.3);+ expect(result.sections[0]).toMatchObject({ label: 'Intro', energy: 0.2 });+ expect(result.sections[1]).toMatchObject({ label: 'Drop', energy: 1 });+ });++ it('leaves a single section untouched — both its edges are track anchors', () => {+ const result = snapSectionsToGrid([{ startSec: 0, endSec: 30.4 }], { beats, downbeats });+ expect(spans(result.sections)).toEqual([[0, 30.4]]);+ expect(result.beatAligned).toEqual([true]);+ });++ it('returns empty for an empty or non-array section list', () => {+ expect(snapSectionsToGrid([], { beats, downbeats })).toEqual({ sections: [], beatAligned: [] });+ expect(snapSectionsToGrid(null, { beats, downbeats })).toEqual({ sections: [], beatAligned: [] });+ });++ it('leaves a non-contiguous boundary alone rather than inventing a shared edge', () => {+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 10.3 }, { startSec: 14.3, endSec: 30 }],+ { beats, downbeats },+ );+ expect(spans(result.sections)).toEqual([[0, 10.3], [14.3, 30]]);+ expect(result.beatAligned).toEqual([false, false]);+ });++ it('derives its tolerance from the tempo, so a slow grid may move an edge further than a fast one', () => {+ const gridAt = (bpm) => {+ const out = [];+ for (let t = 0; t <= 40; t += 60 / bpm) out.push(Number(t.toFixed(3)));+ return out;+ };+ // The furthest a full grid can ever move an edge is half a beat period, so+ // sweeping candidate edges across a beat exposes the tempo-relative bound:+ // ~0.43s at 70 BPM vs ~0.17s at 180 BPM. A fixed constant would give both+ // grids the same ceiling.+ const worstMove = (beats) => {+ let worst = 0;+ for (let edge = 9; edge <= 11; edge = Number((edge + 0.01).toFixed(2))) {+ const { sections } = snapSectionsToGrid(+ [{ startSec: 0, endSec: edge }, { startSec: edge, endSec: 30 }], { beats, downbeats: [] },+ );+ worst = Math.max(worst, Math.abs(sections[0].endSec - edge));+ }+ return worst;+ };+ expect(worstMove(gridAt(70))).toBeGreaterThan(worstMove(gridAt(180)) + 0.2);+ });++ it('never collapses or inverts a boundary, even with minSceneSec: 0', () => {+ // Two adjacent boundaries whose nearest beat is the SAME 10.5s point: the+ // section between them must survive rather than being snapped to zero width.+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 10.3 }, { startSec: 10.3, endSec: 10.4 }, { startSec: 10.4, endSec: 30 }],+ { beats, downbeats, minSceneSec: 0 },+ );+ const out = result.sections;+ for (let i = 1; i < out.length; i++) expect(out[i].startSec).toBe(out[i - 1].endSec);+ for (const s of out) expect(s.endSec).toBeGreaterThan(s.startSec);+ });++ it('snaps a downbeats-only grid (no beats) using the implied 4/4 beat period', () => {+ const result = snapSectionsToGrid(+ [{ startSec: 0, endSec: 18.2 }, { startSec: 18.2, endSec: 30 }],+ { beats: [], downbeats },+ );+ expect(spans(result.sections)).toEqual([[0, 18], [18, 30]]);+ expect(result.beatAligned).toEqual([true, true]);+ });+});diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex 15dbd7ef01..44f50d478b 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -12,7 +12,9 @@* already derives section boundaries from energy-novelty segmentation, so a* loud/eventful stretch of the track is already split into more, shorter* sections and a calm stretch into fewer, longer ones — each proposed scene- * simply takes its section's exact span.+ * takes its section's span, with the internal cuts snapped onto the analyzed+ * beat grid first (`snapSectionsToGrid`, #4664) so the seeded spans cut on+ * the music rather than on energy-window edges.** Director-first (#1760's core design constraint): this only SEEDS the* board with ordinary, fully-editable scene records — it never locks or@@ -29,6 +31,7 @@import { ServerError } from '../../lib/errorHandler.js';import { extractJson } from '../../lib/jsonExtract.js';import { resolveProviderAndModel, runPromptThroughProvider } from '../../lib/promptRunner.js';+import { snapSectionsToGrid } from './audioAnalysis.js';import { getProject, addProjectScenes } from './projects.js';const SECTION_LABEL_MAX = 120;@@ -65,16 +68,33 @@ export function validSections(sections) {* order. `sections` must already be filtered via `validSections` — the* caller owns that so this stays a straight 1:1 map (no index drift between* this and the LLM prompt's section list).+ *+ * Section edges come out of energy-novelty segmentation on half-second window+ * boundaries — they have never touched the beat grid. So before seeding, snap+ * the internal boundaries onto the analysis's downbeats/beats and take+ * `beatAligned` from whether each scene's own edges actually landed there+ * (#4664). Stamping `beatAligned: true` unconditionally, as this used to,+ * told `render.js#beatSnapClips` to honor an arbitrary window edge exactly+ * and suppressed the live snap that would otherwise have corrected it.+ *+ * An edge that cannot snap reports `beatAligned: false`, handing that span back+ * to the live snap. A track with NO grid at all keeps its planned spans honored+ * — there is no live snap to hand them to, and dropping them would render every+ * scene at its raw source-clip length; see `snapSectionsToGrid`.+ *+ * @param {Array<object>} sections+ * @param {{ downbeats?: number[], beats?: number[], toleranceSec?: number, minSceneSec?: number }} [grid]*/-export function planScenesFromSections(sections) {- return sections.map((s) => {+export function planScenesFromSections(sections, grid = {}) {+ const { sections: snapped, beatAligned } = snapSectionsToGrid(sections, grid);+ return snapped.map((s, i) => {const label = typeof s.label === 'string' ? s.label.slice(0, SECTION_LABEL_MAX) : '';return {label,sectionLabel: label || null,startSec: s.startSec,endSec: s.endSec,- beatAligned: true,+ beatAligned: beatAligned[i],};});}@@ -207,7 +227,13 @@ export async function planProject(id, { seedPrompts = true, providerId, model });}- const sceneInputs = planScenesFromSections(sections);+ // `buildScenePlanPrompt` below keeps listing the PRE-snap `sections`:+ // indices still agree 1:1 with `sceneInputs`, and a sub-beat difference in a+ // section's reported duration does not change the creative direction asked for.+ const sceneInputs = planScenesFromSections(sections, {+ downbeats: project.audioAnalysis?.downbeats,+ beats: project.audioAnalysis?.beats,+ });let promptsSeeded = false;let promptsSkippedReason = seedPrompts ? null : 'not-requested';diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.jsindex 004fd08a60..18b4f7d3c9 100644--- a/server/services/musicVideo/planner.test.js+++ b/server/services/musicVideo/planner.test.js@@ -25,12 +25,18 @@ const SECTIONS = [{ label: 'Outro', startSec: 18, endSec: 30, energy: 0.4 },];+// 120 BPM: a beat every 0.5s, a 4/4 downbeat every 2s. Both SECTIONS+// boundaries (10s, 18s) already sit on a downbeat, so the fixture plans+// unchanged spans that legitimately earn `beatAligned`.+const BEATS = Array.from({ length: 81 }, (_, i) => Number((i * 0.5).toFixed(3)));+const DOWNBEATS = BEATS.filter((_, i) => i % 4 === 0);+function makeProject(overrides = {}) {return {id: 'mv-1',name: 'Neon Nights',concept: { prompt: 'cyberpunk chase', style: 'neon, rain-slicked streets' },- audioAnalysis: { bpm: 120, beats: [], downbeats: [], sections: SECTIONS, durationSec: 30 },+ audioAnalysis: { bpm: 120, beats: BEATS, downbeats: DOWNBEATS, sections: SECTIONS, durationSec: 30 },scenes: [],...overrides,};@@ -61,8 +67,10 @@ describe('validSections', () => {});describe('planScenesFromSections', () => {- it('builds one beat-aligned scene-create input per section, in order', () => {- const inputs = planScenesFromSections(SECTIONS);+ const GRID = { beats: BEATS, downbeats: DOWNBEATS };++ it('builds one scene-create input per section, in order', () => {+ const inputs = planScenesFromSections(SECTIONS, GRID);expect(inputs).toHaveLength(3);expect(inputs[0]).toEqual({label: 'Intro', sectionLabel: 'Intro', startSec: 0, endSec: 10, beatAligned: true,@@ -71,15 +79,57 @@ describe('planScenesFromSections', () => {expect(inputs[2]).toMatchObject({ label: 'Outro', startSec: 18, endSec: 30 });});- it('each scene duration is exactly its section span (energy-aware via segmentation)', () => {- const inputs = planScenesFromSections(SECTIONS);+ it('each scene duration is its (snapped) section span — energy-aware via segmentation', () => {+ const inputs = planScenesFromSections(SECTIONS, GRID);for (let i = 0; i < SECTIONS.length; i++) {expect(inputs[i].endSec - inputs[i].startSec).toBe(SECTIONS[i].endSec - SECTIONS[i].startSec);}});+ it('snaps off-grid section boundaries onto the beat grid, keeping the timeline contiguous', () => {+ // Energy-novelty segmentation cuts on 0.5s window edges, so a real analysis+ // routinely lands a boundary off the beat — 10.3s here snaps to the 10.5s+ // beat (the 10.0s downbeat is outside the tempo-derived tolerance).+ const inputs = planScenesFromSections([+ { label: 'A', startSec: 0, endSec: 10.3 },+ { label: 'B', startSec: 10.3, endSec: 18.2 },+ { label: 'C', startSec: 18.2, endSec: 30 },+ ], GRID);+ expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.5], [10.5, 18], [18, 30]]);+ expect(inputs.every((i) => i.beatAligned)).toBe(true);+ });++ it('reports beatAligned:false on a scene whose edge could not snap', () => {+ // Nothing snapped, so the flag must not claim otherwise — render.js's+ // beatSnapClips then does its own live snapping instead of freezing the span.+ const inputs = planScenesFromSections([+ { label: 'A', startSec: 0, endSec: 10.3 },+ { label: 'B', startSec: 10.3, endSec: 30 },+ ], { ...GRID, toleranceSec: 0.05 });+ expect(inputs.every((i) => i.beatAligned === false)).toBe(true);+ expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.3], [10.3, 30]]);+ });++ it('keeps the planned spans honored when the track has no usable tempo', () => {+ // No grid means no live snap to hand the span back to, so dropping the flag+ // would leave the render at each clip's raw source duration instead of the+ // planned section span — the plan would be silently discarded.+ const inputs = planScenesFromSections(SECTIONS, { beats: [], downbeats: [] });+ expect(inputs.every((i) => i.beatAligned === true)).toBe(true);+ expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10], [10, 18], [18, 30]]);+ });++ it('refuses a snap that would push a scene below the minimum scene length', () => {+ const inputs = planScenesFromSections([+ { label: 'A', startSec: 0, endSec: 10.3 },+ { label: 'B', startSec: 10.3, endSec: 30 },+ ], { ...GRID, minSceneSec: 25 });+ expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.3], [10.3, 30]]);+ expect(inputs.every((i) => i.beatAligned === false)).toBe(true);+ });+it('falls back to an empty/null label when a section has no label', () => {- const [input] = planScenesFromSections([{ startSec: 0, endSec: 5 }]);+ const [input] = planScenesFromSections([{ startSec: 0, endSec: 5 }], GRID);expect(input.label).toBe('');expect(input.sectionLabel).toBeNull();});@@ -267,4 +317,39 @@ Here is my answer:expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('toolkit not initialized'));warnSpy.mockRestore();});++ it('threads the cached beat grid into the snap, so seeded spans cut on the music', async () => {+ getProject.mockResolvedValue(makeProject({+ audioAnalysis: {+ bpm: 120,+ beats: BEATS,+ downbeats: DOWNBEATS,+ durationSec: 30,+ sections: [+ { label: 'A', startSec: 0, endSec: 10.3, energy: 0.2 },+ { label: 'B', startSec: 10.3, endSec: 30, energy: 0.9 },+ ],+ },+ }));+ addProjectScenes.mockResolvedValue(freshProjectResult());++ await planProject('mv-1', { seedPrompts: false });++ const seededInputs = addProjectScenes.mock.calls[0][1];+ expect(seededInputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.5], [10.5, 30]]);+ expect(seededInputs.every((i) => i.beatAligned)).toBe(true);+ });++ it('still honors the planned spans when the cached analysis has no beat grid', async () => {+ getProject.mockResolvedValue(makeProject({+ audioAnalysis: { bpm: null, beats: [], downbeats: [], sections: SECTIONS, durationSec: 30 },+ }));+ addProjectScenes.mockResolvedValue(freshProjectResult());++ await planProject('mv-1', { seedPrompts: false });++ const seededInputs = addProjectScenes.mock.calls[0][1];+ expect(seededInputs.every((i) => i.beatAligned === true)).toBe(true);+ expect(seededInputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10], [10, 18], [18, 30]]);+ });});