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 narration reliability and recovery

darkzOGx17cc66138b37
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 22da10d..d8fbe33 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## Unreleased
+- Made narration fail-closed across production assembly, quality review, scheduling, and publishing; missing TTS can no longer silently become an approvable video
+- Added narration-only scene recovery with persistent provider, model, task, generation-time, cost, and failure evidence
+- Added a reasoned, reversible intentional-silence override and scene-aware silent-segment mixing for explicitly silent productions
- 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
diff --git a/README.md b/README.md
index 8055338..6bd2fd4 100644
--- a/README.md
+++ b/README.md
@@ -64,6 +64,10 @@ Every production now keeps a durable scene manifest with its narration, visual p
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.
+Narration is fail-closed. AgentTube records the TTS provider, model, external task when available, generation time, cost evidence, and failure reason for every scene. If narration is missing, simulated, stale, or failed, the production cannot be approved, scheduled, or published. Use **Regenerate narration only** to repair the audio without spending video-generation credits or replacing a visual.
+
+An intentionally silent production requires a separate operator confirmation and a stored reason of at least 10 characters. The override remains visible in Review Studio, can be reversed, and is included in the narration revision history. Silence is never inferred from a failed provider call.
+
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
diff --git a/agents/production-management-agent.js b/agents/production-management-agent.js
index aadddad..9980b9b 100644
--- a/agents/production-management-agent.js
+++ b/agents/production-management-agent.js
@@ -424,24 +424,33 @@ class ProductionManagementAgent {
// Read the TTS script
const ttsText = await fs.readFile(productionData.assets.script.ttsPath, 'utf8');
- // Generate audio using AI TTS
- await this.aiVideoGenerator.generateTTSAudio(ttsText, audioPath);
-
+ // Generate audio using AI TTS and retain the provider evidence returned by the generator.
+ const generatedPath = await this.aiVideoGenerator.generateTTSAudio(ttsText, audioPath);
+ const evidence = this.aiVideoGenerator.lastNarrationResult || {};
+ const usable = await this.aiVideoGenerator.isUsableAudioFile(generatedPath);
+
productionData.assets.audio = {
- path: audioPath,
+ path: generatedPath,
duration: productionData.estimatedDuration,
format: 'mp3',
generatedWith: 'AI',
- quality: 'high'
+ quality: usable ? 'high' : null,
+ status: usable ? 'ready' : 'unavailable',
+ simulated: !usable,
+ provider: evidence.provider || null,
+ model: evidence.model || null,
+ externalTaskId: evidence.externalTaskId || null,
+ generatedAt: evidence.generatedAt || new Date().toISOString(),
+ cost: evidence.cost || {},
+ error: usable ? null : 'No live narration provider returned usable audio',
+ intentionalSilence: false
};
-
- productionData.timeline.audioGenerated = new Date().toISOString();
-
- return audioPath;
+
+ if (usable) productionData.timeline.audioGenerated = new Date().toISOString();
+ return generatedPath;
} catch (error) {
this.logger.error('AI audio generation failed:', error);
- // Fallback to simulation
- return await this.simulateAudioGeneration(productionData);
+ return await this.simulateAudioGeneration(productionData, error);
}
}
@@ -559,6 +568,11 @@ class ProductionManagementAgent {
try {
const finalVideoPath = path.join(__dirname, '..', 'data', 'videos', `${productionData.id}_final.mp4`);
+ const narrationReady = await this.aiVideoGenerator.isUsableAudioFile(productionData.assets.audio?.path);
+ if (!narrationReady && productionData.assets.audio?.intentionalSilence !== true) {
+ this.logger.warn('Final assembly is blocked until narration succeeds or the operator explicitly confirms an intentional silent video.');
+ return await this.simulateVideoAssembly(productionData, 'Narration is missing');
+ }
// Use AI Video Generator to create the final video
const producedPath = await this.aiVideoGenerator.generateVideo(
@@ -665,7 +679,7 @@ class ProductionManagementAgent {
}
// Fallback simulation methods
- async simulateAudioGeneration(productionData) {
+ async simulateAudioGeneration(productionData, failure = null) {
const audioPath = path.join(__dirname, '..', 'data', 'audio', `${productionData.id}_narration.mp3`);
await fs.writeFile(audioPath + '.info', JSON.stringify({
@@ -677,17 +691,26 @@ class ProductionManagementAgent {
path: audioPath + '.info',
duration: productionData.estimatedDuration,
format: 'mp3',
- simulated: true
+ status: 'unavailable',
+ simulated: true,
+ provider: this.aiVideoGenerator.lastNarrationResult?.provider || 'simulation',
+ model: this.aiVideoGenerator.lastNarrationResult?.model || null,
+ externalTaskId: this.aiVideoGenerator.lastNarrationResult?.externalTaskId || null,
+ generatedAt: this.aiVideoGenerator.lastNarrationResult?.generatedAt || new Date().toISOString(),
+ cost: this.aiVideoGenerator.lastNarrationResult?.cost || { billed: false },
+ error: failure?.message || this.aiVideoGenerator.lastNarrationResult?.error || 'No live narration provider is configured',
+ intentionalSilence: false
};
return audioPath + '.info';
}
- async simulateVideoAssembly(productionData) {
+ async simulateVideoAssembly(productionData, reason = null) {
const finalVideoPath = path.join(__dirname, '..', 'data', 'videos', `${productionData.id}_final.mp4`);
const assemblyInstructions = {
message: 'AI video would be assembled here',
+ blockedReason: reason,
assets: productionData.assets,
timestamp: new Date().toISOString()
};
@@ -701,7 +724,8 @@ class ProductionManagementAgent {
path: finalVideoPath + '.assembly.json',
fileSize: 0,
duration: productionData.estimatedDuration,
- simulated: true
+ simulated: true,
+ blockedReason: reason
};
return finalVideoPath + '.assembly.json';
diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.js
index f82ae28..510d17f 100644
--- a/agents/publishing-scheduling-agent.js
+++ b/agents/publishing-scheduling-agent.js
@@ -49,6 +49,10 @@ class PublishingSchedulingAgent {
this.logger.warn(`Not scheduling ${productionData.id}: no real video file was produced (placeholder/simulated output). Fix your AI provider keys and FFmpeg, then regenerate.`);
return null;
}
+ if (!await this.isNarrationReady(productionData.assets?.audio)) {
+ this.logger.warn(`Not scheduling ${productionData.id}: narration is missing. Regenerate narration or explicitly confirm an intentional silent video.`);
+ return null;
+ }
this.logger.info(`Scheduling content: ${productionData.id}`);
const existing = await this.db.getLatestScheduleEntry?.(productionData.id);
@@ -71,6 +75,7 @@ class PublishingSchedulingAgent {
seo: productionData.seo,
thumbnail: productionData.assets.thumbnail,
video: productionData.assets.finalVideo,
+ audio: productionData.assets.audio,
captions: productionData.assets.captions,
privacyStatus: productionData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',
containsSyntheticMedia: productionData.containsSyntheticMedia === true
@@ -92,6 +97,7 @@ class PublishingSchedulingAgent {
async publishContent(contentId) {
try {
+ let productionBundle = null;
if (this.db.getLatestReadinessRun) {
const readiness = await this.db.getLatestReadinessRun();
if (readiness?.status === 'failed') {
@@ -105,8 +111,8 @@ class PublishingSchedulingAgent {
}
}
if (this.db.getProductionBundle) {
- const bundle = await this.db.getProductionBundle(contentId);
- if (bundle && !['verified', 'not_required'].includes(bundle.provenance?.status || 'not_required')) {
+ productionBundle = await this.db.getProductionBundle(contentId);
+ if (productionBundle && !['verified', 'not_required'].includes(productionBundle.provenance?.status || 'not_required')) {
const error = new Error('Publishing is blocked until every factual claim is supported or explicitly waived');
error.status = 409;
error.code = 'PROVENANCE_BLOCKED';
@@ -126,6 +132,12 @@ class PublishingSchedulingAgent {
throw new Error(`Content not found in queue: ${contentId}`);
}
if (scheduleEntry.status === 'published') return scheduleEntry;
+ if (!await this.isNarrationReady(scheduleEntry.metadata?.audio || productionBundle?.assets?.audio)) {
+ const error = new Error('Publishing is blocked because narration is missing or the intentional-silence override is incomplete');
+ error.status = 409;
+ error.code = 'NARRATION_REQUIRED';
+ throw error;
+ }
if (scheduleEntry.youtubeId) {
return this.reconcileUploadedVideo(scheduleEntry);
}
@@ -235,6 +247,19 @@ class PublishingSchedulingAgent {
return videoUpload.data;
}
+ async isNarrationReady(audio = {}) {
+ if (audio.intentionalSilence === true) {
+ return String(audio.silenceReason || '').trim().length >= 10 && Boolean(audio.silenceConfirmedAt);
+ }
+ if (!audio.path || audio.simulated || String(audio.path).endsWith('.info')) return false;
+ try {
+ const stats = await fs.stat(audio.path);
+ return stats.isFile() && stats.size > 0;
+ } catch (_error) {
+ return false;
+ }
+ }
+
isUploadOutcomeUnknown(error) {
const status = Number(error.status || error.response?.status || 0);
return !status || status >= 500;
diff --git a/dashboard/app.js b/dashboard/app.js
index 576279b..e97e025 100644
--- a/dashboard/app.js
+++ b/dashboard/app.js
@@ -545,11 +545,22 @@ function renderSceneEditor(item, canReview = true) {
const scenes = item.scenes || [];
if (!scenes.length) return '';
const verifiedSources = (item.provenance?.sources || []).filter(source => source.status === 'verified');
+ const audio = item.assets?.audio || {};
+ const intentionalSilence = audio.intentionalSilence === true;
+ const narrationIssues = scenes.filter(scene => !['current', 'intentional_silence'].includes(scene.narrationStatus)).length;
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="narration-recovery ${intentionalSilence ? 'intentional' : narrationIssues ? 'attention' : ''}">
+ <div><p class="eyebrow">NARRATION RELIABILITY</p><strong>${intentionalSilence ? 'Intentional silence confirmed' : narrationIssues ? `${narrationIssues} scene${narrationIssues === 1 ? '' : 's'} need narration` : 'Narration evidence is current'}</strong>
+ <p>${intentionalSilence ? escapeHTML(audio.silenceReason || '') : audio.error ? escapeHTML(audio.error) : 'Regenerate narration without replacing the scene visual. Approval remains blocked until audio is ready.'}</p>
+ ${audio.provider ? `<span class="narration-evidence">${escapeHTML(audio.provider)}${audio.model ? ` · ${escapeHTML(audio.model)}` : ''}${audio.externalTaskId ? ` · task ${escapeHTML(audio.externalTaskId)}` : ''}</span>` : ''}</div>
+ ${canReview ? intentionalSilence
+ ? '<button type="button" class="button secondary small" data-require-narration>Require narration</button>'
+ : '<button type="button" class="button secondary small" data-intentional-silence>Use intentional silence</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) => {
@@ -564,7 +575,7 @@ function renderSceneEditor(item, canReview = true) {
<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>
+ <div class="scene-status-row">${statusChip(scene.status)} ${statusChip(`narration_${scene.narrationStatus || 'unavailable'}`)}<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>
@@ -574,12 +585,14 @@ function renderSceneEditor(item, canReview = true) {
${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>
+ <span>Visual: ${escapeHTML(scene.provider || 'local')} ${scene.model ? `· ${escapeHTML(scene.model)}` : ''}</span>
</div>
+ <div class="scene-narration-evidence"><span>Narration: ${escapeHTML(scene.narrationProvider || 'not generated')}${scene.narrationModel ? ` · ${escapeHTML(scene.narrationModel)}` : ''}${scene.narrationTaskId ? ` · task ${escapeHTML(scene.narrationTaskId)}` : ''}</span>${scene.narrationError ? `<span class="danger-text">${escapeHTML(scene.narrationError)}</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-narration ${disabled ? 'disabled' : ''}>Regenerate narration only</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>
@@ -825,7 +838,7 @@ 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]');
+ const sceneButton = event.target.closest('[data-scene-save], [data-scene-narration], [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;
@@ -859,6 +872,14 @@ document.addEventListener('click', async event => {
await refreshContentDialog(productionId, 'Scene draft saved.');
return;
}
+ if (sceneButton.matches('[data-scene-narration]')) {
+ if (!confirm('Regenerate narration for only this scene? This may consume TTS provider credits; the provider invoice is authoritative.')) return;
+ await api(`/api/content/${encodeURIComponent(productionId)}/scenes/${encodeURIComponent(sceneId)}/narration`, {
+ method: 'POST', body: JSON.stringify({ confirmCost: true })
+ });
+ await refreshContentDialog(productionId, 'Scene narration regenerated. Rebuild the final video when every narration segment is ready.');
+ 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?`
@@ -874,6 +895,30 @@ document.addEventListener('click', async event => {
return;
}
+ const silenceAction = event.target.closest('[data-intentional-silence], [data-require-narration]');
+ if (silenceAction) {
+ const productionId = $('#content-review-form')?.dataset.productionId;
+ if (!productionId) return;
+ const enabled = silenceAction.matches('[data-intentional-silence]');
+ let reason = '';
+ if (enabled) {
+ reason = prompt('Why is this production intentionally silent? This reason is stored with the approval evidence.') || '';
+ if (!reason) return;
+ if (!confirm('Confirm that this production is intentionally silent. Captions and visuals will remain, and approval will record this override.')) return;
+ } else if (!confirm('Require narration again? Approval will be blocked until missing scene narration is regenerated and the video is rebuilt.')) {
+ return;
+ }
+ try {
+ await api(`/api/content/${encodeURIComponent(productionId)}/narration/silence`, {
+ method: 'POST', body: JSON.stringify({ enabled, confirmed: enabled, reason })
+ });
+ await refreshContentDialog(productionId, enabled ? 'Intentional silence recorded. Rebuild before approval.' : 'Narration is required again.');
+ } catch (error) {
+ showToast(error.message, 'error');
+ }
+ return;
+ }
+
const rebuildScenes = event.target.closest('[data-rebuild-scenes]');
if (rebuildScenes) {
const productionId = rebuildScenes.dataset.rebuildScenes;
diff --git a/dashboard/styles.css b/dashboard/styles.css
index d68f9a4..e49e51a 100644
--- a/dashboard/styles.css
+++ b/dashboard/styles.css
@@ -198,6 +198,12 @@ label small { color: var(--muted); font-weight: 400; }
.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; }
+.narration-recovery { display: flex; justify-content: space-between; align-items: center; gap: 16px; border: 1px solid rgba(72,213,151,.25); background: rgba(72,213,151,.055); border-radius: 10px; padding: 12px; }
+.narration-recovery.attention { border-color: rgba(255,137,148,.38); background: rgba(255,137,148,.06); }
+.narration-recovery.intentional { border-color: rgba(114,165,255,.35); background: rgba(114,165,255,.06); }
+.narration-recovery strong { display: block; margin-top: 2px; font-size: 13px; }
+.narration-recovery p:not(.eyebrow) { color: var(--muted); font-size: 11px; line-height: 1.45; margin: 5px 0 0; }
+.narration-evidence { display: block; color: var(--muted); font-size: 10px; margin-top: 6px; }
.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); }
@@ -212,13 +218,16 @@ label small { color: var(--muted); font-weight: 400; }
.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-narration-evidence { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 12px; color: var(--muted); 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); }
+.status.narration_stale, .status.narration_unavailable, .status.narration_failed, .status.narration_generating, .status.needs_rebuild, .status.visual_stale, .status.missing_asset, .status.generating { color: var(--amber); background: rgba(245,185,68,.12); }
+.status.narration_current { color: var(--green); background: rgba(72,213,151,.1); }
+.status.narration_intentional_silence { color: var(--blue); background: rgba(114,165,255,.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; }
@@ -274,5 +283,6 @@ label small { color: var(--muted); font-weight: 400; }
.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; }
+ .narration-recovery { align-items: flex-start; flex-direction: column; }
.scene-actions { gap: 4px 11px; }
}
diff --git a/database/db.js b/database/db.js
index 068ad81..9fde2fc 100644
--- a/database/db.js
+++ b/database/db.js
@@ -310,6 +310,12 @@ class Database {
asset_origin TEXT DEFAULT 'generated',
asset_path TEXT,
audio_path TEXT,
+ narration_provider TEXT,
+ narration_model TEXT,
+ narration_task_id TEXT,
+ narration_error TEXT,
+ narration_generated_at TEXT,
+ narration_cost TEXT NOT NULL DEFAULT '{}',
provider TEXT,
model TEXT,
external_task_id TEXT,
@@ -432,10 +438,30 @@ class Database {
await this.executeQuery(tableQuery);
}
+ await this.ensureColumns('production_scenes', {
+ narration_provider: 'TEXT',
+ narration_model: 'TEXT',
+ narration_task_id: 'TEXT',
+ narration_error: 'TEXT',
+ narration_generated_at: 'TEXT',
+ narration_cost: "TEXT NOT NULL DEFAULT '{}'"
+ });
+
// Insert default settings
await this.insertDefaultSettings();
}
+ async ensureColumns(tableName, columns) {
+ const allowedTables = new Set(['production_scenes']);
+ if (!allowedTables.has(tableName)) throw new Error(`Unsupported migration table: ${tableName}`);
+ const existing = new Set((await this.getAllRows(`PRAGMA table_info(${tableName})`)).map(column => column.name));
+ for (const [columnName, definition] of Object.entries(columns)) {
+ if (!existing.has(columnName)) {
+ await this.executeQuery(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);
+ }
+ }
+ }
+
async insertDefaultSettings() {
const defaultSettings = [
['daily_content_enabled', 'true', 'Enable daily content generation'],
@@ -898,15 +924,19 @@ class Database {
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,
+ asset_type, asset_origin, asset_path, audio_path,
+ narration_provider, narration_model, narration_task_id, narration_error,
+ narration_generated_at, narration_cost, provider, model,
external_task_id, status, narration_status, revision, locked,
rights_confirmed, provenance_source_ids, contains_synthetic_media,
estimated_cost, actual_cost
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ) 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.audioPath || null, scene.narrationProvider || null, scene.narrationModel || null,
+ scene.narrationTaskId || null, scene.narrationError || null, scene.narrationGeneratedAt || null,
+ JSON.stringify(scene.narrationCost || {}), 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,
@@ -939,7 +969,9 @@ class Database {
await this.executeQuery(
`UPDATE production_scenes SET
position = ?, label = ?, script_text = ?, prompt = ?, duration = ?,
- asset_type = ?, asset_origin = ?, asset_path = ?, audio_path = ?, provider = ?,
+ asset_type = ?, asset_origin = ?, asset_path = ?, audio_path = ?,
+ narration_provider = ?, narration_model = ?, narration_task_id = ?, narration_error = ?,
+ narration_generated_at = ?, narration_cost = ?, provider = ?,
model = ?, external_task_id = ?, status = ?, narration_status = ?, revision = ?,
locked = ?, rights_confirmed = ?, provenance_source_ids = ?,
contains_synthetic_media = ?, estimated_cost = ?, actual_cost = ?,
@@ -948,7 +980,9 @@ class Database {
[
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.audioPath || null, next.narrationProvider || null, next.narrationModel || null,
+ next.narrationTaskId || null, next.narrationError || null, next.narrationGeneratedAt || null,
+ JSON.stringify(next.narrationCost || {}), 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,
@@ -1018,6 +1052,12 @@ class Database {
assetOrigin: row.asset_origin || 'generated',
assetPath: row.asset_path || null,
audioPath: row.audio_path || null,
+ narrationProvider: row.narration_provider || null,
+ narrationModel: row.narration_model || null,
+ narrationTaskId: row.narration_task_id || null,
+ narrationError: row.narration_error || null,
+ narrationGeneratedAt: row.narration_generated_at || null,
+ narrationCost: JSON.parse(row.narration_cost || '{}'),
externalTaskId: row.external_task_id || null,
narrationStatus: row.narration_status || 'current',
revision: Number(row.revision || 1),
diff --git a/index.js b/index.js
index 6e8c903..601f1db 100644
--- a/index.js
+++ b/index.js
@@ -566,6 +566,31 @@ class YouTubeAutomationAgent {
}
});
+ this.app.post('/api/content/:productionId/scenes/:sceneId/narration', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Narration recovery requires completed setup' });
+ const result = await this.scenes.regenerateNarration(req.params.productionId, req.params.sceneId, req.body || {});
+ await this.refreshContentReview(req.params.productionId, 'Narration regenerated; rebuild the final video before approval');
+ return res.status(202).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/narration/silence', protect, async (req, res) => {
+ try {
+ if (!this.scenes) return res.status(503).json({ error: 'Narration recovery requires completed setup' });
+ const result = await this.scenes.setSilenceOverride(req.params.productionId, req.body || {});
+ await this.refreshContentReview(
+ req.params.productionId,
+ result.enabled ? 'Intentional silence recorded; rebuild and review before approval' : 'Narration is required again; regenerate it before approval'
+ );
+ 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.put(
'/api/content/:productionId/scenes/:sceneId/asset',
protect,
@@ -1374,7 +1399,8 @@ class YouTubeAutomationAgent {
estimatedDuration: bundle.estimated_duration,
privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',
provenance: bundle.provenance,
- containsSyntheticMedia: bundle.provenance?.containsSyntheticMedia === true
+ containsSyntheticMedia: bundle.provenance?.containsSyntheticMedia === true,
+ scenes: bundle.scenes || []
};
const profile = await this.db.getChannelProfile() || {};
const quality = await this.operator.runQualityChecks(productionData, profile);
@@ -1401,6 +1427,7 @@ class YouTubeAutomationAgent {
seo: productionData.seo,
thumbnail: productionData.assets.thumbnail,
video: productionData.assets.finalVideo,
+ audio: productionData.assets.audio,
captions: productionData.assets.captions,
privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',
containsSyntheticMedia: productionData.containsSyntheticMedia
diff --git a/test.js b/test.js
index e3bec79..bd4196a 100644
--- a/test.js
+++ b/test.js
@@ -28,6 +28,7 @@ class SystemTest {
{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },
{ name: 'Durable Multi-Provider Video Generation', test: () => this.testVideoProviderLayer() },
{ name: 'Scene Repair Studio', test: () => this.testSceneRepairStudio() },
+ { name: 'Narration Reliability and Recovery', test: () => this.testNarrationReliability() },
{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },
{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },
{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },
@@ -817,8 +818,10 @@ class SystemTest {
try {
const imagePath = path.join(directory, 'scene.png');
const oldVideoPath = path.join(directory, 'old.mp4');
+ const originalAudioPath = path.join(directory, 'original.mp3');
await sharp({ create: { width: 320, height: 180, channels: 3, background: '#203a5f' } }).png().toFile(imagePath);
await fs.writeFile(oldVideoPath, Buffer.from('previous final video'));
+ await fs.writeFile(originalAudioPath, Buffer.from('previous narration'));
const production = {
id: `prod_scene_${Date.now()}`,
status: 'ready',
@@ -834,7 +837,7 @@ class SystemTest {
strategy: { topic: 'Selective scene repair' },
assets: {
video: { visualAssets: [imagePath] },
- audio: null,
+ audio: { path: originalAudioPath, status: 'ready', simulated: false, provider: 'fixture-tts', model: 'fixture-voice' },
thumbnail: { path: imagePath },
finalVideo: { path: oldVideoPath, simulated: false, duration: '1:00', provider: { actualProvider: 'slideshow' } }
},
@@ -856,6 +859,12 @@ class SystemTest {
throw new Error('Initial scene manifest did not preserve the script structure and visual assets');
}
await db.replaceProductionScenes(production.id, manifest);
+ for (const scene of await db.listProductionScenes(production.id)) {
+ await db.updateProductionScene(production.id, scene.id, {
+ audioPath: originalAudioPath, narrationStatus: 'current',
+ narrationProvider: 'fixture-tts', narrationModel: 'fixture-voice'
+ });
+ }
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');
@@ -877,12 +886,21 @@ class SystemTest {
isValidVideo: async () => true
},
generateVisualAssets: async () => [imagePath],
- generateTTSAudio: async (_text, outputPath) => { await fs.writeFile(outputPath, Buffer.from('scene narration')); return outputPath; },
+ async generateTTSAudio(_text, outputPath) {
+ await fs.writeFile(outputPath, Buffer.from('scene narration'));
+ this.lastNarrationResult = {
+ status: 'ready', path: outputPath, provider: 'fixture-tts', model: 'fixture-voice-v2',
+ externalTaskId: 'narration-task-1', generatedAt: new Date().toISOString(),
+ cost: { provider: 'fixture-tts', amount: null, invoiceRequired: true }
+ };
+ 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 });
+ service.rebuildNarration = async () => originalAudioPath;
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
@@ -905,7 +923,11 @@ class SystemTest {
}
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') {
+ if (
+ regenerated.scene.status !== 'needs_rebuild' || regenerated.scene.externalTaskId !== 'scene-task-1' ||
+ regenerated.scene.narrationStatus !== 'current' || regenerated.scene.narrationProvider !== 'fixture-tts' ||
+ regenerated.scene.narrationTaskId !== 'narration-task-1'
+ ) {
throw new Error('Confirmed selective regeneration did not persist visual and narration evidence');
}
@@ -952,6 +974,134 @@ class SystemTest {
this.logger.info('Scene Repair Studio test completed successfully');
}
+ async testNarrationReliability() {
+ const fs = require('fs').promises;
+ const os = require('os');
+ const { SceneRepairService } = require('./utils/scene-repair-service');
+ const { OperatorService } = require('./utils/operator-service');
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-narration-'));
+ const db = new Database();
+ db.dbPath = path.join(directory, 'narration.db');
+ await db.initialize();
+
+ try {
+ const productionId = 'prod-narration-recovery';
+ const visualPath = path.join(directory, 'scene.png');
+ const videoPath = path.join(directory, 'video.mp4');
+ await fs.writeFile(visualPath, Buffer.from('visual'));
+ await fs.writeFile(videoPath, Buffer.from('video'));
+ const production = {
+ id: productionId, status: 'ready',
+ strategy: { topic: 'Narration recovery' },
+ script: {
+ title: 'Narration recovery',
+ fullScript: 'A complete script that demonstrates reliable narration recovery and explicit operator controls.'.repeat(4)
+ },
+ seo: {
+ title: 'Narration recovery',
+ description: 'A detailed explanation of reliable narration recovery for production workflows.',
+ tags: ['narration', 'recovery', 'workflow']
+ },
+ assets: {
+ audio: { path: path.join(directory, 'missing.mp3.info'), status: 'unavailable', simulated: true, error: 'Provider quota exhausted' },
+ finalVideo: { path: videoPath, simulated: false }, thumbnail: { path: visualPath }
+ },
+ timeline: {}, priority: 50, scheduledPublishTime: new Date(Date.now() + 86400000).toISOString()
+ };
+ await db.saveProductionData(production);
+ await db.saveProductionSnapshot(production);
+ await db.replaceProductionScenes(productionId, [{
+ id: 'scene-narration-1', label: 'Opening', scriptText: 'This narration must be recovered.',
+ prompt: 'Opening visual', duration: 8, assetType: 'image', assetOrigin: 'generated', assetPath: visualPath,
+ status: 'ready', narrationStatus: 'unavailable', narrationError: 'Provider quota exhausted', rightsConfirmed: true
+ }]);
+
+ const blockedQuality = await new OperatorService(db).runQualityChecks({
+ ...production, scenes: await db.listProductionScenes(productionId)
+ }, {});
+ if (blockedQuality.passed || !blockedQuality.blockingFailures.includes('narration')) {
+ throw new Error('Missing narration did not block production quality');
+ }
+
+ let failProvider = true;
+ const generator = {
+ async generateTTSAudio(_text, outputPath) {
+ if (failProvider) {
+ this.lastNarrationResult = {
+ status: 'failed', provider: 'openai', model: 'gpt-4o-mini-tts',
+ generatedAt: new Date().toISOString(), error: 'Provider quota exhausted',
+ cost: { provider: 'openai', amount: null, invoiceRequired: true }
+ };
+ throw new Error('Provider quota exhausted');
+ }
+ await fs.writeFile(outputPath, Buffer.from('recovered narration'));
+ this.lastNarrationResult = {
+ status: 'ready', path: outputPath, provider: 'openai', model: 'gpt-4o-mini-tts',
+ externalTaskId: 'tts-task-1', generatedAt: new Date().toISOString(),
+ cost: { provider: 'openai', amount: null, invoiceRequired: true }
+ };
+ return outputPath;
+ },
+ isUsableAudioFile: async filePath => Boolean(filePath && await fs.stat(filePath).then(stat => stat.size > 0).catch(() => false))
+ };
+ const service = new SceneRepairService(db, generator, { dataRoot: directory, logger: this.logger });
+
+ let confirmationBlocked = false;
+ try {
+ await service.regenerateNarration(productionId, 'scene-narration-1');
+ } catch (error) {
+ confirmationBlocked = error.code === 'NARRATION_COST_CONFIRMATION_REQUIRED';
+ }
+ if (!confirmationBlocked) throw new Error('Narration regeneration bypassed the provider-cost confirmation');
+
+ let outagePersisted = false;
+ try {
+ await service.regenerateNarration(productionId, 'scene-narration-1', { confirmCost: true });
+ } catch (_error) {
+ const failed = await db.getProductionScene(productionId, 'scene-narration-1');
+ outagePersisted = failed.narrationStatus === 'failed' && failed.narrationProvider === 'openai' && /quota/.test(failed.narrationError);
+ }
+ if (!outagePersisted) throw new Error('Narration provider failure evidence was not persisted');
+
+ failProvider = false;
+ const recovered = await service.regenerateNarration(productionId, 'scene-narration-1', { confirmCost: true });
+ if (
+ recovered.narrationStatus !== 'current' || recovered.narrationProvider !== 'openai' ||
+ recovered.narrationModel !== 'gpt-4o-mini-tts' || recovered.narrationTaskId !== 'tts-task-1' ||
+ recovered.status !== 'needs_rebuild'
+ ) {
+ throw new Error('Narration-only recovery did not preserve provider evidence and rebuild state');
+ }
+
+ let weakSilenceBlocked = false;
+ try {
+ await service.setSilenceOverride(productionId, { enabled: true, confirmed: true, reason: 'silent' });
+ } catch (error) {
+ weakSilenceBlocked = /at least 10/.test(error.message);
+ }
+ if (!weakSilenceBlocked) throw new Error('Intentional silence was accepted without a meaningful reason');
+
+ await service.setSilenceOverride(productionId, {
+ enabled: true, confirmed: true, reason: 'This visual demonstration intentionally uses captions only.'
+ });
+ const silenceBundle = await db.getProductionBundle(productionId);
+ const silenceQuality = await new OperatorService(db).runQualityChecks(silenceBundle, {});
+ const narrationCheck = silenceQuality.checks.find(check => check.id === 'narration');
+ if (!narrationCheck?.passed || silenceBundle.scenes[0].narrationStatus !== 'intentional_silence') {
+ throw new Error('Confirmed intentional silence did not satisfy the narration evidence gate');
+ }
+
+ const revisions = await db.listProductionSceneRevisions(productionId);
+ for (const action of ['regenerate_narration', 'confirm_intentional_silence']) {
+ if (!revisions.some(revision => revision.action === action)) throw new Error(`Narration history is missing ${action}`);
+ }
+ } finally {
+ await db.close();
+ await fs.rm(directory, { recursive: true, force: true });
+ }
+ this.logger.info('Narration reliability and recovery test completed successfully');
+ }
+
async testProvenanceDesk() {
const fs = require('fs').promises;
const os = require('os');
@@ -964,13 +1114,15 @@ class SystemTest {
await db.initialize();
const productionId = 'prod-provenance-test';
const videoPath = path.join(directory, 'video.mp4');
+ const audioPath = path.join(directory, 'narration.mp3');
await fs.writeFile(videoPath, Buffer.from('test-video'));
+ await fs.writeFile(audioPath, Buffer.from('test-audio'));
try {
await db.saveProductionData({
id: productionId,
status: 'needs_review',
- assets: { finalVideo: { path: videoPath, simulated: false } },
+ assets: { finalVideo: { path: videoPath, simulated: false }, audio: { path: audioPath, status: 'ready', simulated: false, provider: 'fixture-tts' } },
timeline: {}, scheduledPublishTime: new Date(Date.now() + 86400000).toISOString(),
priority: 50, estimatedDuration: '1:00'
});
@@ -999,7 +1151,7 @@ class SystemTest {
description: 'A detailed description of an evidence-aware automation workflow for careful channel operators.',
tags: ['automation', 'evidence', 'workflow']
},
- assets: { finalVideo: { path: videoPath, simulated: false } }
+ assets: { finalVideo: { path: videoPath, simulated: false }, audio: { path: audioPath, status: 'ready', simulated: false, provider: 'fixture-tts' } }
};
await db.saveProductionSnapshot(production);
@@ -1327,13 +1479,18 @@ class SystemTest {
async testPublishingSafety() {
const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');
+ const intentionalAudio = {
+ intentionalSilence: true,
+ silenceReason: 'This test fixture is intentionally silent.',
+ silenceConfirmedAt: new Date().toISOString()
+ };
const agent = new PublishingSchedulingAgent({
updateScheduleEntry: async () => {}
}, {});
agent.publishQueue = [
- { productionId: 'prod-a', title: 'A', status: 'scheduled', metadata: {} },
- { productionId: 'prod-b', title: 'B', status: 'scheduled', metadata: {} }
+ { productionId: 'prod-a', title: 'A', status: 'scheduled', metadata: { audio: intentionalAudio } },
+ { productionId: 'prod-b', title: 'B', status: 'scheduled', metadata: { audio: intentionalAudio } }
];
agent.uploadToYouTube = async () => ({ id: 'youtube-1' });
@@ -1343,6 +1500,17 @@ class SystemTest {
throw new Error('publishContent removed the wrong publish queue entries');
}
+ const missingNarration = new PublishingSchedulingAgent({ updateScheduleEntry: async () => {} }, {});
+ missingNarration.publishQueue = [{ productionId: 'prod-no-audio', status: 'scheduled', metadata: {} }];
+ missingNarration.uploadToYouTube = async () => { throw new Error('Upload must not start without narration'); };
+ let narrationPublishBlocked = false;
+ try {
+ await missingNarration.publishContent('prod-no-audio');
+ } catch (error) {
+ narrationPublishBlocked = error.code === 'NARRATION_REQUIRED';
+ }
+ if (!narrationPublishBlocked) throw new Error('Publishing accepted a production without narration evidence');
+
let missingFileRejected = false;
try {
await agent.getVideoStream(path.join(__dirname, 'data', 'missing-placeholder.mp4'));
@@ -1359,7 +1527,7 @@ class SystemTest {
updateScheduleEntry: async entry => uncertainUpdates.push({ ...entry })
}, {});
uncertain.publishQueue = [
- { id: 'schedule-uncertain', productionId: 'prod-uncertain', title: 'Uncertain', status: 'scheduled', metadata: {} }
+ { id: 'schedule-uncertain', productionId: 'prod-uncertain', title: 'Uncertain', status: 'scheduled', metadata: { audio: intentionalAudio } }
];
let uploadAttempts = 0;
uncertain.uploadToYouTube = async entry => {
@@ -1387,7 +1555,7 @@ class SystemTest {
let reconciliationCalls = 0;
const recorded = {
id: 'schedule-recorded', productionId: 'prod-recorded', title: 'Recorded', status: 'uploaded',
- youtubeId: 'youtube-existing', metadata: {}
+ youtubeId: 'youtube-existing', metadata: { audio: intentionalAudio }
};
const reconcile = new PublishingSchedulingAgent({
getLatestScheduleEntry: async () => recorded,
@@ -1568,12 +1736,26 @@ class SystemTest {
throw new Error('Production without a final video was scheduled for publishing');
}
+ const missingNarration = await agent.scheduleContent({
+ id: 'prod-no-narration', script: { title: 'No narration' }, priority: 50,
+ scheduledPublishTime: new Date().toISOString(),
+ assets: { finalVideo: { path: 'video.mp4' } }, seo: {}
+ });
+ if (missingNarration !== null) throw new Error('Production without narration was scheduled for publishing');
+
const real = await agent.scheduleContent({
id: 'prod-real',
script: { title: 'Real' },
priority: 50,
scheduledPublishTime: new Date().toISOString(),
- assets: { finalVideo: { path: 'video.mp4' }, thumbnail: {}, captions: {} },
+ assets: {
+ finalVideo: { path: 'video.mp4' }, thumbnail: {}, captions: {},
+ audio: {
+ intentionalSilence: true,
+ silenceReason: 'This fixture intentionally uses a silent timeline.',
+ silenceConfirmedAt: new Date().toISOString()
+ }
+ },
seo: {}
});
if (!real || agent.publishQueue.length !== 1) {
@@ -1675,12 +1857,19 @@ class SystemTest {
throw new Error('Rendered slideshow video is empty');
}
- // Silent fallback: an unusable audio path must still yield a playable output
+ // Missing narration must fail closed unless the operator explicitly confirmed silence.
const finalPath = path.join(dir, 'final.mp4');
- await generator.addAudioToVideo(videoPath, path.join(dir, 'missing.mp3'), finalPath);
+ let missingNarrationBlocked = false;
+ try {
+ await generator.addAudioToVideo(videoPath, path.join(dir, 'missing.mp3'), finalPath);
+ } catch (error) {
+ missingNarrationBlocked = error.code === 'NARRATION_REQUIRED';
+ }
+ if (!missingNarrationBlocked) throw new Error('Missing narration silently produced a final video');
+ await generator.addAudioToVideo(videoPath, path.join(dir, 'missing.mp3'), finalPath, { allowSilent: true });
const finalStats = await fs.stat(finalPath);
if (!finalStats.size) {
- throw new Error('Silent-audio fallback did not produce a video');
+ throw new Error('Explicit intentional-silence assembly did not produce a video');
}
const hybridPath = path.join(dir, 'hybrid.mp4');
diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.js
index 6765ff6..d04d855 100644
--- a/utils/ai-video-generator.js
+++ b/utils/ai-video-generator.js
@@ -14,6 +14,7 @@ class AIVideoGenerator {
const resolvedCredentials = credentials?.credentials || credentials || {};
this.db = options.db || null;
this.lastVideoResult = null;
+ this.lastNarrationResult = null;
// Initialize AI services with graceful fallback
const openaiKey = resolvedCredentials.openai?.apiKey || process.env.OPENAI_API_KEY;
@@ -48,6 +49,7 @@ class AIVideoGenerator {
// ElevenLabs configuration
this.elevenLabsApiKey = resolvedCredentials.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY;
this.elevenLabsVoiceId = resolvedCredentials.elevenLabs?.voiceId || process.env.ELEVENLABS_VOICE_ID;
+ this.elevenLabsModel = process.env.ELEVENLABS_TTS_MODEL || 'eleven_v3';
// Azure Speech configuration
this.azureSpeechKey = resolvedCredentials.azure?.speechKey || process.env.AZURE_SPEECH_KEY;
@@ -59,26 +61,46 @@ class AIVideoGenerator {
async generateTTSAudio(text, outputPath) {
this.logger.info('Generating TTS audio...');
-
+ this.lastNarrationResult = null;
+ let provider = 'simulation';
+ let model = null;
+
try {
- // Try ElevenLabs first (higher quality)
+ let generatedPath;
if (this.elevenLabsApiKey && this.elevenLabsVoiceId) {
- return await this.generateElevenLabsTTS(text, outputPath);
- }
-
- // Fallback to OpenAI TTS
- if (this.openai) {
- return await this.generateOpenAITTS(text, outputPath);
- }
-
- // Fallback to Gemini native TTS (free tier)
- if (this.gemini) {
- return await this.generateGeminiTTS(text, outputPath);
+ provider = 'elevenlabs';
+ model = this.elevenLabsModel;
+ generatedPath = await this.generateElevenLabsTTS(text, outputPath);
+ } else if (this.openai) {
+ provider = 'openai';
+ model = 'gpt-4o-mini-tts';
+ generatedPath = await this.generateOpenAITTS(text, outputPath);
+ } else if (this.gemini) {
+ provider = 'gemini';
+ model = process.env.GEMINI_TTS_MODEL || 'gemini-3.1-flash-tts-preview';
+ generatedPath = await this.generateGeminiTTS(text, outputPath);
+ } else {
+ generatedPath = await this.simulateTTSGeneration(text, outputPath);
}
- // Final fallback to simulation
- return await this.simulateTTSGeneration(text, outputPath);
+ const usable = await this.isUsableAudioFile(generatedPath);
+ this.lastNarrationResult = {
+ status: usable ? 'ready' : 'unavailable',
+ path: generatedPath,
+ provider,
+ model,
+ externalTaskId: null,
+ generatedAt: new Date().toISOString(),
+ simulated: !usable,
+ cost: { provider, amount: null, currency: null, invoiceRequired: provider !== 'simulation' }
+ };
+ return generatedPath;
} catch (error) {
+ this.lastNarrationResult = {
+ status: 'failed', path: null, provider, model, externalTaskId: null,
+ generatedAt: new Date().toISOString(), simulated: false, error: error.message,
+ cost: { provider, amount: null, currency: null, invoiceRequired: provider !== 'simulation' }
+ };
this.logger.error('TTS generation failed:', error);
throw error;
}
@@ -89,7 +111,7 @@ class AIVideoGenerator {
const data = {
text: text,
- model_id: "eleven_v3",
+ model_id: this.elevenLabsModel,
voice_settings: {
stability: 0.5,
similarity_boost: 0.8,
@@ -759,11 +781,14 @@ class AIVideoGenerator {
const hasRealAudio = await this.isUsableAudioFile(audioPath);
if (!hasRealAudio) {
- this.logger.warn('No narration audio available — producing silent video. Configure OpenAI, ElevenLabs, or Azure Speech for narration.');
- if (videoPath !== outputPath) {
- await fs.copyFile(videoPath, outputPath);
+ if (options.allowSilent === true) {
+ this.logger.warn('Creating an intentionally silent video from an operator-confirmed override.');
+ if (videoPath !== outputPath) await fs.copyFile(videoPath, outputPath);
+ return outputPath;
}
- return outputPath;
+ const error = new Error('Narration audio is required. Regenerate narration or explicitly confirm an intentional silent video.');
+ error.code = 'NARRATION_REQUIRED';
+ throw error;
}
// FFmpeg cannot write to its own input, so mux to a temp file when paths collide
diff --git a/utils/operator-service.js b/utils/operator-service.js
index d118b94..19d4607 100644
--- a/utils/operator-service.js
+++ b/utils/operator-service.js
@@ -55,6 +55,32 @@ class OperatorService {
'Final video file exists on disk'));
}
+ const audio = production.assets?.audio || {};
+ const intentionalSilence = audio.intentionalSilence === true &&
+ String(audio.silenceReason || '').trim().length >= 10 &&
+ Boolean(audio.silenceConfirmedAt);
+ const productionAudioReady = !audio.simulated && await this.fileExists(audio.path);
+ const scenes = production.scenes || [];
+ let sceneAudioReady = false;
+ if (scenes.length) {
+ const readiness = [];
+ for (const scene of scenes) {
+ readiness.push(scene.narrationStatus === 'intentional_silence' || (
+ scene.narrationStatus === 'current' && await this.fileExists(scene.audioPath)
+ ));
+ }
+ sceneAudioReady = readiness.every(Boolean);
+ }
+ const narrationReady = intentionalSilence || productionAudioReady || sceneAudioReady;
+ checks.push(this.check('narration', narrationReady,
+ intentionalSilence
+ ? `Intentional silence confirmed: ${audio.silenceReason}`
+ : narrationReady
+ ? `Narration is ready${audio.provider ? ` via ${audio.provider}` : ''}`
+ : audio.intentionalSilence
+ ? 'Intentional silence requires an operator confirmation and reason of at least 10 characters'
+ : 'Narration is missing or unusable; regenerate it before approval'));
+
const matchedBannedTopics = bannedTopics.filter(topic =>
topic && combinedText.includes(String(topic).toLowerCase())
);
@@ -73,10 +99,10 @@ 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'
+ !scene.assetPath || ['missing_asset', 'failed', 'generating', 'needs_rebuild', 'visual_stale'].includes(scene.status) ||
+ !['current', 'intentional_silence'].includes(scene.narrationStatus)
);
const unlicensedUploads = scenes.filter(scene => scene.assetOrigin === 'uploaded' && !scene.rightsConfirmed);
checks.push(this.check('scene_integrity', invalidScenes.length === 0,
diff --git a/utils/scene-repair-service.js b/utils/scene-repair-service.js
index e700ba3..e622a89 100644
--- a/utils/scene-repair-service.js
+++ b/utils/scene-repair-service.js
@@ -77,6 +77,10 @@ function buildInitialSceneManifest(production = {}, providerResult = {}) {
const totalWords = wordCounts.reduce((sum, count) => sum + count, 0);
const generated = providerResult.scenes || [];
const visualAssets = (production.assets?.video?.visualAssets || []).filter(Boolean);
+ const audio = production.assets?.audio || {};
+ const narrationStatus = audio.intentionalSilence === true
+ ? 'intentional_silence'
+ : audio.simulated || audio.status === 'unavailable' ? 'unavailable' : 'current';
return blueprints.map((scene, position) => {
const generatedScene = generated.find(item => String(item.label || '').toLowerCase() === scene.label.toLowerCase()) || generated[position];
@@ -93,11 +97,17 @@ function buildInitialSceneManifest(production = {}, providerResult = {}) {
assetOrigin: 'generated',
assetPath,
audioPath: null,
+ narrationProvider: audio.provider || null,
+ narrationModel: audio.model || null,
+ narrationTaskId: audio.externalTaskId || null,
+ narrationError: audio.error || null,
+ narrationGeneratedAt: audio.generatedAt || null,
+ narrationCost: audio.cost || {},
provider,
model: generatedScene?.model || providerResult.model || null,
externalTaskId: generatedScene?.taskId || null,
status: assetPath ? 'ready' : 'missing_asset',
- narrationStatus: production.assets?.audio?.simulated ? 'unavailable' : 'current',
+ narrationStatus,
revision: 1,
locked: false,
rightsConfirmed: true,
@@ -135,7 +145,14 @@ class SceneRepairService {
async initializeAudioSegments(production, scenes) {
const audioPath = production.assets?.audio?.path;
- if (!await this.videoGenerator?.isUsableAudioFile?.(audioPath)) return scenes;
+ const audio = production.assets?.audio || {};
+ if (!await this.videoGenerator?.isUsableAudioFile?.(audioPath)) {
+ for (const scene of scenes) {
+ scene.narrationStatus = audio.intentionalSilence === true ? 'intentional_silence' : 'unavailable';
+ scene.narrationError = audio.intentionalSilence === true ? null : audio.error || 'Narration audio is unavailable';
+ }
+ return scenes;
+ }
const directory = path.join(this.dataRoot, 'audio', 'scenes', production.id);
await fs.mkdir(directory, { recursive: true });
let start = 0;
@@ -144,9 +161,18 @@ class SceneRepairService {
try {
await runFFmpeg(['-y', '-ss', start.toFixed(2), '-t', Number(scene.duration).toFixed(2), '-i', audioPath, '-vn', '-c:a', 'libmp3lame', output]);
scene.audioPath = output;
+ scene.narrationStatus = 'current';
+ scene.narrationProvider = audio.provider || null;
+ scene.narrationModel = audio.model || null;
+ scene.narrationTaskId = audio.externalTaskId || null;
+ scene.narrationError = null;
+ scene.narrationGeneratedAt = audio.generatedAt || null;
+ scene.narrationCost = audio.cost || {};
} catch (error) {
this.logger.warn(`Could not split narration for scene ${scene.position + 1}: ${error.message}`);
scene.audioPath = null;
+ scene.narrationStatus = 'unavailable';
+ scene.narrationError = `Narration segment could not be prepared: ${error.message}`;
}
start += Number(scene.duration);
}
@@ -231,6 +257,125 @@ class SceneRepairService {
return after;
}
+ async regenerateNarration(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 narration', 409);
+ if (input.confirmCost !== true) {
+ throw this.error('Confirm that narration regeneration may consume provider credits', 409, 'NARRATION_COST_CONFIRMATION_REQUIRED');
+ }
+
+ const before = scene;
+ const outputPath = path.join(this.dataRoot, 'audio', 'scenes', productionId, `${String(scene.position).padStart(3, '0')}_r${scene.revision + 1}.mp3`);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ try {
+ await this.db.updateProductionScene(productionId, sceneId, {
+ narrationStatus: 'generating', narrationError: null
+ });
+ const generatedPath = await this.videoGenerator.generateTTSAudio(scene.scriptText, outputPath);
+ const evidence = this.videoGenerator.lastNarrationResult || {};
+ if (!await this.videoGenerator.isUsableAudioFile(generatedPath)) {
+ throw this.error('Narration regeneration returned no usable audio; configure a live TTS provider and retry', 422, 'NARRATION_UNAVAILABLE');
+ }
+ const cost = evidence.cost || {
+ provider: evidence.provider || 'configured-tts', amount: null, currency: null, invoiceRequired: true
+ };
+ const next = await this.db.updateProductionScene(productionId, sceneId, {
+ audioPath: generatedPath,
+ narrationStatus: 'current',
+ narrationProvider: evidence.provider || 'configured-tts',
+ narrationModel: evidence.model || null,
+ narrationTaskId: evidence.externalTaskId || null,
+ narrationError: null,
+ narrationGeneratedAt: evidence.generatedAt || new Date().toISOString(),
+ narrationCost: cost,
+ status: scene.status === 'visual_stale' ? 'visual_stale' : 'needs_rebuild',
+ revision: scene.revision + 1
+ });
+ await this.updateProductionAudioState(bundle, {
+ status: 'partial', path: null, simulated: false, intentionalSilence: false,
+ error: 'Scene narration changed; rebuild the final narration mix before approval'
+ });
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'regenerate_narration', before, after: next, costEvidence: cost
+ });
+ return next;
+ } catch (error) {
+ const evidence = this.videoGenerator.lastNarrationResult || {};
+ await this.db.updateProductionScene(productionId, sceneId, {
+ narrationStatus: 'failed', narrationProvider: evidence.provider || scene.narrationProvider,
+ narrationModel: evidence.model || scene.narrationModel, narrationTaskId: evidence.externalTaskId || null,
+ narrationError: error.message, narrationGeneratedAt: evidence.generatedAt || new Date().toISOString(),
+ narrationCost: evidence.cost || scene.narrationCost || {}
+ }).catch(() => {});
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId, action: 'regenerate_narration', status: 'failed', before, after: {},
+ costEvidence: evidence.cost || {}, error: error.message
+ }).catch(() => {});
+ throw error;
+ }
+ }
+
+ async setSilenceOverride(productionId, input = {}) {
+ const bundle = await this.getEditableBundle(productionId);
+ const enabled = input.enabled === true;
+ const reason = String(input.reason || '').trim();
+ if (enabled && input.confirmed !== true) {
+ throw this.error('Confirm the intentional-silence override before applying it', 409, 'SILENCE_CONFIRMATION_REQUIRED');
+ }
+ if (enabled && reason.length < 10) {
+ throw this.error('Explain why this production is intentionally silent using at least 10 characters', 400);
+ }
+ const changedAt = new Date().toISOString();
+ const audioChanges = enabled
+ ? {
+ path: null, status: 'intentional_silence', simulated: false, intentionalSilence: true,
+ silenceReason: reason, silenceConfirmedAt: changedAt, provider: 'operator-override', model: null,
+ externalTaskId: null, generatedAt: changedAt, cost: { billed: false }, error: null
+ }
+ : {
+ path: null, status: 'unavailable', simulated: true, intentionalSilence: false,
+ silenceReason: null, silenceConfirmedAt: null, provider: null, model: null,
+ externalTaskId: null, generatedAt: changedAt, cost: { billed: false },
+ error: 'Narration is required; regenerate every missing scene before approval'
+ };
+ await this.updateProductionAudioState(bundle, audioChanges);
+ const updated = [];
+ for (const scene of bundle.scenes) {
+ const before = scene;
+ const hasAudio = !enabled && scene.audioPath && await this.pathExists(scene.audioPath);
+ const next = await this.db.updateProductionScene(productionId, scene.id, {
+ audioPath: enabled ? null : scene.audioPath,
+ narrationStatus: enabled ? 'intentional_silence' : hasAudio ? 'current' : 'unavailable',
+ narrationProvider: enabled ? 'operator-override' : scene.narrationProvider,
+ narrationModel: enabled ? null : scene.narrationModel,
+ narrationTaskId: enabled ? null : scene.narrationTaskId,
+ narrationError: enabled || hasAudio ? null : 'Narration is required for this scene',
+ narrationGeneratedAt: changedAt,
+ narrationCost: enabled ? { billed: false } : scene.narrationCost,
+ status: scene.status === 'visual_stale' ? 'visual_stale' : 'needs_rebuild',
+ revision: scene.revision + 1
+ });
+ await this.db.saveProductionSceneRevision({
+ productionId, sceneId: scene.id, action: enabled ? 'confirm_intentional_silence' : 'require_narration',
+ before, after: next, costEvidence: { billed: false }
+ });
+ updated.push(next);
+ }
+ return { enabled, reason: enabled ? reason : null, scenes: updated };
+ }
+
+ async updateProductionAudioState(bundle, changes) {
+ const assets = { ...bundle.assets, audio: { ...(bundle.assets?.audio || {}), ...changes } };
+ await this.db.updateProductionData({
+ id: bundle.id, status: bundle.status, assets, timeline: bundle.timeline,
+ scheduledPublishTime: bundle.scheduled_publish_time, priority: bundle.priority
+ });
+ bundle.assets = assets;
+ return assets.audio;
+ }
+
async regenerationEstimate(productionId, sceneId, input = {}) {
const bundle = await this.getEditableBundle(productionId);
const scene = bundle.scenes.find(item => item.id === sceneId);
@@ -294,7 +439,13 @@ class SceneRepairService {
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 evidence = this.videoGenerator.lastNarrationResult || {};
+ narration = {
+ audioPath: generatedPath, narrationStatus: 'current',
+ narrationProvider: evidence.provider || 'configured-tts', narrationModel: evidence.model || null,
+ narrationTaskId: evidence.externalTaskId || null, narrationError: null,
+ narrationGeneratedAt: evidence.generatedAt || new Date().toISOString(), narrationCost: evidence.cost || {}
+ };
}
const next = await this.db.updateProductionScene(productionId, sceneId, {
@@ -366,13 +517,23 @@ class SceneRepairService {
const scenes = await this.db.listProductionScenes(productionId);
if (!scenes.length) throw this.error('No scene manifest is available', 409);
const missing = [];
+ const fullNarrationReady = await this.videoGenerator.isUsableAudioFile(bundle.assets?.audio?.path);
+ const currentSceneAudio = [];
for (const scene of scenes) {
- if (scene.narrationStatus === 'stale') missing.push(`${scene.label}: narration is stale`);
+ if (!['current', 'intentional_silence'].includes(scene.narrationStatus)) {
+ missing.push(`${scene.label}: narration is ${String(scene.narrationStatus || 'unavailable').replaceAll('_', ' ')}`);
+ }
+ if (scene.narrationStatus === 'current') currentSceneAudio.push(Boolean(scene.audioPath && await this.pathExists(scene.audioPath)));
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 (currentSceneAudio.some(Boolean) && currentSceneAudio.some(value => !value)) {
+ missing.push('The scene narration mix is incomplete; regenerate every missing narration segment');
+ } else if (currentSceneAudio.length && currentSceneAudio.every(value => !value) && !fullNarrationReady) {
+ missing.push('No usable production or scene narration audio is available');
+ }
if (missing.length) throw this.error(`Cannot rebuild: ${missing.join('; ')}`, 409, 'SCENE_REBUILD_BLOCKED', { blockers: missing });
const timestamp = Date.now();
@@ -386,7 +547,8 @@ class SceneRepairService {
})), visualPath);
const audioPath = await this.rebuildNarration(productionId, scenes, bundle.assets?.audio?.path, timestamp);
- await this.videoGenerator.addAudioToVideo(visualPath, audioPath, finalPath);
+ const allIntentionalSilence = scenes.every(scene => scene.narrationStatus === 'intentional_silence');
+ await this.videoGenerator.addAudioToVideo(visualPath, audioPath, finalPath, { allowSilent: allIntentionalSilence });
await fs.unlink(visualPath).catch(() => {});
await fs.writeFile(captionsPath, this.buildSRT(scenes));
const stats = await fs.stat(finalPath);
@@ -394,7 +556,19 @@ class SceneRepairService {
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,
+ audio: {
+ ...(bundle.assets?.audio || {}), path: audioPath, simulated: false,
+ status: allIntentionalSilence ? 'intentional_silence' : 'ready',
+ intentionalSilence: allIntentionalSilence,
+ provider: allIntentionalSilence ? 'operator-override' : 'scene-mix',
+ model: allIntentionalSilence ? null : 'ffmpeg-concat',
+ generatedAt: new Date().toISOString(), error: null,
+ sceneMixed: scenes.some(scene => scene.audioPath) || scenes.some(scene => scene.narrationStatus === 'intentional_silence'),
+ sceneEvidence: scenes.map(scene => ({
+ sceneId: scene.id, status: scene.narrationStatus, provider: scene.narrationProvider,
+ model: scene.narrationModel, externalTaskId: scene.narrationTaskId, generatedAt: scene.narrationGeneratedAt
+ }))
+ },
captions: { path: captionsPath, format: 'srt', language: 'en', autoGenerated: true, sceneAware: true },
finalVideo: {
...(bundle.assets?.finalVideo || {}), path: finalPath, previousPath, fileSize: stats.size,
@@ -421,15 +595,18 @@ class SceneRepairService {
}
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 hasSceneAudio = scenes.some(scene => scene.audioPath && scene.narrationStatus === 'current');
+ const allCurrentWithoutSegments = scenes.every(scene => scene.narrationStatus === 'current' && !scene.audioPath);
+ if (!hasSceneAudio && allCurrentWithoutSegments) 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);
+ for (const scene of scenes) {
+ if (scene.narrationStatus === 'intentional_silence') {
+ args.push('-f', 'lavfi', '-t', Number(scene.duration).toFixed(2), '-i', 'anullsrc=r=48000:cl=mono');
+ } else {
+ 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);