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
refactor: give music-video services one load-project-or-404 guard
Adam Eivy0fe30ac1385d
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex cd2ddf8628..060969876b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -129,6 +129,7 @@ import {swapProjectSceneFrames,refreshSongStyleFromSuno,} from '../services/musicVideo/projects.js';+import { requireProject } from '../services/musicVideo/requireProject.js';import { buildHandoffManifest, buildHandoffBundle, matchSceneByFileTag } from '../services/musicVideo/handoff.js';import { getHistoryItem } from '../services/videoGen/history.js';import {@@ -297,8 +298,7 @@ router.get('/midi-sources', asyncHandler(async (req, res) => {}));router.get('/:id', asyncHandler(async (req, res) => {- const p = await getProject(req.params.id);- if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const p = await requireProject(req.params.id);// Transient (never persisted): lets a reloaded page reattach to a running publishing-kit build.const activePublishKitBuild = getActivePublishKitBuild(p.id);const presented = presentProjectForRead(p);@@ -448,8 +448,7 @@ router.post('/:id/analyze', asyncHandler(async (req, res) => {// falls back to decoding when no usable prior analysis exists.router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {const { bpm, offsetSec } = validateRequest(musicVideoManualAnalysisSchema, req.body);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const cached = project.audioAnalysis;const analysis = cached && Array.isArray(cached.sections) && typeof cached.durationSec === 'number'? buildManualAnalysisFromCached(cached, { bpm, offsetSec })@@ -516,8 +515,7 @@ router.post('/:id/treatment/proofs/:proofId/review', asyncHandler(async (req, re// markers anchored to the imported lines (lyricMarkers.js).router.post('/:id/lyrics/import', asyncHandler(async (req, res) => {const { format = 'auto', text, mode = 'replace' } = validateRequest(musicVideoLyricsImportSchema, req.body);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { format: detected, cues, markers } = parseLyricCues(text, format);if (cues.length === 0) {throw new ServerError(`No lyric lines found in the ${detected} text`, { status: 422, code: 'NO_LYRICS' });@@ -615,8 +613,7 @@ router.get('/:id/active-jobs', asyncHandler(async (req, res) => {// includes it for the client to merge.router.post('/:id/transcribe-midi', asyncHandler(async (req, res) => {const { model } = validateRequest(musicVideoTranscribeMidiRequestSchema, req.body || {});- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const audioPath = await resolveProjectAudioPath(project);const projectId = project.id;// Audio-source identity at kickoff — the completion callback re-checks it so@@ -866,8 +863,7 @@ router.post('/render/:jobId/cancel', (req, res) => {// section functions and never call a provider. Generate / regenerate are the// only provider calls, and both require this click.router.get('/:id/code/document', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);if (project.composition?.mode !== 'code') {throw new ServerError('Switch the render style to Code-rendered first', { status: 409, code: 'NOT_CODE_MODE' });}@@ -889,12 +885,6 @@ router.post('/:id/code/sections/:sectionId/regenerate', asyncHandler(async (req,// compositionDocument.js): import a zip, a folder inside data/, or the shipped// template; export it; read its manifest; preview it. Files stay on this// install; the record keeps a pointer to the current immutable version.-const requireProject = async (id) => {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-};-// A new document gets its overlay text checked in the background, so the// findings are waiting at the storyboard approval (local browser work, no provider).const checkOverlayTextAfterImport = (projectId) => {@@ -1656,8 +1646,7 @@ router.post('/:id/scenes/:sceneId/continue-from-previous', asyncHandler(async (r// Every still and clip generated for this video, each naming the shots using it now (the shot card's Swap picker).router.get('/:id/media-pool', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { getMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');res.json(await getMusicVideoMediaPool(project));}));@@ -1665,16 +1654,14 @@ router.get('/:id/media-pool', asyncHandler(async (req, res) => {// Swap's search: the pool items whose prompts (the shot's text and the prompt each file was made from) hold the words.router.get('/:id/media-pool/search', asyncHandler(async (req, res) => {const { q } = validateRequest(musicVideoPoolSearchQuerySchema, req.query);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { searchMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');res.json({ items: await searchMusicVideoMediaPool(project, q) });}));// The cutting room floor outro's tally: what was made, kept and turned down for this video.router.get('/:id/stats-outro', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { getMusicVideoOutroStats } = await import('../services/musicVideo/statsOutro.js');res.json({ stats: await getMusicVideoOutroStats(project) });}));@@ -1699,16 +1686,14 @@ router.post('/:id/media-pool/import', asyncHandler(async (req, res) => {// Media made for this video but never filed: search the whole library by prompt, then add picks.router.get('/:id/media-pool/library', asyncHandler(async (req, res) => {const { q } = validateRequest(musicVideoLibrarySearchQuerySchema, req.query);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { searchMediaLibraryForPool } = await import('../services/musicVideo/mediaPool.js');res.json(await searchMediaLibraryForPool(project, q));}));router.post('/:id/media-pool/add', asyncHandler(async (req, res) => {const { items } = validateRequest(musicVideoPoolAddSchema, req.body);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { addLibraryMediaToPool, getMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');const result = await addLibraryMediaToPool(project, items);res.json({ ...result, items: (await getMusicVideoMediaPool(project)).items });@@ -1716,8 +1701,7 @@ router.post('/:id/media-pool/add', asyncHandler(async (req, res) => {router.post('/:id/media-pool/delete', asyncHandler(async (req, res) => {const { items } = validateRequest(musicVideoPoolDeleteSchema, req.body);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { deleteMusicVideoPoolAssets } = await import('../services/musicVideo/mediaPool.js');res.json(await deleteMusicVideoPoolAssets(project, items));}));@@ -1757,8 +1741,7 @@ router.patch('/:id/scenes/:sceneId/takes/:takeId', asyncHandler(async (req, res)// (e.g. Midjourney), and import what the director generated there. Nothing// here contacts the external service.router.get('/:id/handoff', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);res.json(buildHandoffManifest(project));}));@@ -1766,8 +1749,7 @@ router.get('/:id/handoff', asyncHandler(async (req, res) => {// image and each scene's selected frame, so nothing has to be saved out of// the gallery by hand before attaching it in the external tool.router.get('/:id/handoff/bundle', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const { zip } = await buildHandoffBundle(project);res.set('Content-Type', 'application/zip');res.set('Content-Disposition', `attachment; filename="music-video-${project.id}-handoff.zip"`);@@ -1781,8 +1763,7 @@ router.get('/:id/handoff/bundle', asyncHandler(async (req, res) => {// record write with `imported` source + provider provenance.router.post('/:id/handoff/import', asyncHandler(async (req, res) => {const { provider, items } = validateRequest(musicVideoHandoffImportSchema, req.body);- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(req.params.id);const sceneIds = new Set((project.scenes || []).map((scene) => scene.sceneId));const accepted = [];const skipped = [];diff --git a/server/services/musicVideo/audioTiming.js b/server/services/musicVideo/audioTiming.jsindex a4ca6a3f46..f42c5e1ed6 100644--- a/server/services/musicVideo/audioTiming.js+++ b/server/services/musicVideo/audioTiming.js@@ -8,6 +8,7 @@ import { canonicalSnapshotChecksum as checksum } from '../../lib/snapshotChecksuimport { presentMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';import { isPerformanceScene } from '../../lib/musicVideoShotTiming.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { applyProjectPatch } from './projectsLogic.js';const refuse = (message, status = 409) => new ServerError(message, { status, code: 'AUDIO_TIMING_INVALID' });@@ -110,8 +111,7 @@ export async function previewAudioTiming(id, input) {}export async function applyAudioTiming(id, { basis, ...input }) {- const before = await getProject(id);- if (!before) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const before = await requireProject(id);const receipt = (before.audioTimingRevisions || []).find((revision) => revision.basis === basis);if (receipt) {if (checksum(receipt.input) !== checksum(input)) throw refuse('The applied preview belongs to another mapping.');diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.jsindex c40d87a445..e4499fb84c 100644--- a/server/services/musicVideo/autoReviewService.js+++ b/server/services/musicVideo/autoReviewService.js@@ -38,6 +38,7 @@ import { safeChildProcessOptions } from '../../lib/processEnv.js';import { findFfmpeg, findFfprobe, probeVideoStreamInfo, safeUnder } from '../../lib/ffmpeg.js';import { isVisionCapableCliProvider } from '../../lib/localModelHeuristics.js';import { getProject, mutateProjectRecord as mutateRecord } from './projects.js';+import { requireProject } from './requireProject.js';const mutateProjectRecord = (id, transform) => mutateRecord(id, transform, { source: 'auto-review' });import { musicVideoEvents } from './events.js';import { startExcerptRender } from './excerptRender.js';@@ -100,12 +101,6 @@ function findRun(project, runId) {return run;}-async function requireProject(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-function publish(projectId, project, run, action) {musicVideoEvents.emit('auto-review', { projectId, runId: run.id, run, action, project });}diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex 4b957d6cba..e44b795ca1 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -93,6 +93,7 @@ import {} from '../../lib/musicVideoAutonomous.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { getProject, mutateProjectRecord as mutateRecord } from './projects.js';+import { requireProject } from './requireProject.js';// `runId` lets the run's repairs land on shots its own approval locked (preserveAutomatedShotLocks).const mutateProjectRecord = (id, transform, { runId = null } = {}) => mutateRecord(id, transform, { source: 'orchestrator', runId });import { musicVideoEvents } from './events.js';@@ -180,8 +181,7 @@ const projectAutonomousRun = (project) => project?.autonomousRun || null;const ownsRunningRun = (current, run) => current?.id === run.id && current.status === 'running' && current.processId === PROCESS_ID;async function requireRun(projectId) {- const project = await getProject(projectId);- if (!project) throw runError(404, 'NOT_FOUND', 'Project not found');+ const project = await requireProject(projectId);const run = projectAutonomousRun(project);if (!run) throw runError(404, 'NO_AUTONOMOUS_RUN', 'This project has no autonomous run');return { project, run };diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex 41117a67b4..94e9b5bac9 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -37,6 +37,7 @@ import { resolveGalleryImage, resolveImageRef } from '../../lib/pathSafety.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';import { trimTo } from '../../lib/textUtils.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { musicVideoEvents } from './events.js';import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';import {@@ -113,12 +114,6 @@ export const presentProjectCastAndSets = (project) => (project?.castAndSets? { ...project, castAndSets: presentCastAndSets(project.castAndSets, PROCESS_ID) }: project);-async function requireProject(id) {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-function publish(projectId, project) {musicVideoEvents.emit('cast-and-sets', {projectId,diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.jsindex 6772270d58..f01ff947d7 100644--- a/server/services/musicVideo/codeGeneration.js+++ b/server/services/musicVideo/codeGeneration.js@@ -17,6 +17,7 @@ import { buildMusicVideoCodePrompt, extractCodeSections } from '../codeAnimationimport { normalizeComposition } from './composition.js';import { approvedCastAndSetsDirection } from './castAndSets.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { musicVideoLlmRouteLabel } from '../../lib/musicVideoAutomation.js';import { effortArg, resolveMusicVideoLlm } from './llmRoute.js';import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';@@ -128,8 +129,7 @@ async function writeComposition(projectId, run, sections, timelineIds, authoring* model returned; a section it omitted keeps its previous function.*/export async function generateMusicVideoCode(projectId, { providerId, model, effort } = {}) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);assertProductionApproval(project, 'storyboard');const timeline = buildCodeTimeline(project);if (!timeline.sections.length) {@@ -161,8 +161,7 @@ export async function generateMusicVideoCode(projectId, { providerId, model, eff/** Replace one section function. Every other stored function stays. */export async function regenerateMusicVideoCodeSection(projectId, sectionId, { providerId, model, effort } = {}) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);assertProductionApproval(project, 'storyboard');const timeline = buildCodeTimeline(project);if (!timeline.sections.some((section) => section.id === sectionId)) {diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.jsindex 99f4c3a86e..51941fda81 100644--- a/server/services/musicVideo/compositionDocument.js+++ b/server/services/musicVideo/compositionDocument.js@@ -34,7 +34,8 @@ import { isPathInsideDir } from '../../lib/pathSafety.js';import { readZipArchive, unsafeZipEntryName } from '../../lib/zipArchive.js';import { createZip } from '../../lib/zipWriter.js';import { MUSIC_VIDEO_DOCUMENT_DIRECTORY, MUSIC_VIDEO_DOCUMENT_TEMPLATES } from '../../lib/musicVideoValidation.js';-import { getProject, listProjects, mutateProjectRecord } from './projects.js';+import { listProjects, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { normalizeComposition } from './composition.js';// The composition browser snapshots at most 256 MiB / 4096 files per render,@@ -232,9 +233,8 @@ async function storeVersionNow(projectId, inputFiles, source, { draft = false, vif (files.length > DOCUMENT_MAX_FILES || totalBytes > DOCUMENT_MAX_BYTES) {throw refuse('Shared document assets exceed the document file or byte limit', 'COMPOSITION_DOCUMENT_TOO_LARGE', 413);}- const initial = await getProject(projectId);+ const initial = await requireProject(projectId);await assertDocumentMediaPolicy(initial, files);- if (!initial) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });const versionId = `doc-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;const root = projectDocumentRoot(projectId);const staging = join(root, `.${versionId}.partial`);@@ -463,13 +463,12 @@ const engineDigest = bytes => createHash('sha256').update(bytes.toString('utf8')export function upgradeDocumentEngine(projectId, directory) {assertProjectId(projectId);return serializeProject(projectId, async () => {- const project = await getProject(projectId);+ const project = await requireProject(projectId);const verifyCurrent = current => {if (current.composition?.mode !== 'document' || current.composition?.document?.directory !== directory || current.composition?.documentDraft) {throw refuse('The selected document changed or has a pending candidate — finish it before upgrading', 'COMPOSITION_DRAFT_STALE', 409);}};- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });verifyCurrent(project);const dir = await requireDocument(project);const { files } = await collectTree(dir);diff --git a/server/services/musicVideo/continueShot.js b/server/services/musicVideo/continueShot.jsindex cb1fe07a80..6fe33bbc99 100644--- a/server/services/musicVideo/continueShot.js+++ b/server/services/musicVideo/continueShot.js@@ -20,7 +20,8 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { findFfmpeg, probeVideoGeometry, runFfmpegProcess, safeUnder } from '../../lib/ffmpeg.js';import { previousShot, sceneClipOutFrameSec, shotHandoffSource } from '../../lib/musicVideoHandoffFrame.js';import { getHistoryItem } from '../videoGen/history.js';-import { appendSceneTakes, getProject, selectSceneTake } from './projects.js';+import { appendSceneTakes, selectSceneTake } from './projects.js';+import { requireProject } from './requireProject.js';import { assertClipUnlocked } from './productionReview.js';const refuse = (message, code, status = 409) => new ServerError(message, { status, code });@@ -30,8 +31,7 @@ const refuse = (message, code, status = 409) => new ServerError(message, { statu* start frame. Returns `{ scene, frame: { imageId, atSec, fromSceneId } }`.*/export async function continueFromPreviousShot(projectId, sceneId, { keepStillAsEnd = false } = {}) {- const project = await getProject(projectId);- if (!project) throw refuse('Project not found', 'NOT_FOUND', 404);+ const project = await requireProject(projectId);const scene = project.scenes?.find((s) => s.sceneId === sceneId);if (!scene) throw refuse('Scene not found', 'NOT_FOUND', 404);assertClipUnlocked(project, sceneId);diff --git a/server/services/musicVideo/coverArt.js b/server/services/musicVideo/coverArt.jsindex 3dad7ce72c..6eb867c2e2 100644--- a/server/services/musicVideo/coverArt.js+++ b/server/services/musicVideo/coverArt.js@@ -32,6 +32,7 @@ import { listCoverFonts, registerCoverFonts } from './coverFonts.js';import { buildCoverDesignPrompt, parseCoverDesign } from './coverArtDesign.js';import { musicVideoEvents } from './events.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { projectPublishKit, releaseKitFiles } from './publishKit.js';const MAX_GENERATED = 12;@@ -78,12 +79,6 @@ export const projectCoverArt = (project) => {return art && typeof art === 'object' ? art : {};};-async function requireProject(projectId) {- const project = await getProject(projectId);- if (!project) throw coverError(404, 'NOT_FOUND', 'Project not found');- return project;-}-function publish(projectId, project) {musicVideoEvents.emit('cover-art', { projectId, project });}diff --git a/server/services/musicVideo/devArtifactService.js b/server/services/musicVideo/devArtifactService.jsindex 45d6f98f76..709d3aefe2 100644--- a/server/services/musicVideo/devArtifactService.js+++ b/server/services/musicVideo/devArtifactService.js@@ -16,7 +16,8 @@ import { extname } from 'path';import { unlink } from 'fs/promises';import { ServerError } from '../../lib/errorHandler.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';-import { getProject, mutateProjectRecord } from './projects.js';+import { mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { musicVideoEvents } from './events.js';import {addDevArtifactNote,@@ -33,12 +34,6 @@ import {} from './devArtifacts.js';import { discardDevArtifactFile, resolveDevArtifactFile, writeDevArtifactFile } from './devArtifactStore.js';-async function requireProject(id) {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-/** Artifact kinds that show rendered output rather than planning imagery. */export const DEV_ARTIFACT_EVIDENCE_KINDS = new Set(['storyboard', 'animatic']);diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.jsindex 2ed5f6b991..d7bebf7a10 100644--- a/server/services/musicVideo/documentGeneration.js+++ b/server/services/musicVideo/documentGeneration.js@@ -21,6 +21,7 @@ import { isLocalInstanceEndpoint } from '../../lib/localEndpoint.js';import { castAndSetsCodeContext, runModel, styleLinesFor } from './codeGeneration.js';import { resolveMusicVideoLlm } from './llmRoute.js';import { getProject } from './projects.js';+import { requireProject } from './requireProject.js';import { buildDocumentData, documentAspect, documentRenderClock, documentSongDuration, DOCUMENT_FRAME_SIZES, resolveSceneMedia } from './documentRender.js';import { acceptGeneratedDocument, readDocumentFiles, stageGeneratedDocument } from './compositionDocument.js';@@ -283,8 +284,7 @@ async function priorManifest(project) {}async function runAuthoring(projectId, { providerId, model, effort, sectionId = null, eventRevision = false, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {}, promptBudgetChars = LOCAL_PROMPT_BUDGET_CHARS } = {}) {- const project = await getProject(projectId);- if (!project) throw fail('Project not found', 'NOT_FOUND', 404);+ const project = await requireProject(projectId);assertProductionApproval(project, 'storyboard');const context = await authoringContext(project);let prior = null;@@ -470,8 +470,7 @@ export async function acceptMixedMediaDocument(projectId, directory, { verifyCur}export async function readMixedMediaCandidate(projectId) {- const project = await getProject(projectId);- if (!project) throw fail('Project not found', 'NOT_FOUND', 404);+ const project = await requireProject(projectId);if (!project.composition?.documentDraft && project.composition?.document?.source?.kind !== 'generated') return { candidate: null, source: null, sections: [] };const { pointer, manifest } = await priorManifest(project);const currentSong = buildSongDocument(project);diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex a749ae4194..7c7bd0fa98 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -34,6 +34,7 @@ import { safeUnder } from '../../lib/ffmpeg.js';import { filterGraphViaFile } from '../../lib/ffmpegFilterGraph.js';import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';import { getProject, listProjects, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { assertCurrentPerformanceTakes, withDraftPerformanceFallbacks } from './performanceShot.js';import { assertCurrentClipDependencies, planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath, resolveSoundBedPath } from './render.js';import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';@@ -248,8 +249,7 @@ export async function renderSeekedWindow(stored, { startSec, endSec, aspect, fad}export async function startExcerptRender(projectId, { startSec, endSec, aspect = null, fade = false }, { revisionId = null, pilotSceneId = null, verifyCurrent = null } = {}) {- const stored = await getProject(projectId);- if (!stored) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const stored = await requireProject(projectId);await verifyCurrent?.(stored);const project = pilotSceneId ? productionPilotRenderProject(stored, pilotSceneId) : stored;const pilotEvidence = pilotSceneId ? pilotDependencies(stored, pilotSceneId) : null;diff --git a/server/services/musicVideo/lyricAlignJob.js b/server/services/musicVideo/lyricAlignJob.jsindex 9db70ef6b2..4942383b57 100644--- a/server/services/musicVideo/lyricAlignJob.js+++ b/server/services/musicVideo/lyricAlignJob.js@@ -16,7 +16,7 @@ import { shortId } from '../../lib/fileUtils.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { alignProjectLyrics } from './lyricAlign.js';-import { getProject } from './projects.js';+import { requireProject } from './requireProject.js';const reviewableRevision = (project) => project.songRevision?.status === 'selected' && Boolean(project.songRevision.baseline);const retimeRevisedSongLazy = async (...args) => (await import('./songRevision.js')).retimeRevisedSong(...args);@@ -51,8 +51,7 @@ export async function startLyricAlign(projectId, { cueId = null, separateVocalsconst running = getActiveLyricAlignJobId(projectId);if (running) return { jobId: running, reused: true };// Fail with a real status before a job exists, as the blocking route did.- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const cues = Array.isArray(project.lyricCues) ? project.lyricCues : [];// A revised song re-times as a whole: analysis, alignment and the board (songRevision.js).if (retimeSong && !reviewableRevision(project)) {diff --git a/server/services/musicVideo/mediaPool.js b/server/services/musicVideo/mediaPool.jsindex 1f7a5bda48..8f1d0599c0 100644--- a/server/services/musicVideo/mediaPool.js+++ b/server/services/musicVideo/mediaPool.js@@ -371,14 +371,14 @@ export async function forgetDeletedMusicVideoAssets(keys, { mutateProjectRecord:* the batch on every music video (forgetDeletedMusicVideoAssets).*/export async function deleteMusicVideoPoolAssets(project, items) {- const { withProjectMediaMutation, getProject, listProjects } = await import('./projects.js');+ const { withProjectMediaMutation, listProjects } = await import('./projects.js');+ const { requireProject } = await import('./requireProject.js');const { ServerError } = await import('../../lib/errorHandler.js');const { withBackupAssetPublication } = await import('../../lib/backupSnapshotBoundary.js');// Backup admission precedes the project boundary, matching gallery/history// deletion; one lease covers physical deletion and project cleanup.return withBackupAssetPublication(() => withProjectMediaMutation(async (admitted) => {- const current = await getProject(project.id);- if (!current) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const current = await requireProject(project.id);const pool = new Set((await getMusicVideoMediaPool(current)).items.map((item) => `${item.kind}:${item.assetId}`));// A shot on any music video using it keeps it, not only this video's shots.const usedAnywhere = new Set((await listProjects()).flatMap((other) => [...usedKeys(other)]));diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex fabc9561ce..b24cbfeb95 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -44,6 +44,7 @@ import { runPromptThroughProvider } from '../promptRunner.js';import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';import { directShots, planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { productionFeedbackContext } from './productionReview.js';import { parseShotCamera, planShotCameras, shotCameraPromptSection } from './shotCamera.js';import { getCameraMovement } from '../../lib/cameraMovements.js';@@ -354,8 +355,7 @@ async function tryProposeScenePrompts(project, shots, { providerId, model, effor* keeps it under `automation.routes.plan`.*/export async function planProject(id, { seedPrompts = true, providerId, model, effort, directive, mode = 'append' } = {}) {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(id);const existingCount = (project.scenes || []).length;if (mode === 'require' && existingCount > 0) {throw new ServerError(diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.jsindex 5c8762aa8d..eea91f5902 100644--- a/server/services/musicVideo/productionReviewService.js+++ b/server/services/musicVideo/productionReviewService.js@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { ServerError } from '../../lib/errorHandler.js';-import { getProject, mutateProjectRecord } from './projects.js';+import { mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { musicVideoEvents } from './events.js';import { shotCameraLabel } from '../../lib/cameraMovements.js';import { productionReadiness, boardStoryboard, seedArtDraft, productionReviewBasis, productionAlignmentBasis, documentStoryboardBasis, approveProductionStage, assertProductionApproval, assertShotApproval, assertClipUnlocked, setShotLocks, recordProductionFeedback, resolveProductionFeedback, revertApprovedInput, anchorShotsToSungLyrics, clipLocked, dropStaleStoryboardRows, carryStoryboardApproval } from './productionReview.js';@@ -8,12 +9,6 @@ import { sungLyricTextWithin } from '../../lib/musicVideoLyricAnchors.js';const reviewProcessId = randomUUID();-async function requireProject(id) {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-const present = project => ({ project, readiness: productionReadiness(project) });function changed(project) {// Reuse the existing project-bearing development-artifact notification.diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex fa927dfd26..cb8c439ac1 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -29,6 +29,7 @@ import { ensureSceneTakes, selectSceneTake } from './takes.js';import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord as mutateRecord } from './projects.js';+import { requireProject } from './requireProject.js';const mutateProjectRecord = (id, transform) => mutateRecord(id, transform, { source: 'production-run' });import { musicVideoEvents } from './events.js';import { isFreeProvider } from '../../lib/modelPricing.js';@@ -132,12 +133,6 @@ export async function __settleProductionForTests() {while (background.size) await Promise.allSettled([...background]);}-async function requireProject(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-/** Read the newest record at the queue boundary, after provider preparation. */export async function assertProductionSubmission(projectId, runId, stepKey, input) {const project = await requireProject(projectId);diff --git a/server/services/musicVideo/projectAudio.js b/server/services/musicVideo/projectAudio.jsindex 14f01c0155..dfe6a80efd 100644--- a/server/services/musicVideo/projectAudio.js+++ b/server/services/musicVideo/projectAudio.js@@ -8,7 +8,8 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS } from '../../lib/fileUtils.js';import { safeUnder } from '../../lib/ffmpeg.js';import { getTrack } from '../tracks/index.js';-import { getProject, setProjectAnalysis } from './projects.js';+import { setProjectAnalysis } from './projects.js';+import { requireProject } from './requireProject.js';import { analyzeAudioFile } from './audioAnalysis.js';import { relabelAnalysisSections } from './lyricMarkers.js';@@ -40,8 +41,7 @@ export async function resolveProjectAudioPath(project) {* aligned). Resolves to the updated project.*/export async function analyzeProjectSong(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const analysis = await analyzeAudioFile(await resolveProjectAudioPath(project));if (!analysis) {throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex a1534a6581..033cb5a1b4 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -71,6 +71,7 @@ export async function listProjects(options = {}) {return (await selectBackend()).listProjects(options);}+/** Null when missing; a caller that answers 404 for that uses requireProject.js. */export async function getProject(id, options = {}) {return presentMusicVideoDependencies(await (await selectBackend()).getProject(id, options));}diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex 7d24102c55..6bc3f69d02 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -13,7 +13,8 @@ import { join } from 'path';import { ServerError } from '../../../lib/errorHandler.js';import { PATHS, ensureDir } from '../../../lib/fileUtils.js';import { safeUnder } from '../../../lib/ffmpeg.js';-import { getProject, mutateProjectRecord } from '../projects.js';+import { mutateProjectRecord } from '../projects.js';+import { requireProject } from '../requireProject.js';import { buildPublishPayload, publishPreviewParts, publishSongUrl } from './payloads.js';import { canonicalizeSunoUrl, isSunoShareLink } from '../../sunoShareLink.js';import { connectPortosBrowser, serializeBrowserOperation as serialize } from './browser.js';@@ -222,8 +223,7 @@ export async function preparePublishDraft(projectId, target, options = {}, depsif (!adapter) throw new ServerError(`Unknown publish target: ${target}`, { status: 400, code: 'VALIDATION_ERROR' });const platforms = deps.platforms || await getPublishPlatforms();assertPlatformEnabled(platforms, target);- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);// A platform already posted to gets a second draft only when the director says so:// otherwise one stray click is one duplicate post.const existing = project.publishKit?.posts?.[target];@@ -272,8 +272,7 @@ export async function preparePublishDraft(projectId, target, options = {}, deps*/export async function previewPublishPost(projectId, target, options = {}, deps = {}) {if (!(deps.adapters || PUBLISH_ADAPTERS)[target]) throw new ServerError(`Unknown publish target: ${target}`, { status: 400, code: 'VALIDATION_ERROR' });- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const platforms = deps.platforms || await getPublishPlatforms();return withSongPage(target, project, withPlatformDefaults(target, options, platforms), deps).then((resolved) => buildPublishPayload(target, project, resolved))@@ -346,8 +345,7 @@ export async function setPublishCrossLinks(projectId, enabled) {export async function prepareCrossLinkEdit(projectId, target, deps = {}) {const adapter = (deps.crossLinkAdapters || CROSS_LINK_ADAPTERS)[target];if (!adapter) throw new ServerError(`No cross-link edit for ${target}`, { status: 400, code: 'VALIDATION_ERROR' });- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const row = crossLinkBackfill(project.publishKit).find((r) => r.target === target);if (!row) throw new ServerError(`Record the ${adapter.label} post's link first`, { status: 422, code: 'PUBLISH_ASSET_MISSING' });if (!row.missing.length) throw new ServerError(`The ${adapter.label} post already links every other post`, { status: 409, code: 'PUBLISH_CROSS_LINKS_CURRENT' });diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.jsindex 0e8d4f0cf7..c908a3376f 100644--- a/server/services/musicVideo/publishKit.js+++ b/server/services/musicVideo/publishKit.js@@ -22,7 +22,8 @@ import { ServerError } from '../../lib/errorHandler.js';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { safeUnder, edgeFadeFilter } from '../../lib/ffmpeg.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';-import { getProject, listProjects, mutateProjectRecord } from './projects.js';+import { listProjects, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { suggestSocialCuts } from './socialCuts.js';import { musicVideoAspect } from '../../lib/musicVideoAspect.js';import { musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';@@ -57,12 +58,6 @@ export const getActivePublishKitBuild = (projectId) => {return jobId && jobs.get(jobId)?.status === 'running' ? { jobId, status: 'running' } : null;};-async function requireProject(projectId) {- const project = await getProject(projectId);- if (!project) throw kitError(404, 'NOT_FOUND', 'Project not found');- return project;-}-/** The final render's file (the YouTube master), or a 409 naming what's missing. */async function finalRenderFile(project) {if (!project.renderHistoryId) throw kitError(409, 'NO_FINAL_RENDER', 'Render the final video before building the publishing kit');diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 139d062c87..9883091d33 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -42,6 +42,7 @@ import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';import { getTrack } from '../tracks/index.js';import { getProject, listProjects, updateProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { applyProjectPatch } from './projectsLogic.js';import { MUSIC_VIDEO_FRAME_FITS, STILL_PAN_TRAVEL, STILL_PUSH_ZOOM, clipOffsetSec, clipReversed, clipSpeedRate, isSelfDrawnLayer, sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';import { musicVideoAspect, musicVideoRenderCanvas } from '../../lib/musicVideoAspect.js';@@ -1168,8 +1169,7 @@ export async function renderMusicVideo(projectId, options = {}) {}async function renderAdmittedMusicVideo(projectId, options, permit) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);assertProductionApproval(project, 'storyboard');if (typeof options?.codeDirectory === 'string' && options.codeDirectory) {throw new ServerError('Import and select the composition document before rendering.', { status: 409, code: 'MUSIC_VIDEO_UNREVIEWED_DIRECTORY' });diff --git a/server/services/musicVideo/renderCleanup.js b/server/services/musicVideo/renderCleanup.jsindex ef02456560..d0c15c24a7 100644--- a/server/services/musicVideo/renderCleanup.js+++ b/server/services/musicVideo/renderCleanup.js@@ -6,7 +6,8 @@ import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import { safeUnder } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';-import { getProject, listProjects, withProjectMediaMutation } from './projects.js';+import { listProjects, withProjectMediaMutation } from './projects.js';+import { requireProject } from './requireProject.js';import { withRenderCleanupReservation } from './renderCleanupActivity.js';export { assertRenderCleanupIdle, withRenderCleanupReservation } from './renderCleanupActivity.js';import { musicVideoEvents } from './events.js';@@ -51,8 +52,7 @@ const renderFiles = entry => [safeUnder(PATHS.videos, entry.filename),].filter(Boolean);async function finalInventory(projectId, history, pending = []) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const [{ listCollections }, timeline, director, { isPublishKitBuildActive }, { listJobs }] = await Promise.all([import('../mediaCollections.js'), import('../videoTimeline/local.js'), import('../creativeDirector/local.js'),import('./publishKit.js'), import('../mediaJobQueue/index.js'),diff --git a/server/services/musicVideo/requireProject.js b/server/services/musicVideo/requireProject.jsnew file mode 100644index 0000000000..801392b9ec--- /dev/null+++ b/server/services/musicVideo/requireProject.js@@ -0,0 +1,14 @@+/**+ * The one "load this music-video project or answer 404" guard for services and+ * routes. A leaf beside projects.js rather than an export of it: ~30 suites+ * `vi.mock('./projects.js')` with a getProject-only factory, and those mocks+ * keep reaching this guard through its import of getProject.+ */+import { ServerError } from '../../lib/errorHandler.js';+import { getProject } from './projects.js';++export async function requireProject(id) {+ const project = await getProject(id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.jsindex 1672430e7f..9299ea0478 100644--- a/server/services/musicVideo/revisionService.js+++ b/server/services/musicVideo/revisionService.js@@ -22,6 +22,7 @@import { musicVideoDependencyImpact } from '../../lib/musicVideoDependencies.js';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';import {assertRevisionOpenForGeneration,@@ -171,14 +172,12 @@ async function dependencyImpactFor(project) {}export async function getDependencyImpact(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);return dependencyImpactFor(project);}export async function startDependencyRepair(projectId, input) {- const before = await getProject(projectId);- if (!before) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const before = await requireProject(projectId);const impact = await dependencyImpactFor(before);const structuralBasis = musicVideoDependencyImpact(before).basis;return mutateProjectRecord(projectId, (current) => {diff --git a/server/services/musicVideo/sharingCopy.js b/server/services/musicVideo/sharingCopy.jsindex 03f969fc70..f3e4068589 100644--- a/server/services/musicVideo/sharingCopy.js+++ b/server/services/musicVideo/sharingCopy.js@@ -12,6 +12,7 @@ import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js'import { maintenance } from '../../lib/maintenanceAdmission.js';import { ServerError } from '../../lib/errorHandler.js';import { getProject, listProjects, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { getHistoryItem } from '../videoGen/history.js';import { videoGenEvents } from '../videoGen/events.js';@@ -58,8 +59,7 @@ async function assertSourceSelected(source) {}async function finalSource(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);if (!project.renderHistoryId) throw fail('Render the final video before preparing a sharing copy');const entry = await getHistoryItem(project.renderHistoryId);if (!entry?.filename) throw fail('The final render is missing');diff --git a/server/services/musicVideo/shotSegments.js b/server/services/musicVideo/shotSegments.jsindex 276281a0e2..a2498155bc 100644--- a/server/services/musicVideo/shotSegments.js+++ b/server/services/musicVideo/shotSegments.js@@ -39,7 +39,7 @@ import { lyricOverlayDocumentData } from './lyricPlaythrough.js';import { applyFilmLookFinish } from './filmLookFinish.js';import { getMusicVideoOutroStats, renderStatsOutroClip } from './statsOutro.js';import { nameShots } from './productionReview.js';-import { getProject } from './projects.js';+import { requireProject } from './requireProject.js';import { assertRenderCleanupIdle, withRenderCleanupReservation } from './renderCleanupActivity.js';import { musicVideoEvents } from './events.js';import { maintenance } from '../../lib/maintenanceAdmission.js';@@ -568,8 +568,7 @@ const shotJobKey = (projectId, sceneId) => `${projectId}:${sceneId}`;const emitShotRender = (payload) => musicVideoEvents.emit('shot-render', payload);async function loadProjectScene(projectId, sceneId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);if (!(project.scenes || []).some((scene) => scene.sceneId === sceneId)) throw new ServerError('Shot not found', { status: 404, code: 'NOT_FOUND' });return project;}@@ -580,8 +579,7 @@ async function loadProjectScene(projectId, sceneId) {* fix) instead of shot states, since no segment can be placed until it plans.*/export async function getShotRenderStatus(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);if (project.composition?.mode !== 'composed') return { available: false, shots: [], outro: null, ready: 0, total: 0 };const plan = await planShotSegments(project).catch((err) => {if (!err?.status || err.status >= 500) throw err;@@ -712,8 +710,7 @@ const rememberFilmLook = (dir, look) => updateFilmLooks(dir, (looks) => {const videoLookSegments = (plan) => [...plan.segments.filter((s) => !s.ownLook), ...(plan.outro ? [plan.outro] : [])];async function planForLooks(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);if (project.composition?.mode !== 'composed') return { project, plan: null };const plan = await planShotSegments(project).catch((err) => {if (!err?.status || err.status >= 500) throw err;diff --git a/server/services/musicVideo/songAutoPrepare.js b/server/services/musicVideo/songAutoPrepare.jsindex 03d663c853..e90c4a9cb2 100644--- a/server/services/musicVideo/songAutoPrepare.js+++ b/server/services/musicVideo/songAutoPrepare.js@@ -15,9 +15,8 @@* and a project an autonomous run is driving are left alone.*/-import { ServerError } from '../../lib/errorHandler.js';import { isNonBlankStr } from '../../lib/textUtils.js';-import { getProject } from './projects.js';+import { requireProject } from './requireProject.js';import { analyzeProjectSong } from './projectAudio.js';import { startLyricAlign } from './lyricAlignJob.js';@@ -46,8 +45,7 @@ function needsAutoAlignment(project) {* (null when none was needed).*/export async function autoPrepareSong(projectId, { analyze = analyzeProjectSong, align = startLyricAlign } = {}) {- let project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ let project = await requireProject(projectId);if (!hasAudio(project) || autonomousRunActive(project)) return { project, analyzed: false, alignJobId: null };let analyzed = false;if (!project.audioAnalysis) {diff --git a/server/services/musicVideo/songRevision.js b/server/services/musicVideo/songRevision.jsindex da93be2e70..e3d74850fc 100644--- a/server/services/musicVideo/songRevision.js+++ b/server/services/musicVideo/songRevision.js@@ -2,6 +2,7 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord, cloneProject } from './projects.js';+import { requireProject } from './requireProject.js';import { applyProjectPatch, addScenes } from './projectsLogic.js';import { parseLyricCues } from './timedText.js';import { musicVideoEvents } from './events.js';@@ -172,8 +173,7 @@ export async function selectSongRevision(projectId, revisionId, songId) {* sheet, then starts re-timing it. Resolves `{ project, retimeJobId }`.*/export async function reviseSongFromTrack(projectId, { trackId }) {- const source = await getProject(projectId);- if (!source) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const source = await requireProject(projectId);if (productionActive(source)) fail('Stop active production before revising the song');const track = await deps.getTrack(trackId);if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });@@ -277,8 +277,7 @@ function replanNote(scene, entry) {* `dismiss` keeps the named shots as they are.*/export async function resolveSongRevisionScenes(projectId, { revisionId, action, sceneIds = null, ...route }) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const revision = requireRevision(project, revisionId);if (!revision.sceneReview) fail('Re-time the shots to the new song first', 'SONG_REVISION_NOT_REMAPPED');const statuses = action === 'remove' ? ['removed'] : action === 'replan' ? ['changed', 'new'] : ['changed', 'new', 'removed'];diff --git a/server/services/musicVideo/trackLyrics.js b/server/services/musicVideo/trackLyrics.jsindex 2fd1b37255..b877a140bb 100644--- a/server/services/musicVideo/trackLyrics.js+++ b/server/services/musicVideo/trackLyrics.js@@ -12,7 +12,8 @@import { ServerError } from '../../lib/errorHandler.js';import { getTrack } from '../tracks/index.js';-import { getProject, updateProject } from './projects.js';+import { updateProject } from './projects.js';+import { requireProject } from './requireProject.js';import { parseLyricCues } from './timedText.js';export const MAX_LYRIC_CUES = 2000;@@ -23,8 +24,7 @@ export const MAX_LYRIC_CUES = 2000;* @returns {Promise<{ project: object, imported: number, markers: number, skipped: string|null }>}*/export async function importTrackLyrics(projectId, { mode = 'replace' } = {}) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);const ifEmpty = mode === 'if-empty';const skip = (skipped) => ({ project, imported: 0, markers: 0, skipped });if (ifEmpty && (project.lyricCues || []).length > 0) return skip('has-lyrics');diff --git a/server/services/musicVideo/treatmentService.js b/server/services/musicVideo/treatmentService.jsindex 3b9d7d7d66..f05eae2395 100644--- a/server/services/musicVideo/treatmentService.js+++ b/server/services/musicVideo/treatmentService.js@@ -12,10 +12,10 @@* draft and says why.*/-import { ServerError } from '../../lib/errorHandler.js';import { runPromptThroughProvider } from '../promptRunner.js';import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';-import { getProject, mutateProjectRecord } from './projects.js';+import { mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import {applyTreatmentPatch,applyTreatmentToProject,@@ -32,12 +32,6 @@ import {parseTreatmentResponse,} from './treatmentDraft.js';-async function requireProject(id) {- const project = await getProject(id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- return project;-}-/** Edit the brief / arc / shot directions, or rebase onto the current inputs. */export async function updateTreatment(id, patch) {const { project } = await mutateProjectRecord(id, (current) => ({ project: applyTreatmentPatch(current, patch) }));diff --git a/server/services/musicVideo/vocalStem.js b/server/services/musicVideo/vocalStem.jsindex 941686c551..f860c61577 100644--- a/server/services/musicVideo/vocalStem.js+++ b/server/services/musicVideo/vocalStem.js@@ -32,6 +32,7 @@ import { PATHS } from '../../lib/fileUtils.js';import { probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';import { importUploadedTrack } from '../pipeline/musicLibrary.js';import { getProject, updateProject } from './projects.js';+import { requireProject } from './requireProject.js';// A same-session bounce differs from the master by encoder padding at most// (an MP3 frame is ~26ms); a tenth of a second admits that and nothing that@@ -76,8 +77,7 @@ const audioSourceKey = (project) => `${project?.trackId ?? ''}\u0000${project?.u*/export async function attachVocalStem(projectId, { tempPath, originalName }) {try {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = await requireProject(projectId);// Lazy: render.js pulls the whole render pipeline.const { resolveMasterAudioPath } = await import('./render.js');const masterPath = await resolveMasterAudioPath(project);@@ -104,7 +104,6 @@ export async function attachVocalStem(projectId, { tempPath, originalName }) {* audio, because the library is shared.*/export async function detachVocalStem(projectId) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ await requireProject(projectId);return updateProject(projectId, { vocalStemFilename: null, performanceConditioningSource: 'master' });}diff --git a/server/services/musicVideo/youtubeThumbnail.js b/server/services/musicVideo/youtubeThumbnail.jsindex 5d1e59ab7c..b59052fe27 100644--- a/server/services/musicVideo/youtubeThumbnail.js+++ b/server/services/musicVideo/youtubeThumbnail.js@@ -42,6 +42,7 @@ import { promptAddition } from '../../lib/modelInput.js';import { trimTo } from '../../lib/textUtils.js';import { musicVideoEvents } from './events.js';import { getProject, mutateProjectRecord } from './projects.js';+import { requireProject } from './requireProject.js';import { projectPublishKit, releaseKitFiles } from './publishKit.js';export const MAX_THUMBNAIL_TESTS = 3;@@ -89,8 +90,7 @@ const unitOr = (value, fallback) => (Number.isFinite(value) ? value : (Number.is* cover's title, else the song's name). `lettering: false` uses the image bare.*/export async function composeProjectYoutubeThumbnail(projectId, { source = null, title, focusX, focusY, lettering } = {}) {- const project = await getProject(projectId);- if (!project) throw thumbError(404, 'NOT_FOUND', 'Project not found');+ const project = await requireProject(projectId);const thumb = projectYoutubeThumbnail(project);const art = projectCoverArt(project);const from = source || thumb.source;@@ -130,8 +130,7 @@ export async function recomposeYoutubeThumbnail(projectId) {/** Stop using the made thumbnail: the YouTube post goes back to the best video frame. */export async function clearProjectYoutubeThumbnail(projectId) {- const project = await getProject(projectId);- if (!project) throw thumbError(404, 'NOT_FOUND', 'Project not found');+ const project = await requireProject(projectId);const old = projectYoutubeThumbnail(project).filename;const out = await mutateProjectRecord(projectId, (current) => {const { youtubeThumbnail, ...kit } = projectPublishKit(current);@@ -151,8 +150,7 @@ const testsOf = (project) => {/** Keep the made thumbnail, as it is now, as one of the Test & Compare variants. */export async function addYoutubeThumbnailTest(projectId) {- const project = await getProject(projectId);- if (!project) throw thumbError(404, 'NOT_FOUND', 'Project not found');+ await requireProject(projectId);const out = await mutateProjectRecord(projectId, (current) => {const kit = projectPublishKit(current);const thumb = projectYoutubeThumbnail(current);@@ -168,8 +166,7 @@ export async function addYoutubeThumbnailTest(projectId) {/** Drop a variant from the test set (its file goes once nothing names it). */export async function removeYoutubeThumbnailTest(projectId, filename) {- const project = await getProject(projectId);- if (!project) throw thumbError(404, 'NOT_FOUND', 'Project not found');+ await requireProject(projectId);let held = false;const out = await mutateProjectRecord(projectId, (current) => {const kit = projectPublishKit(current);@@ -221,8 +218,7 @@ const writeThumb = (projectId, update) => mutateProjectRecord(projectId, (curren* thumbnail when it lands.*/export async function paintYoutubeThumbnail(projectId, { source, title, notes = '' } = {}) {- const project = await getProject(projectId);- if (!project) throw thumbError(404, 'NOT_FOUND', 'Project not found');+ const project = await requireProject(projectId);const previous = projectYoutubeThumbnail(project).pending;if (await pendingIsLive(previous)) throw thumbError(409, 'THUMBNAIL_IN_PROGRESS', 'A thumbnail is already being painted');const name = String(title || '').trim();