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: refuse to render a performance take against a re-timed scene or replaced song (#8977)

[._.]/ Adam Eivy649848bc8cfb
diff --git a/server/lib/README.md b/server/lib/README.md
index 83e4f66df3..68c85398a3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -298,7 +298,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
-| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–14.8s), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`. Dependency-free; the client re-exports it. |
+| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–14.8s), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`. Dependency-free; the client re-exports it. |
| `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. |
| `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.js
index c5d3ff27cb..438dd31dec 100644
--- a/server/lib/musicVideoShotTiming.js
+++ b/server/lib/musicVideoShotTiming.js
@@ -35,6 +35,21 @@ export const MUSIC_VIDEO_SHOT_MODES = Object.freeze(['cutaway', 'performance']);
/** A scene with no `shotMode` (every pre-#8977 record) is a cutaway. */
export const isPerformanceScene = (scene) => scene?.shotMode === 'performance';
+/**
+ * The shot instruction of a performance scene's SELECTED video take, or null —
+ * for a cutaway scene (even one whose selected take was once generated as a
+ * performance), or a take with no usable edit points.
+ */
+export function selectedPerformanceInstruction(scene) {
+ if (!isPerformanceScene(scene) || !scene.videoHistoryId) return null;
+ const take = (Array.isArray(scene.takes) ? scene.takes : [])
+ .find((t) => t?.kind === 'video' && t.assetId === scene.videoHistoryId);
+ const instruction = take?.shotInstruction;
+ const edit = instruction?.edit;
+ if (instruction?.shotMode !== 'performance' || !Number.isFinite(edit?.inSec) || !Number.isFinite(edit?.outSec)) return null;
+ return edit.inSec >= 0 && edit.outSec > edit.inSec ? instruction : null;
+}
+
// Safety margin kept inside the provider's documented bounds so ffmpeg's
// sample rounding can never land a window a hair under the minimum (rejected)
// or over the maximum (silently clipped by the provider).
diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.js
index 5e0dd4f2d6..6de95b04ad 100644
--- a/server/services/musicVideo/performanceShot.js
+++ b/server/services/musicVideo/performanceShot.js
@@ -39,6 +39,7 @@ import {
performanceBlockedReason,
performanceCapability,
planPerformanceWindow,
+ selectedPerformanceInstruction,
} from '../../lib/musicVideoShotTiming.js';
import { getProject } from './projects.js';
@@ -78,6 +79,32 @@ async function sliceAudioWindow(sourcePath, outPath, { startSec, endSec }) {
const refuse = (message, code, status = 400) => new ServerError(message, { status, code });
+// Recorded vs current scene times agree within a millisecond.
+const SAME_TIME_SEC = 0.001;
+
+/**
+ * Performance scenes whose SELECTED take was generated against a different song
+ * interval (the scene was re-timed) or a different recording (the song was
+ * replaced). Returns `[{ sceneId, reason: 'retimed' | 'audio-changed' }]`;
+ * the master is hashed only when there is a performance take to check.
+ */
+export async function findStalePerformanceTakes(project, masterPath) {
+ const selected = (Array.isArray(project?.scenes) ? project.scenes : [])
+ .map((scene) => ({ scene, instruction: selectedPerformanceInstruction(scene) }))
+ .filter(({ instruction }) => instruction);
+ if (selected.length === 0) return [];
+ const sha256 = await hashFile(masterPath);
+ const stale = [];
+ for (const { scene, instruction } of selected) {
+ const interval = instruction.songInterval || {};
+ if (instruction.audio?.sha256 !== sha256) stale.push({ sceneId: scene.sceneId, reason: 'audio-changed' });
+ else if (!(Math.abs(interval.startSec - scene.startSec) <= SAME_TIME_SEC && Math.abs(interval.endSec - scene.endSec) <= SAME_TIME_SEC)) {
+ stale.push({ sceneId: scene.sceneId, reason: 'retimed' });
+ }
+ }
+ return stale;
+}
+
/**
* Prepare a Music Video scene render's performance inputs.
*
diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.js
index 81cc2b6138..a4df9dd398 100644
--- a/server/services/musicVideo/performanceShot.test.js
+++ b/server/services/musicVideo/performanceShot.test.js
@@ -27,7 +27,7 @@ vi.mock('../videoGen/local.js', async () => {
const { PATHS } = await import('../../lib/fileUtils.js');
const { findFfmpeg, probeVideoStreamInfo } = await import('../../lib/ffmpeg.js');
-const { preparePerformanceShot } = await import('./performanceShot.js');
+const { preparePerformanceShot, findStalePerformanceTakes } = await import('./performanceShot.js');
const fal = await import('../videoGen/fal.js');
const { videoGenEvents } = await import('../videoGen/events.js');
const { buildMusicVideoFfmpegArgs, beatSnapClips, resolveSceneClips } = await import('./render.js');
@@ -172,6 +172,22 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync
]).toString().trim());
expect(out.fps).toBe(24);
expect(Math.abs(frames - 36)).toBeLessThanOrEqual(1);
+
+ // The take is only valid for the interval and recording it sang: a
+ // re-timed scene or a replaced song must be regenerated, not rendered.
+ const songPath = join(PATHS.music, 'song.wav');
+ expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath)).toEqual([]);
+ expect(await findStalePerformanceTakes({ scenes: [{ ...withTake, endSec: 22 }] }, songPath))
+ .toEqual([{ sceneId: 'mvs-1', reason: 'retimed' }]);
+ const replaced = songWav();
+ replaced.writeInt16LE(1000, 44 + 2);
+ await writeFile(songPath, replaced);
+ expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath))
+ .toEqual([{ sceneId: 'mvs-1', reason: 'audio-changed' }]);
+ // Switched back to a cutaway, the old take is an ordinary clip again.
+ expect(await findStalePerformanceTakes({ scenes: [{ ...withTake, shotMode: 'cutaway' }] }, songPath)).toEqual([]);
+ const [asCutaway] = await resolveSceneClips({ scenes: [{ ...withTake, shotMode: 'cutaway' }] });
+ expect(asCutaway).toMatchObject({ inSec: 0 });
}, 60_000);
it('uses the full span of a long shot and stays under the provider maximum', async () => {
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 4b070275e0..c7157bede2 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -38,6 +38,8 @@ import { getProject, listProjects, updateProject } from './projects.js';
import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
import { renderableCues, sectionCardCues } from './composition.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';
+import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
+import { findStalePerformanceTakes } from './performanceShot.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).
@@ -74,14 +76,7 @@ const round3 = (n) => Math.round(n * 1000) / 1000;
// generated with — its footage starts `edit.inSec` into the clip (the audio
// window was padded to the provider minimum) and ends at `edit.outSec`. It
// never loops: repeating a sung take would desync the mouth from the song.
-function performanceEdit(scene) {
- const take = (Array.isArray(scene.takes) ? scene.takes : [])
- .find((t) => t?.kind === 'video' && t.assetId === scene.videoHistoryId);
- const instruction = take?.shotInstruction;
- const edit = instruction?.edit;
- if (instruction?.shotMode !== 'performance' || !Number.isFinite(edit?.inSec) || !Number.isFinite(edit?.outSec)) return null;
- return edit.outSec > edit.inSec && edit.inSec >= 0 ? edit : null;
-}
+const performanceEdit = (scene) => selectedPerformanceInstruction(scene)?.edit ?? null;
// A non-looping shot may run this much past its source clip; the gap holds the
// final frame (tpad) rather than repeating footage. Longer shortfalls block the
@@ -472,6 +467,16 @@ export async function renderMusicVideo(projectId) {
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
const audioPath = await resolveMasterAudioPath(project);
+ // #8977: a performance take sings one stretch of one recording. If the
+ // scene was re-timed or the song replaced since, its mouth motion no longer
+ // matches the audio under it — refuse rather than render it out of sync.
+ const stale = await findStalePerformanceTakes(project, audioPath);
+ if (stale.length > 0) {
+ throw new ServerError(
+ `${stale.length} performance shot${stale.length === 1 ? ' was' : 's were'} generated against a different song interval or recording — regenerate ${stale.length === 1 ? 'it' : 'them'}, or switch to Cutaway, before rendering`,
+ { status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale } },
+ );
+ }
// #8985: a composed render cuts still and card sections into the same
// timebase as the footage; plain concat renders footage only, as before.
const composed = project.composition?.mode === 'composed';