Skip to content

🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.

feat: add scene repair studio

darkzOGx231a110e1bee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5a72f3a..22da10d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## Unreleased
+- Added a persistent Scene Repair Studio with scene-level narration, prompts, timing, provider/task evidence, asset origin, rights state, source links, locks, and revision history
+- Added selective scene editing, reordering, paid regeneration confirmation, licensed image/video replacement, narration invalidation, and scene-aware caption rebuilding
+- Final scene rebuilds now create a new MP4 while preserving the previous artifact; incomplete, stale, unlicensed, or unrepaired scenes block approval
- Added a durable video-provider layer for Seedance 2.5, MiniMax H3, Gemini Omni Flash, Kling 3.0 Omni, and Wan 2.7
- Added capability-aware automatic routing with local slideshow as the no-cost default and final fallback
- Added persistent external media task IDs, provider/model evidence, cancellation handoff where supported, and restart-safe reuse of known provider tasks
diff --git a/README.md b/README.md
index 1c7275c..8055338 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,14 @@ Every generation stage writes a local SQLite checkpoint. If a provider times out
Autonomous Operator runs preserve their research and editorial plan, so **Resume run** continues unfinished plan items instead of researching and generating completed videos again. Publishing remains fail-closed: if an upload may have reached YouTube but no video ID was returned, Lumen requires channel reconciliation before another upload attempt.
+### Repair one scene without starting over
+
+Every production now keeps a durable scene manifest with its narration, visual prompt, timing, provider/task identity, asset origin, rights state, evidence links, and revision history. Open **Scene Repair Studio** inside Review Studio to edit a scene, change its order, lock a scene that already works, upload a licensed replacement asset, or regenerate only that scene.
+
+Paid video regeneration always shows the provider and generated seconds and requires a separate confirmation. Uploaded assets require an explicit rights confirmation. Narration edits invalidate that scene's audio and factual review; live narration must be regenerated and any new factual claim must be reviewed against verified evidence before approval.
+
+When the timeline is ready, **Rebuild final video** creates a new MP4 and scene-aware captions while preserving the previous final video path in the production record. Approval stays blocked while any scene is missing, generating, stale, failed, or waiting for rebuild. Approved or scheduled productions are locked against scene repair.
+
### Review research and provenance
Every production has an **Evidence desk** inside Review Studio. Autonomous research carries exact YouTube source metadata into the production, while AI-generated scripts list the factual claims that need review. Add any official articles, datasets, asset licenses, or other evidence that the script needs, verify each source, and connect it to the claims it supports.
diff --git a/agents/production-management-agent.js b/agents/production-management-agent.js
index 40b6c33..aadddad 100644
--- a/agents/production-management-agent.js
+++ b/agents/production-management-agent.js
@@ -2,6 +2,7 @@ const path = require('path');
const fs = require('fs').promises;
const { Logger } = require('../utils/logger');
const { AIVideoGenerator } = require('../utils/ai-video-generator');
+const { SceneRepairService } = require('../utils/scene-repair-service');
class ProductionManagementAgent {
constructor(db, credentials) {
@@ -11,6 +12,7 @@ class ProductionManagementAgent {
this.pipeline = [];
this.assets = new Map();
this.aiVideoGenerator = new AIVideoGenerator(credentials, { db });
+ this.sceneRepair = new SceneRepairService(db, this.aiVideoGenerator, { logger: this.logger });
}
async initialize() {
@@ -101,6 +103,9 @@ class ProductionManagementAgent {
// Final assembly
await this.assembleVideo(productionData);
+ // Persist a scene-addressable production manifest for selective review and repair.
+ await this.sceneRepair.initializeProduction(productionData, this.aiVideoGenerator.lastVideoResult || {});
+
// Mark as ready — or simulated, when no real video could be produced
const simulated = Boolean(productionData.assets.finalVideo?.simulated);
if (simulated) {
diff --git a/dashboard/app.js b/dashboard/app.js
index 693d7c2..576279b 100644
--- a/dashboard/app.js
+++ b/dashboard/app.js
@@ -541,6 +541,55 @@ function renderProvenanceEditor(provenance = {}, canReview = true) {
</section>`;
}
+function renderSceneEditor(item, canReview = true) {
+ const scenes = item.scenes || [];
+ if (!scenes.length) return '';
+ const verifiedSources = (item.provenance?.sources || []).filter(source => source.status === 'verified');
+ return `<section class="scene-repair-panel">
+ <div class="panel-heading scene-heading">
+ <div><p class="eyebrow">SCENE REPAIR STUDIO</p><h3>Repair the timeline, not the whole video</h3><p>Edit, replace, or regenerate one scene. Changes remain draft-only until the timeline is rebuilt and approved.</p></div>
+ ${canReview ? `<button type="button" class="button primary small" data-rebuild-scenes="${escapeHTML(item.id)}">Rebuild final video</button>` : ''}
+ </div>
+ <div class="scene-summary"><strong>${scenes.length} scenes</strong><span>${Math.round(scenes.reduce((sum, scene) => sum + Number(scene.duration || 0), 0))}s timeline</span><span>${scenes.filter(scene => scene.status !== 'ready').length} pending repairs</span></div>
+ <div class="scene-list">
+ ${scenes.map((scene, index) => {
+ const disabled = !canReview || scene.locked;
+ const sourceIds = new Set(scene.provenanceSourceIds || []);
+ const preview = scene.assetUrl
+ ? scene.assetType === 'video'
+ ? `<video controls preload="metadata"><source src="${escapeHTML(scene.assetUrl)}"></video>`
+ : `<img src="${escapeHTML(scene.assetUrl)}" alt="${escapeHTML(scene.label)} scene asset">`
+ : '<div class="preview-placeholder">No scene asset</div>';
+ return `<article class="scene-card ${scene.locked ? 'locked' : ''}" data-scene-card="${escapeHTML(scene.id)}">
+ <div class="scene-card-top">
+ <div class="scene-preview">${preview}<span class="scene-number">${index + 1}</span></div>
+ <div class="scene-identity">
+ <div class="scene-status-row">${statusChip(scene.status)} ${scene.narrationStatus === 'stale' ? statusChip('narration_stale') : ''}<span>r${scene.revision}</span></div>
+ <label><span>Scene label</span><input data-scene-field="label" maxlength="120" value="${escapeHTML(scene.label)}" ${disabled ? 'disabled' : ''}></label>
+ <label><span>Duration</span><input data-scene-field="duration" type="number" min="2" max="600" step="0.5" value="${escapeHTML(scene.duration)}" ${disabled ? 'disabled' : ''}></label>
+ </div>
+ </div>
+ <label><span>Narration</span><textarea data-scene-field="scriptText" rows="4" maxlength="10000" ${disabled ? 'disabled' : ''}>${escapeHTML(scene.scriptText)}</textarea></label>
+ <label><span>Visual prompt</span><textarea data-scene-field="prompt" rows="3" maxlength="2000" ${disabled ? 'disabled' : ''}>${escapeHTML(scene.prompt)}</textarea></label>
+ ${verifiedSources.length ? `<fieldset class="source-checklist scene-sources" ${disabled ? 'disabled' : ''}><legend>Verified evidence linked to this narration</legend>${verifiedSources.map(source => `<label><input type="checkbox" data-scene-source value="${escapeHTML(source.id)}" ${sourceIds.has(source.id) ? 'checked' : ''}> ${escapeHTML(source.title)}</label>`).join('')}</fieldset>` : ''}
+ <div class="scene-options">
+ <label class="toggle"><input type="checkbox" data-scene-factual checked ${disabled ? 'disabled' : ''}><span></span> Narration changes may contain factual claims</label>
+ <span>${escapeHTML(scene.provider || 'local')} ${scene.model ? `· ${escapeHTML(scene.model)}` : ''}</span>
+ </div>
+ ${canReview ? `<div class="scene-actions">
+ <button type="button" class="text-button" data-scene-move="up" ${disabled || index === 0 ? 'disabled' : ''}>↑ Earlier</button>
+ <button type="button" class="text-button" data-scene-move="down" ${disabled || index === scenes.length - 1 ? 'disabled' : ''}>↓ Later</button>
+ <button type="button" class="text-button approve" data-scene-save ${disabled ? 'disabled' : ''}>Save scene</button>
+ <button type="button" class="text-button" data-scene-regenerate ${disabled ? 'disabled' : ''}>Regenerate scene</button>
+ <label class="text-button upload-button ${disabled ? 'disabled' : ''}">Replace asset<input type="file" data-scene-upload accept="image/png,image/jpeg,image/webp,video/mp4" ${disabled ? 'disabled' : ''}></label>
+ <button type="button" class="text-button" data-scene-lock>${scene.locked ? 'Unlock' : 'Lock'}</button>
+ </div>` : ''}
+ </article>`;
+ }).join('')}
+ </div>
+ </section>`;
+}
+
async function openContent(productionId) {
$('#loading').classList.add('active');
try {
@@ -556,22 +605,26 @@ async function openContent(productionId) {
const selectedThumbnailVariant = Number(data.selectedThumbnailVariant || 0);
$('#content-detail').innerHTML = `
<div class="dialog-heading"><div><p class="eyebrow">CONTENT REVIEW</p><h2>${escapeHTML(title)}</h2><div class="meta-line">${statusChip(item.schedule?.status || item.review_status || item.status)} · Quality ${qualityScore(item.qualityChecks)}%</div></div><button type="button" class="close-button" data-close>×</button></div>
- <div class="content-layout">
- <div>
- <div class="preview">${item.assetUrls.video ? `<video controls preload="metadata" poster="${item.assetUrls.thumbnail || ''}"><source src="${item.assetUrls.video}" type="video/mp4"></video>` : item.assetUrls.thumbnail ? `<img src="${item.assetUrls.thumbnail}" alt="Generated thumbnail">` : '<div class="preview-placeholder">No playable preview was produced.</div>'}</div>
- <div class="quality-grid">${(item.qualityChecks || []).map(check => `<div class="quality-check ${check.passed ? 'pass' : 'fail'}">${check.passed ? '✓' : '×'} ${escapeHTML(check.message)}</div>`).join('') || '<div class="quality-check">No quality results recorded.</div>'}</div>
- ${item.review_notes ? `<p class="callout">${escapeHTML(item.review_notes)}</p>` : ''}
+ <form id="content-review-form" class="editor content-review-editor">
+ <div class="content-layout">
+ <div>
+ <div class="preview">${item.assetUrls.video ? `<video controls preload="metadata" poster="${item.assetUrls.thumbnail || ''}"><source src="${item.assetUrls.video}" type="video/mp4"></video>` : item.assetUrls.thumbnail ? `<img src="${item.assetUrls.thumbnail}" alt="Generated thumbnail">` : '<div class="preview-placeholder">No playable preview was produced.</div>'}</div>
+ <div class="quality-grid">${(item.qualityChecks || []).map(check => `<div class="quality-check ${check.passed ? 'pass' : 'fail'}">${check.passed ? '✓' : '×'} ${escapeHTML(check.message)}</div>`).join('') || '<div class="quality-check">No quality results recorded.</div>'}</div>
+ ${item.review_notes ? `<p class="callout">${escapeHTML(item.review_notes)}</p>` : ''}
+ </div>
+ <div class="editor">
+ <label><span>Title</span><input name="title" maxlength="100" value="${escapeHTML(title)}" required></label>
+ <label><span>Description</span><textarea name="description" rows="7">${escapeHTML(description)}</textarea></label>
+ <label><span>Tags</span><input name="tags" value="${escapeHTML(tags.join(', '))}"></label>
+ ${experiment ? `<section class="experiment-panel">
+ <div><p class="eyebrow">APPROVED LEARNING EXPERIMENT</p><strong>${escapeHTML(experiment.hypothesis)}</strong><p>Choose the packaging to ship. Nothing changes on YouTube until this content is approved and published.</p></div>
+ <label><span>Title variant</span><select name="selectedTitleVariant">${experiment.titleVariants.map((variant, index) => `<option value="${index}" data-title="${escapeHTML(variant.title)}" ${index === selectedTitleVariant ? 'selected' : ''}>${escapeHTML(variant.label)} — ${escapeHTML(variant.title)}</option>`).join('')}</select></label>
+ <div class="experiment-thumbnails">${experiment.thumbnailVariants.map((variant, index) => `<label class="experiment-thumb ${index === selectedThumbnailVariant ? 'selected' : ''}"><input type="radio" name="selectedThumbnailVariant" value="${index}" ${index === selectedThumbnailVariant ? 'checked' : ''}><img src="${escapeHTML(item.assetUrls.experimentThumbnails?.[index] || '')}" alt="${escapeHTML(variant.label)} thumbnail variant"><span>${escapeHTML(variant.label)}</span></label>`).join('')}</div>
+ </section>` : ''}
+ </div>
</div>
- <form id="content-review-form" class="editor">
- <label><span>Title</span><input name="title" maxlength="100" value="${escapeHTML(title)}" required></label>
- <label><span>Description</span><textarea name="description" rows="7">${escapeHTML(description)}</textarea></label>
- <label><span>Tags</span><input name="tags" value="${escapeHTML(tags.join(', '))}"></label>
- ${experiment ? `<section class="experiment-panel">
- <div><p class="eyebrow">APPROVED LEARNING EXPERIMENT</p><strong>${escapeHTML(experiment.hypothesis)}</strong><p>Choose the packaging to ship. Nothing changes on YouTube until this content is approved and published.</p></div>
- <label><span>Title variant</span><select name="selectedTitleVariant">${experiment.titleVariants.map((variant, index) => `<option value="${index}" data-title="${escapeHTML(variant.title)}" ${index === selectedTitleVariant ? 'selected' : ''}>${escapeHTML(variant.label)} — ${escapeHTML(variant.title)}</option>`).join('')}</select></label>
- <div class="experiment-thumbnails">${experiment.thumbnailVariants.map((variant, index) => `<label class="experiment-thumb ${index === selectedThumbnailVariant ? 'selected' : ''}"><input type="radio" name="selectedThumbnailVariant" value="${index}" ${index === selectedThumbnailVariant ? 'checked' : ''}><img src="${escapeHTML(item.assetUrls.experimentThumbnails?.[index] || '')}" alt="${escapeHTML(variant.label)} thumbnail variant"><span>${escapeHTML(variant.label)}</span></label>`).join('')}</div>
- </section>` : ''}
- ${renderProvenanceEditor(item.provenance, canReview)}
+ ${renderSceneEditor(item, canReview)}
+ ${renderProvenanceEditor(item.provenance, canReview)}
<div class="form-grid two">
<label><span>Publish time</span><input name="publishTime" type="datetime-local" value="${toLocalInput(publishTime)}"></label>
<label><span>Privacy</span><select name="privacyStatus"><option value="private" ${data.privacyStatus === 'private' ? 'selected' : ''}>Private</option><option value="unlisted" ${data.privacyStatus === 'unlisted' ? 'selected' : ''}>Unlisted</option><option value="public" ${data.privacyStatus === 'public' ? 'selected' : ''}>Public</option></select></label>
@@ -581,8 +634,7 @@ async function openContent(productionId) {
<label class="toggle"><input name="rightsConfirmed" type="checkbox" ${data.rightsConfirmed ? 'checked' : ''}><span></span> Media rights confirmed</label>
</div>
${canReview ? `<div class="form-actions"><button type="button" class="button primary" data-approve-content="${escapeHTML(item.id)}">Approve & schedule</button><button type="button" class="button secondary" data-save-content="${escapeHTML(item.id)}">Save draft</button><button type="button" class="button danger" data-reject-content="${escapeHTML(item.id)}">Reject</button><button type="button" class="button ghost" data-retry-content="${escapeHTML(item.id)}">Regenerate</button></div>` : `<a class="button secondary" href="${escapeHTML(item.schedule?.youtube_url || '#')}" target="_blank" rel="noopener">Open on YouTube</a>`}
- </form>
- </div>`;
+ </form>`;
$('#content-review-form').dataset.productionId = item.id;
$('#content-dialog').showModal();
} catch (error) {
@@ -616,6 +668,47 @@ function contentFormData() {
};
}
+function sceneFormData(card) {
+ return {
+ label: card.querySelector('[data-scene-field="label"]').value,
+ duration: Number(card.querySelector('[data-scene-field="duration"]').value),
+ scriptText: card.querySelector('[data-scene-field="scriptText"]').value,
+ prompt: card.querySelector('[data-scene-field="prompt"]').value,
+ provenanceSourceIds: Array.from(card.querySelectorAll('[data-scene-source]:checked')).map(input => input.value),
+ factualChange: card.querySelector('[data-scene-factual]')?.checked !== false
+ };
+}
+
+async function refreshContentDialog(productionId, message) {
+ if (message) showToast(message);
+ if ($('#content-dialog').open) $('#content-dialog').close();
+ await refreshDashboard(true);
+ await openContent(productionId);
+}
+
+async function uploadSceneAsset(productionId, sceneId, file) {
+ if (!confirm('Confirm you own or have permission to use this replacement asset.')) return;
+ const synthetic = confirm('Does this replacement contain realistic altered or synthetic media that should be disclosed to YouTube?');
+ $('#loading').classList.add('active');
+ try {
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}/asset`, {
+ method: 'PUT',
+ body: file,
+ headers: {
+ 'Content-Type': file.type,
+ 'x-file-name': file.name,
+ 'x-rights-confirmed': 'true',
+ 'x-synthetic-media': String(synthetic)
+ }
+ });
+ await refreshContentDialog(productionId, 'Scene asset replaced. Rebuild before approval.');
+ } catch (error) {
+ showToast(error.message, 'error');
+ } finally {
+ $('#loading').classList.remove('active');
+ }
+}
+
function provenanceFormData() {
const sources = $$('[data-provenance-source]').map(item => ({
id: item.dataset.id,
@@ -732,6 +825,69 @@ document.addEventListener('click', async event => {
await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});
}
+ const sceneButton = event.target.closest('[data-scene-save], [data-scene-regenerate], [data-scene-lock], [data-scene-move]');
+ if (sceneButton) {
+ const card = sceneButton.closest('[data-scene-card]');
+ const productionId = $('#content-review-form')?.dataset.productionId;
+ const sceneId = card?.dataset.sceneCard;
+ if (!productionId || !sceneId) return;
+ try {
+ if (sceneButton.matches('[data-scene-lock]')) {
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}`, {
+ method: 'PATCH', body: JSON.stringify({ locked: !card.classList.contains('locked') })
+ });
+ await refreshContentDialog(productionId, card.classList.contains('locked') ? 'Scene unlocked.' : 'Scene locked.');
+ return;
+ }
+ if (sceneButton.matches('[data-scene-move]')) {
+ const cards = $$('[data-scene-card]');
+ const index = cards.indexOf(card);
+ const target = sceneButton.dataset.sceneMove === 'up' ? index - 1 : index + 1;
+ if (target < 0 || target >= cards.length) return;
+ const ids = cards.map(item => item.dataset.sceneCard);
+ [ids[index], ids[target]] = [ids[target], ids[index]];
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/reorder`, {
+ method: 'POST', body: JSON.stringify({ sceneIds: ids })
+ });
+ await refreshContentDialog(productionId, 'Timeline order updated. Rebuild before approval.');
+ return;
+ }
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}`, {
+ method: 'PATCH', body: JSON.stringify(sceneFormData(card))
+ });
+ if (sceneButton.matches('[data-scene-save]')) {
+ await refreshContentDialog(productionId, 'Scene draft saved.');
+ return;
+ }
+ const estimate = await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}/estimate`);
+ const message = estimate.paid
+ ? `Regenerate only this scene with ${estimate.provider} (${estimate.generatedSeconds}s). This consumes provider credits; the provider invoice is authoritative. Continue?`
+ : 'Regenerate only this scene with the configured image provider? A live image request may consume provider credits. Continue?';
+ if (!confirm(message)) return;
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}/regenerate`, {
+ method: 'POST', body: JSON.stringify({ confirmPaid: estimate.paid })
+ });
+ await refreshContentDialog(productionId, 'Scene regenerated. Rebuild the final video when the timeline is ready.');
+ } catch (error) {
+ showToast(error.message, 'error');
+ }
+ return;
+ }
+
+ const rebuildScenes = event.target.closest('[data-rebuild-scenes]');
+ if (rebuildScenes) {
+ const productionId = rebuildScenes.dataset.rebuildScenes;
+ if (confirm('Rebuild a new final MP4 from the current scene timeline? The previous final video will be preserved.')) {
+ try {
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/rebuild`, { method: 'POST', body: '{}' });
+ await refreshContentDialog(productionId, 'Final video rebuilt from the repaired timeline. Review it before approval.');
+ } catch (error) {
+ showToast(error.message, 'error');
+ }
+ }
+ return;
+ }
+
const addSource = event.target.closest('[data-add-provenance-source]');
if (addSource) {
const list = $('#provenance-sources');
@@ -800,6 +956,14 @@ document.addEventListener('change', event => {
const input = $('#content-review-form [name="title"]');
if (title && input) input.value = title;
}
+ if (event.target.matches('[data-scene-upload]')) {
+ const file = event.target.files?.[0];
+ const card = event.target.closest('[data-scene-card]');
+ const productionId = $('#content-review-form')?.dataset.productionId;
+ if (file && card && productionId) {
+ uploadSceneAsset(productionId, card.dataset.sceneCard, file);
+ }
+ }
});
$('#generate-button').addEventListener('click', () => $('#generate-dialog').showModal());
diff --git a/dashboard/styles.css b/dashboard/styles.css
index 48d61b3..d68f9a4 100644
--- a/dashboard/styles.css
+++ b/dashboard/styles.css
@@ -194,6 +194,31 @@ label small { color: var(--muted); font-weight: 400; }
.experiment-thumb input { width: auto; position: absolute; opacity: 0; }
.experiment-thumb img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 6px; background: #080a0d; }
.experiment-thumb span { display: block; color: var(--text); font-size: 11px; margin-top: 6px; text-align: center; }
+.scene-repair-panel { display: grid; gap: 14px; border: 1px solid rgba(245,185,68,.28); background: rgba(245,185,68,.045); border-radius: 12px; padding: 14px; }
+.scene-heading { align-items: flex-start; margin: 0; }
+.scene-heading h3 { font-size: 17px; margin: 2px 0 0; }
+.scene-heading p:not(.eyebrow) { color: var(--muted); font-size: 12px; line-height: 1.45; margin: 6px 0 0; }
+.scene-summary { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; color: var(--muted); font-size: 11px; }
+.scene-summary strong, .scene-summary span { border: 1px solid var(--line); border-radius: 999px; padding: 5px 9px; }
+.scene-summary strong { color: var(--text); }
+.scene-list { display: grid; gap: 12px; }
+.scene-card { display: grid; gap: 12px; border: 1px solid var(--line); border-radius: 11px; padding: 12px; background: rgba(7,10,14,.48); min-width: 0; }
+.scene-card.locked { border-color: rgba(114,165,255,.34); }
+.scene-card-top { display: grid; grid-template-columns: minmax(150px, .7fr) minmax(180px, 1fr); gap: 12px; align-items: start; }
+.scene-preview { position: relative; display: grid; place-items: center; aspect-ratio: 16 / 9; overflow: hidden; border: 1px solid var(--line); border-radius: 9px; background: #080a0d; }
+.scene-preview img, .scene-preview video { width: 100%; height: 100%; object-fit: cover; }
+.scene-number { position: absolute; top: 7px; left: 7px; display: grid; place-items: center; min-width: 25px; height: 25px; padding: 0 6px; border-radius: 999px; color: white; background: rgba(7,10,14,.82); font-size: 11px; font-weight: 800; }
+.scene-identity { display: grid; gap: 10px; }
+.scene-status-row { display: flex; flex-wrap: wrap; gap: 7px; align-items: center; color: var(--muted); font-size: 10px; }
+.scene-options { display: flex; justify-content: space-between; gap: 12px; align-items: center; color: var(--muted); font-size: 10px; }
+.scene-options .toggle { font-size: 10px; }
+.scene-actions { display: flex; flex-wrap: wrap; gap: 5px 13px; align-items: center; border-top: 1px solid var(--line); padding-top: 9px; }
+.scene-actions .text-button, .upload-button { min-height: 42px; display: inline-flex; align-items: center; }
+.scene-actions .text-button:disabled, .upload-button.disabled { opacity: .42; cursor: not-allowed; }
+.upload-button { cursor: pointer; }
+.upload-button input { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }
+.scene-sources { max-height: 130px; overflow: auto; }
+.status.narration_stale, .status.needs_rebuild, .status.visual_stale, .status.missing_asset, .status.generating { color: var(--amber); background: rgba(245,185,68,.12); }
.provenance-panel { display: grid; gap: 14px; border: 1px solid rgba(72,213,151,.25); background: rgba(72,213,151,.045); border-radius: 12px; padding: 14px; }
.provenance-panel .panel-heading { align-items: flex-start; margin: 0; }
.provenance-panel h3 { font-size: 17px; margin: 2px 0 0; }
@@ -247,4 +272,7 @@ label small { color: var(--muted); font-weight: 400; }
.job-card { align-items: flex-start; flex-wrap: wrap; }
.job-recovery { width: auto; max-width: 100%; flex: 1 1 100%; }
.job-recovery select { width: auto; min-width: 0; flex: 1; }
+ .scene-card-top { grid-template-columns: 1fr; }
+ .scene-options { align-items: flex-start; flex-direction: column; }
+ .scene-actions { gap: 4px 11px; }
}
diff --git a/database/db.js b/database/db.js
index bcdb641..068ad81 100644
--- a/database/db.js
+++ b/database/db.js
@@ -298,6 +298,50 @@ class Database {
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (production_id) REFERENCES productions(id)
)`,
+ `CREATE TABLE IF NOT EXISTS production_scenes (
+ id TEXT PRIMARY KEY,
+ production_id TEXT NOT NULL,
+ position INTEGER NOT NULL,
+ label TEXT NOT NULL,
+ script_text TEXT NOT NULL DEFAULT '',
+ prompt TEXT NOT NULL DEFAULT '',
+ duration REAL NOT NULL DEFAULT 5,
+ asset_type TEXT DEFAULT 'missing',
+ asset_origin TEXT DEFAULT 'generated',
+ asset_path TEXT,
+ audio_path TEXT,
+ provider TEXT,
+ model TEXT,
+ external_task_id TEXT,
+ status TEXT DEFAULT 'ready',
+ narration_status TEXT DEFAULT 'current',
+ revision INTEGER DEFAULT 1,
+ locked INTEGER DEFAULT 0,
+ rights_confirmed INTEGER DEFAULT 0,
+ provenance_source_ids TEXT NOT NULL DEFAULT '[]',
+ contains_synthetic_media INTEGER DEFAULT 0,
+ estimated_cost TEXT NOT NULL DEFAULT '{}',
+ actual_cost TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(production_id, position),
+ FOREIGN KEY (production_id) REFERENCES productions(id)
+ )`,
+ `CREATE TABLE IF NOT EXISTS production_scene_revisions (
+ id TEXT PRIMARY KEY,
+ production_id TEXT NOT NULL,
+ scene_id TEXT NOT NULL,
+ action TEXT NOT NULL,
+ status TEXT DEFAULT 'completed',
+ before_state TEXT NOT NULL DEFAULT '{}',
+ after_state TEXT NOT NULL DEFAULT '{}',
+ cost_evidence TEXT NOT NULL DEFAULT '{}',
+ error TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ completed_at TEXT,
+ FOREIGN KEY (production_id) REFERENCES productions(id),
+ FOREIGN KEY (scene_id) REFERENCES production_scenes(id)
+ )`,
`CREATE TABLE IF NOT EXISTS channel_profiles (
id TEXT PRIMARY KEY,
channel_name TEXT,
@@ -624,6 +668,8 @@ class Database {
[productionId]
);
const provenance = await this.getContentProvenance(productionId);
+ const scenes = await this.listProductionScenes(productionId);
+ const sceneRevisions = scenes.length ? await this.listProductionSceneRevisions(productionId, 50) : [];
return {
...row,
assets: JSON.parse(row.assets || '{}'),
@@ -638,7 +684,9 @@ class Database {
provenance: provenance || {
sources: [], claims: [], containsSyntheticMedia: false, status: 'not_required',
summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }
- }
+ },
+ scenes,
+ sceneRevisions
};
}
@@ -843,6 +891,154 @@ class Database {
} : null;
}
+ async replaceProductionScenes(productionId, scenes = []) {
+ await this.executeQuery('DELETE FROM production_scenes WHERE production_id = ?', [productionId]);
+ for (const [position, scene] of scenes.entries()) {
+ const id = scene.id || this.generateId('scene');
+ await this.executeQuery(
+ `INSERT INTO production_scenes (
+ id, production_id, position, label, script_text, prompt, duration,
+ asset_type, asset_origin, asset_path, audio_path, provider, model,
+ external_task_id, status, narration_status, revision, locked,
+ rights_confirmed, provenance_source_ids, contains_synthetic_media,
+ estimated_cost, actual_cost
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [
+ id, productionId, position, scene.label, scene.scriptText || '', scene.prompt || '', scene.duration,
+ scene.assetType || 'missing', scene.assetOrigin || 'generated', scene.assetPath || null,
+ scene.audioPath || null, scene.provider || null, scene.model || null, scene.externalTaskId || null,
+ scene.status || 'ready', scene.narrationStatus || 'current', scene.revision || 1,
+ scene.locked ? 1 : 0, scene.rightsConfirmed ? 1 : 0,
+ JSON.stringify(scene.provenanceSourceIds || []), scene.containsSyntheticMedia ? 1 : 0,
+ JSON.stringify(scene.estimatedCost || {}), JSON.stringify(scene.actualCost || {})
+ ]
+ );
+ }
+ return this.listProductionScenes(productionId);
+ }
+
+ async listProductionScenes(productionId) {
+ const rows = await this.getAllRows(
+ 'SELECT * FROM production_scenes WHERE production_id = ? ORDER BY position, created_at',
+ [productionId]
+ );
+ return rows.map(row => this.parseProductionScene(row));
+ }
+
+ async getProductionScene(productionId, sceneId) {
+ return this.parseProductionScene(await this.getRow(
+ 'SELECT * FROM production_scenes WHERE production_id = ? AND id = ?',
+ [productionId, sceneId]
+ ));
+ }
+
+ async updateProductionScene(productionId, sceneId, changes = {}) {
+ const current = await this.getProductionScene(productionId, sceneId);
+ if (!current) return null;
+ const next = { ...current, ...changes };
+ await this.executeQuery(
+ `UPDATE production_scenes SET
+ position = ?, label = ?, script_text = ?, prompt = ?, duration = ?,
+ asset_type = ?, asset_origin = ?, asset_path = ?, audio_path = ?, provider = ?,
+ model = ?, external_task_id = ?, status = ?, narration_status = ?, revision = ?,
+ locked = ?, rights_confirmed = ?, provenance_source_ids = ?,
+ contains_synthetic_media = ?, estimated_cost = ?, actual_cost = ?,
+ updated_at = datetime('now')
+ WHERE production_id = ? AND id = ?`,
+ [
+ next.position, next.label, next.scriptText || '', next.prompt || '', next.duration,
+ next.assetType || 'missing', next.assetOrigin || 'generated', next.assetPath || null,
+ next.audioPath || null, next.provider || null, next.model || null, next.externalTaskId || null,
+ next.status || 'ready', next.narrationStatus || 'current', next.revision || 1,
+ next.locked ? 1 : 0, next.rightsConfirmed ? 1 : 0,
+ JSON.stringify(next.provenanceSourceIds || []), next.containsSyntheticMedia ? 1 : 0,
+ JSON.stringify(next.estimatedCost || {}), JSON.stringify(next.actualCost || {}),
+ productionId, sceneId
+ ]
+ );
+ return this.getProductionScene(productionId, sceneId);
+ }
+
+ async reorderProductionScenes(productionId, orderedIds = []) {
+ const scenes = await this.listProductionScenes(productionId);
+ if (orderedIds.length !== scenes.length || new Set(orderedIds).size !== scenes.length ||
+ scenes.some(scene => !orderedIds.includes(scene.id))) {
+ throw new Error('Scene order must contain every scene exactly once');
+ }
+ // Move through temporary negative positions to preserve the unique constraint.
+ for (const scene of scenes) {
+ await this.executeQuery('UPDATE production_scenes SET position = ? WHERE id = ?', [-(scene.position + 1), scene.id]);
+ }
+ for (const [position, sceneId] of orderedIds.entries()) {
+ await this.executeQuery(
+ `UPDATE production_scenes SET position = ?, status = 'needs_rebuild', updated_at = datetime('now') WHERE id = ?`,
+ [position, sceneId]
+ );
+ }
+ return this.listProductionScenes(productionId);
+ }
+
+ async saveProductionSceneRevision(input = {}) {
+ const id = this.generateId('scene_revision');
+ await this.executeQuery(
+ `INSERT INTO production_scene_revisions (
+ id, production_id, scene_id, action, status, before_state, after_state,
+ cost_evidence, error, completed_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [
+ id, input.productionId, input.sceneId, input.action, input.status || 'completed',
+ JSON.stringify(input.before || {}), JSON.stringify(input.after || {}),
+ JSON.stringify(input.costEvidence || {}), input.error || null,
+ input.completedAt || new Date().toISOString()
+ ]
+ );
+ return this.getProductionSceneRevision(id);
+ }
+
+ async getProductionSceneRevision(id) {
+ return this.parseProductionSceneRevision(await this.getRow('SELECT * FROM production_scene_revisions WHERE id = ?', [id]));
+ }
+
+ async listProductionSceneRevisions(productionId, limit = 100) {
+ const rows = await this.getAllRows(
+ 'SELECT * FROM production_scene_revisions WHERE production_id = ? ORDER BY created_at DESC LIMIT ?',
+ [productionId, limit]
+ );
+ return rows.map(row => this.parseProductionSceneRevision(row));
+ }
+
+ parseProductionScene(row) {
+ if (!row) return null;
+ return {
+ ...row,
+ position: Number(row.position),
+ duration: Number(row.duration),
+ scriptText: row.script_text || '',
+ assetType: row.asset_type || 'missing',
+ assetOrigin: row.asset_origin || 'generated',
+ assetPath: row.asset_path || null,
+ audioPath: row.audio_path || null,
+ externalTaskId: row.external_task_id || null,
+ narrationStatus: row.narration_status || 'current',
+ revision: Number(row.revision || 1),
+ locked: Boolean(row.locked),
+ rightsConfirmed: Boolean(row.rights_confirmed),
+ provenanceSourceIds: JSON.parse(row.provenance_source_ids || '[]'),
+ containsSyntheticMedia: Boolean(row.contains_synthetic_media),
+ estimatedCost: JSON.parse(row.estimated_cost || '{}'),
+ actualCost: JSON.parse(row.actual_cost || '{}')
+ };
+ }
+
+ parseProductionSceneRevision(row) {
+ return row ? {
+ ...row,
+ before: JSON.parse(row.before_state || '{}'),
+ after: JSON.parse(row.after_state || '{}'),
+ costEvidence: JSON.parse(row.cost_evidence || '{}')
+ } : null;
+ }
+
async markInterruptedJobs() {
await this.executeQuery(
`UPDATE generation_jobs SET status = 'interrupted',
diff --git a/index.js b/index.js
index 520481c..6e8c903 100644
--- a/index.js
+++ b/index.js
@@ -21,6 +21,7 @@ const { AnonymousTelemetry } = require('./utils/anonymous-telemetry');
const { ProductionReadinessService } = require('./utils/production-readiness-service');
const { GenerationRecoveryService, GENERATION_STAGES } = require('./utils/generation-recovery-service');
const { ProvenanceService } = require('./utils/provenance-service');
+const { SceneRepairService } = require('./utils/scene-repair-service');
const { version } = require('./package.json');
const chalk = require('chalk');
@@ -40,6 +41,7 @@ class YouTubeAutomationAgent {
this.readiness = null;
this.recovery = null;
this.provenance = null;
+ this.scenes = null;
this.setupRequired = false;
}
@@ -91,6 +93,11 @@ class YouTubeAutomationAgent {
// Initialize agents
this.logger.info('Initializing agents...');
await this.initializeAgents();
+ this.scenes = this.agents.production?.sceneRepair || new SceneRepairService(
+ this.db,
+ this.agents.production?.aiVideoGenerator,
+ { logger: this.logger }
+ );
// Show which pipeline stages will run for real vs. be simulated
const capabilities = await this.logCapabilitySummary();
@@ -502,11 +509,110 @@ class YouTubeAutomationAgent {
});
this.app.get('/api/content/:productionId', async (req, res) => {
- const bundle = await this.db.getProductionBundle(req.params.productionId);
+ let bundle = await this.db.getProductionBundle(req.params.productionId);
if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ if (this.scenes && !bundle.scenes?.length) {
+ await this.scenes.ensureManifest(bundle);
+ bundle = await this.db.getProductionBundle(req.params.productionId);
+ }
return res.json(this.decorateContentBundle(bundle));
});
+ this.app.get('/api/content/:productionId/scenes/:sceneId/estimate', async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.regenerationEstimate(req.params.productionId, req.params.sceneId, {
+ provider: req.query.provider
+ });
+ return res.json(result);
+ } catch (error) {
+ return res.status(error.status || 400).json({ error: error.message, code: error.code, details: error.details });
+ }
+ });
+
+ this.app.patch('/api/content/:productionId/scenes/:sceneId', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.updateScene(req.params.productionId, req.params.sceneId, req.body || {});
+ await this.refreshContentReview(req.params.productionId, 'Scene changes require review before scheduling');
+ return res.json({ success: true, result: this.scenes.decorateScene(result, req.params.productionId) });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code, details: error.details });
+ }
+ });
+
+ this.app.post('/api/content/:productionId/scenes/reorder', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.reorder(req.params.productionId, req.body?.sceneIds);
+ await this.refreshContentReview(req.params.productionId, 'Timeline order changed; rebuild and review before scheduling');
+ return res.json({ success: true, result: result.map(scene => this.scenes.decorateScene(scene, req.params.productionId)) });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code, details: error.details });
+ }
+ });
+
+ this.app.post('/api/content/:productionId/scenes/:sceneId/regenerate', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.regenerate(req.params.productionId, req.params.sceneId, req.body || {});
+ await this.refreshContentReview(req.params.productionId, 'Regenerated scene must be rebuilt and reviewed');
+ return res.status(202).json({ success: true, result: {
+ ...result,
+ scene: this.scenes.decorateScene(result.scene, req.params.productionId)
+ } });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code, details: error.details });
+ }
+ });
+
+ this.app.put(
+ '/api/content/:productionId/scenes/:sceneId/asset',
+ protect,
+ express.raw({ type: ['image/*', 'video/*'], limit: '100mb' }),
+ async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.replaceAsset(req.params.productionId, req.params.sceneId, {
+ buffer: req.body,
+ contentType: req.get('content-type'),
+ filename: req.get('x-file-name'),
+ rightsConfirmed: req.get('x-rights-confirmed') === 'true',
+ containsSyntheticMedia: req.get('x-synthetic-media') === 'true'
+ });
+ await this.refreshContentReview(req.params.productionId, 'Replacement scene asset must be rebuilt and reviewed');
+ return res.json({ success: true, result: this.scenes.decorateScene(result, req.params.productionId) });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code, details: error.details });
+ }
+ }
+ );
+
+ this.app.post('/api/content/:productionId/scenes/rebuild', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Scene repair requires completed setup' });
+ const result = await this.scenes.rebuild(req.params.productionId);
+ await this.refreshContentReview(req.params.productionId, 'Scene repair rebuilt; final approval is required');
+ return res.json({ success: true, result });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code, details: error.details });
+ }
+ });
+
+ this.app.get('/api/content/:productionId/scenes/:sceneId/asset', async (req, res) => {
+ try {
+ const scene = await this.db.getProductionScene(req.params.productionId, req.params.sceneId);
+ if (!scene?.assetPath) return res.status(404).json({ error: 'Scene asset not found' });
+ const resolved = path.resolve(scene.assetPath);
+ const dataRoot = path.resolve(__dirname, 'data');
+ if (!resolved.startsWith(`${dataRoot}${path.sep}`)) return res.status(403).json({ error: 'Scene asset path is not allowed' });
+ await fs.access(resolved);
+ return res.sendFile(resolved);
+ } catch (_error) {
+ return res.status(404).json({ error: 'Scene asset not found' });
+ }
+ });
+
this.app.patch('/api/content/:productionId', protect, async (req, res) => {
try {
const bundle = await this.db.getProductionBundle(req.params.productionId);
@@ -1191,6 +1297,9 @@ class YouTubeAutomationAgent {
const experiment = bundle.editorData?.packagingExperiment;
return {
...bundle,
+ scenes: (bundle.scenes || []).map(scene => this.scenes
+ ? this.scenes.decorateScene(scene, bundle.id)
+ : scene),
assetUrls: {
video: bundle.assets?.finalVideo?.path && !bundle.assets?.finalVideo?.simulated ? `/api/content/${bundle.id}/asset/video` : null,
thumbnail: bundle.assets?.thumbnail?.path ? `/api/content/${bundle.id}/asset/thumbnail` : null,
@@ -1203,6 +1312,24 @@ class YouTubeAutomationAgent {
};
}
+ async refreshContentReview(productionId, reviewNotes) {
+ const bundle = await this.db.getProductionBundle(productionId);
+ if (!bundle) return null;
+ const profile = await this.db.getChannelProfile() || {};
+ const quality = await this.operator.runQualityChecks({
+ ...bundle,
+ scheduledPublishTime: bundle.scheduled_publish_time
+ }, profile);
+ const status = quality.passed ? 'needs_review' : 'needs_attention';
+ return this.db.saveContentReview(productionId, {
+ status,
+ editorData: { ...(bundle.editorData || {}), factChecked: false, rightsConfirmed: false },
+ qualityChecks: quality.checks,
+ reviewNotes: reviewNotes || (quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`),
+ reviewedAt: null
+ });
+ }
+
async approveContent(productionId, input) {
const bundle = await this.db.getProductionBundle(productionId);
if (!bundle) {
diff --git a/test.js b/test.js
index 414440f..e3bec79 100644
--- a/test.js
+++ b/test.js
@@ -27,6 +27,7 @@ class SystemTest {
{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },
{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },
{ name: 'Durable Multi-Provider Video Generation', test: () => this.testVideoProviderLayer() },
+ { name: 'Scene Repair Studio', test: () => this.testSceneRepairStudio() },
{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },
{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },
{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },
@@ -802,6 +803,155 @@ class SystemTest {
this.logger.info('Durable multi-provider video generation test completed successfully');
}
+ async testSceneRepairStudio() {
+ const fs = require('fs').promises;
+ const os = require('os');
+ const sharp = require('sharp');
+ const { SceneRepairService, buildInitialSceneManifest } = require('./utils/scene-repair-service');
+ const { OperatorService } = require('./utils/operator-service');
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-scene-repair-'));
+ const db = new Database();
+ db.dbPath = path.join(directory, 'scenes.db');
+ await db.initialize();
+
+ try {
+ const imagePath = path.join(directory, 'scene.png');
+ const oldVideoPath = path.join(directory, 'old.mp4');
+ await sharp({ create: { width: 320, height: 180, channels: 3, background: '#203a5f' } }).png().toFile(imagePath);
+ await fs.writeFile(oldVideoPath, Buffer.from('previous final video'));
+ const production = {
+ id: `prod_scene_${Date.now()}`,
+ status: 'ready',
+ script: {
+ title: 'Repair one scene',
+ fullScript: 'A complete factual-review-safe script for testing selective scene repair without replacing the entire production.',
+ hook: { text: 'Fix one weak moment without starting over.' },
+ introduction: { greeting: 'Hello.', topicIntro: 'Scene repair matters.', valueProposition: 'Save time and credits.' },
+ mainContent: { sections: [{ title: 'Selective repair', content: 'Keep the scenes that work and replace only the scene that does not.' }] },
+ conclusion: { recap: ['Preserve good work.'], finalThought: 'Review the repaired timeline.' }
+ },
+ seo: { title: 'Repair one scene', description: 'A detailed description of selective scene repair for video production workflows.', tags: ['video', 'repair', 'workflow'] },
+ strategy: { topic: 'Selective scene repair' },
+ assets: {
+ video: { visualAssets: [imagePath] },
+ audio: null,
+ thumbnail: { path: imagePath },
+ finalVideo: { path: oldVideoPath, simulated: false, duration: '1:00', provider: { actualProvider: 'slideshow' } }
+ },
+ timeline: { readyForUpload: new Date().toISOString() },
+ scheduledPublishTime: new Date(Date.now() + 86400000).toISOString(),
+ priority: 50,
+ estimatedDuration: '1:00'
+ };
+ await db.saveProductionData(production);
+ await db.saveProductionSnapshot(production);
+ await db.saveContentReview(production.id, { status: 'needs_review', editorData: {}, qualityChecks: [] });
+ await db.saveContentProvenance(production.id, {
+ sources: [], claims: [], containsSyntheticMedia: false, status: 'not_required',
+ summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }
+ });
+
+ const manifest = buildInitialSceneManifest(production, { actualProvider: 'slideshow', model: 'local-ffmpeg' });
+ if (manifest.length < 3 || manifest.some(scene => scene.assetPath !== imagePath)) {
+ throw new Error('Initial scene manifest did not preserve the script structure and visual assets');
+ }
+ await db.replaceProductionScenes(production.id, manifest);
+ const roundTrip = await db.listProductionScenes(production.id);
+ if (roundTrip.length !== manifest.length || roundTrip[0].scriptText !== manifest[0].scriptText) {
+ throw new Error('Scene manifest did not round-trip through SQLite');
+ }
+
+ const fakeProvider = {
+ id: 'seedance', model: 'seedance-test',
+ normalizeRequest: request => ({ ...request, duration: Math.min(4, Number(request.duration || 4)) })
+ };
+ const fakeGenerator = {
+ mediaGeneration: {
+ settings: async () => ({ provider: 'seedance', order: ['seedance'], clipDuration: 4, resolution: '720p', aspectRatio: '16:9' }),
+ registry: { select: () => fakeProvider, get: () => fakeProvider },
+ generateClip: async ({ outputPath }) => {
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, Buffer.from('generated scene video'));
+ return { outputPath, task: { model: fakeProvider.model, external_task_id: 'scene-task-1' } };
+ },
+ isValidVideo: async () => true
+ },
+ generateVisualAssets: async () => [imagePath],
+ generateTTSAudio: async (_text, outputPath) => { await fs.writeFile(outputPath, Buffer.from('scene narration')); return outputPath; },
+ isUsableAudioFile: async filePath => Boolean(filePath && await fs.stat(filePath).then(stat => stat.size > 0).catch(() => false)),
+ renderMediaTimeline: async (_segments, outputPath) => { await fs.writeFile(outputPath, Buffer.from('rebuilt visual timeline')); return outputPath; },
+ addAudioToVideo: async (videoPath, _audioPath, outputPath) => { await fs.copyFile(videoPath, outputPath); return outputPath; }
+ };
+ const service = new SceneRepairService(db, fakeGenerator, { dataRoot: directory, logger: this.logger });
+ const first = roundTrip[0];
+ const edited = await service.updateScene(production.id, first.id, {
+ scriptText: `${first.scriptText} Updated narration.`, prompt: `${first.prompt} Brighter composition.`, factualChange: false
+ });
+ if (edited.status !== 'visual_stale' || edited.narrationStatus !== 'stale' || edited.revision !== first.revision + 1) {
+ throw new Error('Scene edits did not invalidate only the scene rebuild and narration state');
+ }
+
+ const quality = await new OperatorService(db).runQualityChecks({ ...(await db.getProductionBundle(production.id)), scenes: await db.listProductionScenes(production.id) }, {});
+ if (quality.passed || !quality.blockingFailures.includes('scene_integrity')) {
+ throw new Error('Approval quality checks did not block an unrepaired scene');
+ }
+ const estimate = await service.regenerationEstimate(production.id, first.id);
+ if (!estimate.paid || estimate.provider !== 'seedance') throw new Error('Paid scene estimate did not expose provider billing risk');
+ let paidBlocked = false;
+ try {
+ await service.regenerate(production.id, first.id, { regenerateNarration: true });
+ } catch (error) {
+ paidBlocked = error.code === 'PAID_CONFIRMATION_REQUIRED';
+ }
+ if (!paidBlocked) throw new Error('Paid scene regeneration started without explicit confirmation');
+ const regenerated = await service.regenerate(production.id, first.id, { confirmPaid: true, regenerateNarration: true });
+ if (regenerated.scene.status !== 'needs_rebuild' || regenerated.scene.externalTaskId !== 'scene-task-1' || regenerated.scene.narrationStatus !== 'current') {
+ throw new Error('Confirmed selective regeneration did not persist visual and narration evidence');
+ }
+
+ const second = roundTrip[1];
+ const replacement = await sharp({ create: { width: 320, height: 180, channels: 3, background: '#ad3d45' } }).png().toBuffer();
+ let rightsBlocked = false;
+ try {
+ await service.replaceAsset(production.id, second.id, { buffer: replacement, contentType: 'image/png', filename: 'replacement.png' });
+ } catch (error) {
+ rightsBlocked = error.code === 'RIGHTS_CONFIRMATION_REQUIRED';
+ }
+ if (!rightsBlocked) throw new Error('Uploaded scene asset bypassed rights confirmation');
+ const replaced = await service.replaceAsset(production.id, second.id, {
+ buffer: replacement, contentType: 'image/png', filename: 'replacement.png', rightsConfirmed: true
+ });
+ if (replaced.assetOrigin !== 'uploaded' || !replaced.rightsConfirmed || replaced.status !== 'needs_rebuild') {
+ throw new Error('Replacement asset evidence did not persist');
+ }
+
+ const ordered = await service.reorder(production.id, (await db.listProductionScenes(production.id)).map(scene => scene.id).reverse());
+ if (ordered[0].id === first.id) throw new Error('Scene timeline order did not persist');
+ const rebuilt = await service.rebuild(production.id);
+ const finalBundle = await db.getProductionBundle(production.id);
+ if (!rebuilt.finalVideo || finalBundle.assets.finalVideo.previousPath !== oldVideoPath || finalBundle.scenes.some(scene => scene.status !== 'ready')) {
+ throw new Error('Scene rebuild did not preserve the prior video and finalize every scene');
+ }
+ const revisions = await db.listProductionSceneRevisions(production.id);
+ for (const action of ['edit', 'regenerate', 'replace_asset', 'reorder', 'rebuild']) {
+ if (!revisions.some(revision => revision.action === action)) throw new Error(`Scene revision history is missing ${action}`);
+ }
+
+ const locked = await service.updateScene(production.id, ordered[0].id, { locked: true });
+ let lockBlocked = false;
+ try {
+ await service.updateScene(production.id, locked.id, { prompt: 'Unauthorized locked edit' });
+ } catch (error) {
+ lockBlocked = error.status === 409;
+ }
+ if (!lockBlocked) throw new Error('Locked scene accepted an edit');
+ } finally {
+ await db.close();
+ await fs.rm(directory, { recursive: true, force: true });
+ }
+ this.logger.info('Scene Repair Studio test completed successfully');
+ }
+
async testProvenanceDesk() {
const fs = require('fs').promises;
const os = require('os');
diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.js
index 783f2e2..6765ff6 100644
--- a/utils/ai-video-generator.js
+++ b/utils/ai-video-generator.js
@@ -300,14 +300,18 @@ class AIVideoGenerator {
model: generated.model,
mode: generated.settings.mode,
generatedSeconds: generated.clips.reduce((total, clip) => total + clip.duration, 0),
- tasks: generated.clips.map(clip => ({ scene: clip.index, taskId: clip.taskId, provider: clip.provider, model: clip.model }))
+ tasks: generated.clips.map(clip => ({ scene: clip.index, taskId: clip.taskId, provider: clip.provider, model: clip.model })),
+ scenes: generated.clips.map(clip => ({
+ index: clip.index, label: clip.label, prompt: clip.prompt, duration: clip.duration,
+ path: clip.path, taskId: clip.taskId, provider: clip.provider, model: clip.model
+ }))
};
return produced;
}
}
const produced = await this.generateSlideshowVideo(script, visualAssets, audioPath, outputPath);
- this.lastVideoResult = { requestedProvider: 'slideshow', actualProvider: 'slideshow', model: 'local-ffmpeg', mode: 'slideshow', generatedSeconds: 0, tasks: [] };
+ this.lastVideoResult = { requestedProvider: 'slideshow', actualProvider: 'slideshow', model: 'local-ffmpeg', mode: 'slideshow', generatedSeconds: 0, tasks: [], scenes: [] };
return produced;
} catch (error) {
// The Logger's console line only shows the message string, so put the real
@@ -320,7 +324,7 @@ class AIVideoGenerator {
this.lastVideoResult = {
requestedProvider: this.lastVideoResult?.requestedProvider || 'configured-provider',
actualProvider: 'slideshow', model: 'local-ffmpeg', mode: 'fallback', generatedSeconds: 0,
- fallbackReason: reason, tasks: []
+ fallbackReason: reason, tasks: [], scenes: []
};
return produced;
} catch (fallbackError) {
@@ -328,7 +332,7 @@ class AIVideoGenerator {
const produced = await this.simulateVideoGeneration(script, visualAssets, audioPath, outputPath);
this.lastVideoResult = {
requestedProvider: 'configured-provider', actualProvider: 'simulation', model: null,
- mode: 'simulation', generatedSeconds: 0, fallbackReason: `${reason}; ${fallbackError.message}`, tasks: []
+ mode: 'simulation', generatedSeconds: 0, fallbackReason: `${reason}; ${fallbackError.message}`, tasks: [], scenes: []
};
return produced;
}
@@ -358,7 +362,7 @@ class AIVideoGenerator {
const args = ['-y'];
for (const segment of segments) {
if (segment.type === 'image') args.push('-loop', '1', '-t', Number(segment.duration).toFixed(2), '-framerate', '30', '-i', segment.path);
- else args.push('-i', segment.path);
+ else args.push('-stream_loop', '-1', '-i', segment.path);
}
const filters = segments.map((segment, index) =>
`[${index}:v]scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black,fps=30,format=yuv420p,trim=duration=${Number(segment.duration).toFixed(2)},setpts=PTS-STARTPTS[v${index}]`
diff --git a/utils/operator-service.js b/utils/operator-service.js
index 28b4175..d118b94 100644
--- a/utils/operator-service.js
+++ b/utils/operator-service.js
@@ -30,7 +30,9 @@ class OperatorService {
this.check('thumbnail', Boolean(thumbnail?.path),
thumbnail?.path ? 'Thumbnail asset is present' : 'Thumbnail asset is missing', false),
this.check('video', Boolean(finalVideo?.path && !finalVideo?.simulated),
- finalVideo?.simulated ? 'Only a simulated video was produced' : 'Final MP4 is missing')
+ finalVideo?.simulated
+ ? 'Only a simulated video was produced'
+ : finalVideo?.path ? 'Final MP4 is ready' : 'Final MP4 is missing')
];
const topic = String(production.strategy?.topic || '').trim();
@@ -71,6 +73,22 @@ class OperatorService {
? 'No externally verifiable factual claims were declared'
: `${unresolved} factual claim${unresolved === 1 ? '' : 's'} still require evidence review`));
+ const scenes = production.scenes || [];
+ if (scenes.length) {
+ const invalidScenes = scenes.filter(scene =>
+ !scene.assetPath || ['missing_asset', 'failed', 'generating', 'needs_rebuild', 'visual_stale'].includes(scene.status) || scene.narrationStatus === 'stale'
+ );
+ const unlicensedUploads = scenes.filter(scene => scene.assetOrigin === 'uploaded' && !scene.rightsConfirmed);
+ checks.push(this.check('scene_integrity', invalidScenes.length === 0,
+ invalidScenes.length === 0
+ ? `${scenes.length} scene${scenes.length === 1 ? '' : 's'} are rebuilt and current`
+ : `${invalidScenes.length} scene${invalidScenes.length === 1 ? '' : 's'} still require repair or rebuild`));
+ checks.push(this.check('scene_rights', unlicensedUploads.length === 0,
+ unlicensedUploads.length === 0
+ ? 'Replacement scene assets have rights confirmation'
+ : `${unlicensedUploads.length} uploaded scene asset${unlicensedUploads.length === 1 ? '' : 's'} lack rights confirmation`));
+ }
+
const blockingFailures = checks.filter(check => check.blocking && !check.passed);
return {
passed: blockingFailures.length === 0,
diff --git a/utils/scene-repair-service.js b/utils/scene-repair-service.js
new file mode 100644
index 0000000..e700ba3
--- /dev/null
+++ b/utils/scene-repair-service.js
@@ -0,0 +1,503 @@
+const crypto = require('crypto');
+const fs = require('fs').promises;
+const path = require('path');
+const sharp = require('sharp');
+const { runFFmpeg } = require('./ffmpeg');
+const { ProvenanceService } = require('./provenance-service');
+
+const VIDEO_EXTENSIONS = new Set(['.mp4']);
+const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
+
+function textFromSection(section = {}) {
+ if (typeof section.content === 'string') return section.content;
+ if (Array.isArray(section.content)) return section.content.filter(item => typeof item === 'string' && !item.startsWith('[')).join(' ');
+ if (Array.isArray(section.items)) return section.items.map(item => `${item.title || ''}. ${item.description || ''}`).join(' ');
+ if (Array.isArray(section.steps)) return section.steps.map(item => `${item.title || ''}. ${item.description || ''}`).join(' ');
+ return '';
+}
+
+function scriptScenes(script = {}) {
+ const scenes = [];
+ if (script.hook?.text || script.title) {
+ scenes.push({
+ label: 'Hook',
+ scriptText: script.hook?.text || script.title,
+ prompt: `${script.hook?.text || script.title}. Cinematic opening shot, clear subject, intentional camera movement, no captions or on-screen text.`
+ });
+ }
+ if (script.introduction) {
+ const scriptText = [
+ script.introduction.greeting,
+ script.introduction.topicIntro,
+ script.introduction.valueProposition,
+ script.introduction.credibility
+ ].filter(Boolean).join(' ');
+ if (scriptText) scenes.push({
+ label: 'Introduction', scriptText,
+ prompt: `${scriptText}. Establishing visual, clear subject, coherent lighting, no captions or on-screen text.`
+ });
+ }
+ for (const [index, section] of (script.mainContent?.sections || []).entries()) {
+ const scriptText = textFromSection(section);
+ scenes.push({
+ label: section.title || `Scene ${index + 1}`,
+ scriptText,
+ prompt: `${section.title || ''}. ${scriptText}`.trim() + '. Cinematic explanatory B-roll, natural motion, coherent lighting, no captions or on-screen text.'
+ });
+ }
+ if (script.conclusion) {
+ const scriptText = [...(script.conclusion.recap || []), script.conclusion.finalThought].filter(Boolean).join(' ');
+ if (scriptText) scenes.push({
+ label: 'Conclusion', scriptText,
+ prompt: `${scriptText}. Memorable cinematic closing shot, no captions or on-screen text.`
+ });
+ }
+ if (script.callToAction) {
+ const scriptText = Object.values(script.callToAction).filter(value => typeof value === 'string').join(' ');
+ if (scriptText) scenes.push({
+ label: 'Call to action', scriptText,
+ prompt: `${scriptText}. Clean closing visual with open composition, no captions or on-screen text.`
+ });
+ }
+ return scenes.length ? scenes : [{ label: script.title || 'Video', scriptText: script.fullScript || '', prompt: script.title || 'Video scene' }];
+}
+
+function durationSeconds(value, fallback = 60) {
+ if (Number.isFinite(Number(value))) return Math.max(1, Number(value));
+ const parts = String(value || '').split(':').map(Number);
+ if (parts.length === 2 && parts.every(Number.isFinite)) return Math.max(1, parts[0] * 60 + parts[1]);
+ if (parts.length === 3 && parts.every(Number.isFinite)) return Math.max(1, parts[0] * 3600 + parts[1] * 60 + parts[2]);
+ return fallback;
+}
+
+function buildInitialSceneManifest(production = {}, providerResult = {}) {
+ const blueprints = scriptScenes(production.script || {});
+ const totalDuration = durationSeconds(production.estimatedDuration || production.assets?.finalVideo?.duration, Math.max(30, blueprints.length * 8));
+ const wordCounts = blueprints.map(scene => Math.max(8, scene.scriptText.trim().split(/\s+/).filter(Boolean).length));
+ const totalWords = wordCounts.reduce((sum, count) => sum + count, 0);
+ const generated = providerResult.scenes || [];
+ const visualAssets = (production.assets?.video?.visualAssets || []).filter(Boolean);
+
+ return blueprints.map((scene, position) => {
+ const generatedScene = generated.find(item => String(item.label || '').toLowerCase() === scene.label.toLowerCase()) || generated[position];
+ const imagePath = visualAssets[position % Math.max(1, visualAssets.length)] || null;
+ const assetPath = generatedScene?.path || imagePath;
+ const assetType = generatedScene?.path ? 'video' : imagePath ? 'image' : 'missing';
+ const provider = generatedScene?.provider || (assetType === 'image' ? 'image-provider' : providerResult.actualProvider || 'slideshow');
+ return {
+ id: `scene_${crypto.randomUUID()}`,
+ position,
+ ...scene,
+ duration: Math.max(2, Number(((wordCounts[position] / totalWords) * totalDuration).toFixed(2))),
+ assetType,
+ assetOrigin: 'generated',
+ assetPath,
+ audioPath: null,
+ provider,
+ model: generatedScene?.model || providerResult.model || null,
+ externalTaskId: generatedScene?.taskId || null,
+ status: assetPath ? 'ready' : 'missing_asset',
+ narrationStatus: production.assets?.audio?.simulated ? 'unavailable' : 'current',
+ revision: 1,
+ locked: false,
+ rightsConfirmed: true,
+ provenanceSourceIds: [],
+ containsSyntheticMedia: Boolean(generatedScene?.path && !['slideshow', 'simulation'].includes(provider)),
+ estimatedCost: generatedScene?.path ? { unit: 'generated_seconds', amount: generatedScene.duration || 0, pricing: 'provider-priced' } : {},
+ actualCost: {}
+ };
+ });
+}
+
+class SceneRepairService {
+ constructor(db, videoGenerator, options = {}) {
+ this.db = db;
+ this.videoGenerator = videoGenerator;
+ this.mediaGeneration = videoGenerator?.mediaGeneration;
+ this.logger = options.logger || { info() {}, warn() {}, error() {} };
+ this.dataRoot = options.dataRoot || path.join(__dirname, '..', 'data');
+ }
+
+ async ensureManifest(bundle) {
+ if (bundle.scenes?.length) return bundle.scenes;
+ const scenes = buildInitialSceneManifest(bundle, bundle.assets?.finalVideo?.provider || {});
+ await this.initializeAudioSegments(bundle, scenes);
+ return this.db.replaceProductionScenes(bundle.id, scenes);
+ }
+
+ async initializeProduction(production, providerResult = {}) {
+ const scenes = buildInitialSceneManifest(production, providerResult);
+ await this.initializeAudioSegments(production, scenes);
+ const saved = await this.db.replaceProductionScenes(production.id, scenes);
+ production.assets.sceneManifest = { count: saved.length, version: 1, updatedAt: new Date().toISOString() };
+ return saved;
+ }
+
+ async initializeAudioSegments(production, scenes) {
+ const audioPath = production.assets?.audio?.path;
+ if (!await this.videoGenerator?.isUsableAudioFile?.(audioPath)) return scenes;
+ const directory = path.join(this.dataRoot, 'audio', 'scenes', production.id);
+ await fs.mkdir(directory, { recursive: true });
+ let start = 0;
+ for (const scene of scenes) {
+ const output = path.join(directory, `${String(scene.position).padStart(3, '0')}_r1.mp3`);
+ try {
+ await runFFmpeg(['-y', '-ss', start.toFixed(2), '-t', Number(scene.duration).toFixed(2), '-i', audioPath, '-vn', '-c:a', 'libmp3lame', output]);
+ scene.audioPath = output;
+ } catch (error) {
+ this.logger.warn(`Could not split narration for scene ${scene.position + 1}: ${error.message}`);
+ scene.audioPath = null;
+ }
+ start += Number(scene.duration);
+ }
+ return scenes;
+ }
+
+ async getEditableBundle(productionId) {
+ const bundle = await this.db.getProductionBundle(productionId);
+ if (!bundle) throw this.error('Content not found', 404);
+ if (bundle.schedule || bundle.review_status === 'approved') {
+ throw this.error('Scene repair is locked after content is approved or scheduled', 409);
+ }
+ if (!bundle.scenes?.length) {
+ bundle.scenes = await this.ensureManifest(bundle);
+ }
+ return bundle;
+ }
+
+ async updateScene(productionId, sceneId, input = {}) {
+ const bundle = await this.getEditableBundle(productionId);
+ const scene = bundle.scenes.find(item => item.id === sceneId);
+ if (!scene) throw this.error('Scene not found', 404);
+ if (scene.locked && input.locked !== false) throw this.error('Unlock this scene before editing it', 409);
+
+ const verifiedSourceIds = new Set((bundle.provenance?.sources || []).filter(source => source.status === 'verified').map(source => source.id));
+ const provenanceSourceIds = input.provenanceSourceIds === undefined
+ ? scene.provenanceSourceIds
+ : [...new Set(this.array(input.provenanceSourceIds).filter(id => verifiedSourceIds.has(id)))];
+ const scriptText = input.scriptText === undefined ? scene.scriptText : this.text(input.scriptText, 10000, 'Scene narration');
+ const prompt = input.prompt === undefined ? scene.prompt : this.text(input.prompt, 2000, 'Scene prompt');
+ const label = input.label === undefined ? scene.label : this.text(input.label, 120, 'Scene label');
+ const duration = input.duration === undefined ? scene.duration : Number(input.duration);
+ if (!Number.isFinite(duration) || duration < 2 || duration > 600) throw this.error('Scene duration must be between 2 and 600 seconds', 400);
+ const scriptChanged = scriptText !== scene.scriptText;
+ const promptChanged = prompt !== scene.prompt;
+ const durationChanged = duration !== scene.duration;
+ const next = await this.db.updateProductionScene(productionId, sceneId, {
+ label, scriptText, prompt, duration, provenanceSourceIds,
+ locked: input.locked === undefined ? scene.locked : input.locked === true,
+ narrationStatus: scriptChanged ? 'stale' : scene.narrationStatus,
+ status: promptChanged ? 'visual_stale' : scriptChanged || durationChanged ? 'needs_rebuild' : scene.status,
+ revision: scriptChanged || promptChanged || durationChanged ? scene.revision + 1 : scene.revision
+ });
+
+ if (scriptChanged && input.factualChange !== false) {
+ await this.markSceneClaimForReview(bundle, next, verifiedSourceIds);
+ }
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'edit', before: scene, after: next,
+ costEvidence: { billed: false }
+ });
+ return next;
+ }
+
+ async markSceneClaimForReview(bundle, scene, verifiedSourceIds) {
+ const provenance = bundle.provenance || { sources: [], claims: [], containsSyntheticMedia: false };
+ const id = `scene_claim_${scene.id}_r${scene.revision}`;
+ const sourceIds = scene.provenanceSourceIds.filter(sourceId => verifiedSourceIds.has(sourceId));
+ const claims = [...(provenance.claims || []).filter(claim => !String(claim.id).startsWith(`scene_claim_${scene.id}_`)), {
+ id,
+ text: scene.scriptText,
+ riskLevel: 'standard',
+ sourceIds,
+ status: sourceIds.length ? 'supported' : 'pending',
+ notes: `Narration changed in ${scene.label}; review before approval.`
+ }];
+ await new ProvenanceService(this.db).review(bundle.id, {
+ sources: provenance.sources || [], claims,
+ containsSyntheticMedia: provenance.containsSyntheticMedia
+ });
+ }
+
+ async reorder(productionId, orderedIds) {
+ const bundle = await this.getEditableBundle(productionId);
+ if (bundle.scenes.some(scene => scene.locked)) throw this.error('Unlock every scene before changing timeline order', 409);
+ const before = bundle.scenes;
+ const after = await this.db.reorderProductionScenes(productionId, this.array(orderedIds));
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId: after[0].id, action: 'reorder', before: { order: before.map(scene => scene.id) },
+ after: { order: after.map(scene => scene.id) }, costEvidence: { billed: false }
+ });
+ return after;
+ }
+
+ async regenerationEstimate(productionId, sceneId, input = {}) {
+ const bundle = await this.getEditableBundle(productionId);
+ const scene = bundle.scenes.find(item => item.id === sceneId);
+ if (!scene) throw this.error('Scene not found', 404);
+ const settings = await this.mediaGeneration?.settings?.() || { provider: 'slideshow', order: [], clipDuration: scene.duration };
+ const requestedProvider = input.provider || (scene.provider && scene.provider !== 'image-provider' ? scene.provider : settings.provider);
+ const provider = this.mediaGeneration?.registry?.select(requestedProvider, settings.order, { duration: Math.min(scene.duration, settings.clipDuration || scene.duration) });
+ const paid = Boolean(provider && provider.id !== 'slideshow');
+ const generatedSeconds = paid ? provider.normalizeRequest({ duration: Math.min(scene.duration, settings.clipDuration || scene.duration) }).duration : 0;
+ return {
+ provider: provider?.id || 'slideshow', model: provider?.model || 'local-image', paid,
+ generatedSeconds, pricing: paid ? 'provider-priced' : 'no video-provider charge',
+ warning: paid ? 'This regeneration can consume provider credits. The provider invoice is authoritative.' : null
+ };
+ }
+
+ async regenerate(productionId, sceneId, input = {}) {
+ const bundle = await this.getEditableBundle(productionId);
+ const scene = bundle.scenes.find(item => item.id === sceneId);
+ if (!scene) throw this.error('Scene not found', 404);
+ if (scene.locked) throw this.error('Unlock this scene before regenerating it', 409);
+ const estimate = await this.regenerationEstimate(productionId, sceneId, input);
+ if (estimate.paid && input.confirmPaid !== true) throw this.error('Confirm the paid scene regeneration before starting it', 409, 'PAID_CONFIRMATION_REQUIRED', estimate);
+
+ const before = scene;
+ let visual = {};
+ let narration = {};
+ try {
+ await this.db.updateProductionScene(productionId, sceneId, { status: 'generating' });
+ if (estimate.paid) {
+ const provider = this.mediaGeneration.registry.get(estimate.provider);
+ const settings = await this.mediaGeneration.settings();
+ const request = provider.normalizeRequest({
+ prompt: scene.prompt, duration: estimate.generatedSeconds, resolution: settings.resolution,
+ aspectRatio: settings.aspectRatio, generateAudio: false, referenceImages: []
+ });
+ const outputPath = path.join(this.dataRoot, 'videos', 'scenes', `${productionId}_${scene.id}_r${scene.revision + 1}.mp4`);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ const result = await this.mediaGeneration.generateClip({
+ jobId: `repair_${productionId}_${scene.id}_${scene.revision + 1}`,
+ productionId, scene: { index: scene.position, prompt: scene.prompt }, provider, outputPath, request
+ });
+ visual = {
+ assetType: 'video', assetOrigin: 'generated', assetPath: result.outputPath,
+ provider: provider.id, model: result.task.model, externalTaskId: result.task.external_task_id,
+ containsSyntheticMedia: true
+ };
+ } else {
+ const assets = await this.videoGenerator.generateVisualAssets(scene.prompt, 'ethereal', 1);
+ const assetPath = assets[0];
+ if (!assetPath || !IMAGE_EXTENSIONS.has(path.extname(assetPath).toLowerCase()) || !await this.pathExists(assetPath)) {
+ throw this.error('No real replacement image was generated; configure an image provider or upload an asset', 422, 'SCENE_ASSET_UNAVAILABLE');
+ }
+ visual = { assetType: 'image', assetOrigin: 'generated', assetPath, provider: 'image-provider', model: null, externalTaskId: null, containsSyntheticMedia: true };
+ }
+
+ if (scene.narrationStatus === 'stale' || input.regenerateNarration === true) {
+ const audioPath = path.join(this.dataRoot, 'audio', 'scenes', productionId, `${String(scene.position).padStart(3, '0')}_r${scene.revision + 1}.mp3`);
+ await fs.mkdir(path.dirname(audioPath), { recursive: true });
+ const generatedPath = await this.videoGenerator.generateTTSAudio(scene.scriptText, audioPath);
+ if (!await this.videoGenerator.isUsableAudioFile(generatedPath)) {
+ throw this.error('Narration regeneration returned a simulation; configure a live TTS provider before rebuilding edited narration', 422, 'NARRATION_UNAVAILABLE');
+ }
+ narration = { audioPath: generatedPath, narrationStatus: 'current' };
+ }
+
+ const next = await this.db.updateProductionScene(productionId, sceneId, {
+ ...visual, ...narration, status: 'needs_rebuild', revision: scene.revision + 1,
+ estimatedCost: estimate,
+ actualCost: { generatedSeconds: estimate.generatedSeconds, provider: estimate.provider, amount: null, currency: null, invoiceRequired: estimate.paid }
+ });
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'regenerate', before, after: next,
+ costEvidence: next.actualCost
+ });
+ return { scene: next, estimate };
+ } catch (error) {
+ await this.db.updateProductionScene(productionId, sceneId, { status: 'failed' }).catch(() => {});
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'regenerate', status: 'failed', before,
+ after: {}, costEvidence: estimate, error: error.message
+ }).catch(() => {});
+ throw error;
+ }
+ }
+
+ async replaceAsset(productionId, sceneId, file = {}) {
+ const bundle = await this.getEditableBundle(productionId);
+ const scene = bundle.scenes.find(item => item.id === sceneId);
+ if (!scene) throw this.error('Scene not found', 404);
+ if (scene.locked) throw this.error('Unlock this scene before replacing its asset', 409);
+ if (file.rightsConfirmed !== true) throw this.error('Confirm that you have rights to the replacement asset', 400, 'RIGHTS_CONFIRMATION_REQUIRED');
+ if (!Buffer.isBuffer(file.buffer) || !file.buffer.length) throw this.error('Replacement asset is empty', 400);
+
+ const contentType = String(file.contentType || '').toLowerCase();
+ const assetType = contentType.startsWith('image/') ? 'image' : contentType.startsWith('video/') ? 'video' : null;
+ if (!assetType) throw this.error('Replacement assets must be an image or video', 415);
+ const suppliedExtension = path.extname(String(file.filename || '')).toLowerCase();
+ const extension = suppliedExtension || (assetType === 'video' ? '.mp4' : '.png');
+ if ((assetType === 'video' && !VIDEO_EXTENSIONS.has(extension)) || (assetType === 'image' && !IMAGE_EXTENSIONS.has(extension))) {
+ throw this.error('Replacement asset file type is not supported', 415);
+ }
+ const directory = path.join(this.dataRoot, 'scene-assets', productionId);
+ const outputPath = path.join(directory, `${scene.id}_r${scene.revision + 1}${extension}`);
+ await fs.mkdir(directory, { recursive: true });
+ await fs.writeFile(outputPath, file.buffer);
+ try {
+ if (assetType === 'video') {
+ if (!await this.mediaGeneration?.isValidVideo?.(outputPath)) throw new Error('Video is not a valid, decodable MP4-compatible asset');
+ } else {
+ await sharp(outputPath).metadata();
+ }
+ } catch (error) {
+ await fs.unlink(outputPath).catch(() => {});
+ throw this.error(error.message || 'Replacement asset is invalid', 422);
+ }
+
+ const next = await this.db.updateProductionScene(productionId, sceneId, {
+ assetType, assetOrigin: 'uploaded', assetPath: outputPath, provider: 'operator-upload', model: null,
+ externalTaskId: null, rightsConfirmed: true, containsSyntheticMedia: file.containsSyntheticMedia === true,
+ status: 'needs_rebuild', revision: scene.revision + 1,
+ estimatedCost: {}, actualCost: { billed: false }
+ });
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'replace_asset', before: scene, after: next,
+ costEvidence: { billed: false }
+ });
+ return next;
+ }
+
+ async rebuild(productionId) {
+ const bundle = await this.getEditableBundle(productionId);
+ const scenes = await this.db.listProductionScenes(productionId);
+ if (!scenes.length) throw this.error('No scene manifest is available', 409);
+ const missing = [];
+ for (const scene of scenes) {
+ if (scene.narrationStatus === 'stale') missing.push(`${scene.label}: narration is stale`);
+ if (scene.status === 'visual_stale') missing.push(`${scene.label}: visual prompt changed but the asset was not regenerated or replaced`);
+ if (['failed', 'generating', 'missing_asset'].includes(scene.status)) missing.push(`${scene.label}: scene status is ${scene.status.replaceAll('_', ' ')}`);
+ if (!scene.assetPath || !await this.pathExists(scene.assetPath)) missing.push(`${scene.label}: visual asset is missing`);
+ if (scene.assetOrigin === 'uploaded' && !scene.rightsConfirmed) missing.push(`${scene.label}: media rights are not confirmed`);
+ }
+ if (missing.length) throw this.error(`Cannot rebuild: ${missing.join('; ')}`, 409, 'SCENE_REBUILD_BLOCKED', { blockers: missing });
+
+ const timestamp = Date.now();
+ const visualPath = path.join(this.dataRoot, 'videos', `${productionId}_repair_${timestamp}_visual.mp4`);
+ const finalPath = path.join(this.dataRoot, 'videos', `${productionId}_repair_${timestamp}.mp4`);
+ const captionsPath = path.join(this.dataRoot, 'captions', `${productionId}_repair_${timestamp}.srt`);
+ await fs.mkdir(path.dirname(finalPath), { recursive: true });
+ await fs.mkdir(path.dirname(captionsPath), { recursive: true });
+ await this.videoGenerator.renderMediaTimeline(scenes.map(scene => ({
+ type: scene.assetType, path: scene.assetPath, duration: scene.duration
+ })), visualPath);
+
+ const audioPath = await this.rebuildNarration(productionId, scenes, bundle.assets?.audio?.path, timestamp);
+ await this.videoGenerator.addAudioToVideo(visualPath, audioPath, finalPath);
+ await fs.unlink(visualPath).catch(() => {});
+ await fs.writeFile(captionsPath, this.buildSRT(scenes));
+ const stats = await fs.stat(finalPath);
+ const previousPath = bundle.assets?.finalVideo?.path || null;
+ const containsSyntheticMedia = scenes.some(scene => scene.containsSyntheticMedia);
+ const assets = {
+ ...bundle.assets,
+ audio: audioPath ? { ...(bundle.assets?.audio || {}), path: audioPath, sceneMixed: scenes.every(scene => scene.audioPath) } : bundle.assets?.audio,
+ captions: { path: captionsPath, format: 'srt', language: 'en', autoGenerated: true, sceneAware: true },
+ finalVideo: {
+ ...(bundle.assets?.finalVideo || {}), path: finalPath, previousPath, fileSize: stats.size,
+ duration: scenes.reduce((sum, scene) => sum + scene.duration, 0), simulated: false,
+ provider: { actualProvider: 'scene-repair', model: 'mixed-assets', scenes: scenes.length }
+ },
+ sceneManifest: { count: scenes.length, version: 1, updatedAt: new Date().toISOString() }
+ };
+ const timeline = { ...bundle.timeline, sceneRepairAt: new Date().toISOString(), captionsGenerated: new Date().toISOString(), readyForUpload: new Date().toISOString() };
+ await this.db.updateProductionData({
+ id: productionId, status: 'ready', assets, timeline,
+ scheduledPublishTime: bundle.scheduled_publish_time, priority: bundle.priority
+ });
+ for (const scene of scenes) await this.db.updateProductionScene(productionId, scene.id, { status: 'ready' });
+ if (containsSyntheticMedia && bundle.provenance && !bundle.provenance.containsSyntheticMedia) {
+ await this.db.saveContentProvenance(productionId, { ...bundle.provenance, containsSyntheticMedia: true, reviewedAt: null });
+ }
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId: scenes[0].id, action: 'rebuild', before: { finalVideo: previousPath },
+ after: { finalVideo: finalPath, captions: captionsPath },
+ costEvidence: { billed: false, reusedScenes: scenes.length }
+ });
+ return { productionId, finalVideo: finalPath, previousVideo: previousPath, captions: captionsPath, scenes: scenes.length };
+ }
+
+ async rebuildNarration(productionId, scenes, fallbackAudioPath, timestamp) {
+ if (!scenes.every(scene => scene.audioPath && scene.narrationStatus === 'current')) {
+ return fallbackAudioPath;
+ }
+ const usable = [];
+ for (const scene of scenes) usable.push(await this.pathExists(scene.audioPath));
+ if (usable.some(value => !value)) return fallbackAudioPath;
+ const outputPath = path.join(this.dataRoot, 'audio', `${productionId}_scene_mix_${timestamp}.m4a`);
+ const args = ['-y'];
+ for (const scene of scenes) args.push('-i', scene.audioPath);
+ const filters = scenes.map((scene, index) => `[${index}:a]aresample=48000,apad,atrim=duration=${Number(scene.duration).toFixed(2)},asetpts=PTS-STARTPTS[a${index}]`);
+ filters.push(`${scenes.map((_, index) => `[a${index}]`).join('')}concat=n=${scenes.length}:v=0:a=1[aout]`);
+ args.push('-filter_complex', filters.join(';'), '-map', '[aout]', '-c:a', 'aac', outputPath);
+ await runFFmpeg(args);
+ return outputPath;
+ }
+
+ buildSRT(scenes) {
+ const time = seconds => {
+ const ms = Math.max(0, Math.round(seconds * 1000));
+ const hours = Math.floor(ms / 3600000);
+ const minutes = Math.floor((ms % 3600000) / 60000);
+ const secs = Math.floor((ms % 60000) / 1000);
+ const millis = ms % 1000;
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')},${String(millis).padStart(3, '0')}`;
+ };
+ let cursor = 0;
+ let index = 1;
+ const blocks = [];
+ for (const scene of scenes) {
+ const words = scene.scriptText.trim().split(/\s+/).filter(Boolean);
+ const groups = [];
+ for (let offset = 0; offset < words.length; offset += 8) groups.push(words.slice(offset, offset + 8).join(' '));
+ const duration = Number(scene.duration);
+ const perGroup = groups.length ? duration / groups.length : duration;
+ for (const group of groups) {
+ blocks.push(`${index++}\n${time(cursor)} --> ${time(cursor + perGroup)}\n${group}`);
+ cursor += perGroup;
+ }
+ if (!groups.length) cursor += duration;
+ }
+ return blocks.join('\n\n') + (blocks.length ? '\n' : '');
+ }
+
+ decorateScene(scene, productionId) {
+ return {
+ ...scene,
+ assetUrl: scene.assetPath ? `/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(scene.id)}/asset?v=${scene.revision}` : null
+ };
+ }
+
+ text(value, limit, label) {
+ const output = String(value || '').trim();
+ if (!output) throw this.error(`${label} is required`, 400);
+ if (output.length > limit) throw this.error(`${label} must be ${limit.toLocaleString()} characters or less`, 400);
+ return output;
+ }
+
+ array(value) {
+ return Array.isArray(value) ? value.map(item => String(item)) : [];
+ }
+
+ async pathExists(filePath) {
+ try {
+ const stat = await fs.stat(filePath);
+ return stat.isFile() && stat.size > 0;
+ } catch (_error) {
+ return false;
+ }
+ }
+
+ error(message, status = 400, code, details) {
+ const error = new Error(message);
+ error.status = status;
+ if (code) error.code = code;
+ if (details) error.details = details;
+ return error;
+ }
+}
+
+module.exports = { SceneRepairService, buildInitialSceneManifest, scriptScenes };