🎬 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.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
feat: add shorts repurposing studio
darkzOGxbd7ac90e20d2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d8fbe33..de5997e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,9 @@## Unreleased+- Added a persistent Shorts Repurposing Studio that proposes source-scene-backed vertical excerpts from an existing production without new provider calls+- Added local 9:16 FFmpeg rendering with blurred-canvas, center-crop, and stacked-focus layouts plus mobile-safe burned captions and SRT output+- Added independent Short review, evidence inheritance, scheduling, publishing-state reconciliation, and Shorts-specific analytics context- 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 productionsdiff --git a/README.md b/README.mdindex 6bd2fd4..4782437 100644--- a/README.md+++ b/README.md@@ -70,6 +70,14 @@ An intentionally silent production requires a separate operator confirmation andWhen 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.+### Repurpose an approved video into Shorts++Open **Shorts Repurposing Studio** inside Review Studio and choose **Create 3 Short drafts**. AgentTube selects self-contained windows from the durable scene timeline and preserves the exact source-scene IDs, start time, duration, rationale, title, description, tags, layout, and inherited review evidence for each candidate. Draft selection is local and does not call an AI provider.++Choose a blurred-canvas, center-crop, or stacked-focus layout, then render a real 9:16 MP4 with mobile-safe burned captions and a separate SRT file. The source video and narration are reused, so the default workflow does not spend new image, video, or TTS credits. Changing the layout invalidates the prior render and requires a fresh local render.++Every Short has its own approval and schedule. Scheduling remains blocked until the source production is approved, provenance is resolved, uploaded media rights are confirmed, every source scene is current, and the operator explicitly confirms the Short's privacy and publish time. Published Shorts retain their parent-production identity while their analytics use a separate Shorts baseline.+### Review research and provenanceEvery 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/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.jsindex 510d17f..6fe9cdb 100644--- a/agents/publishing-scheduling-agent.js+++ b/agents/publishing-scheduling-agent.js@@ -78,7 +78,10 @@ class PublishingSchedulingAgent {audio: productionData.assets.audio,captions: productionData.assets.captions,privacyStatus: productionData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',- containsSyntheticMedia: productionData.containsSyntheticMedia === true+ containsSyntheticMedia: productionData.containsSyntheticMedia === true,+ contentType: productionData.contentType || 'long_form',+ sourceProductionId: productionData.sourceProductionId || productionData.id,+ shortClipId: productionData.shortClipId || null},createdAt: new Date().toISOString()};@@ -151,6 +154,7 @@ class PublishingSchedulingAgent {scheduleEntry.status = 'uploading';scheduleEntry.error = null;await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'uploading');let uploadResult;try {@@ -160,12 +164,14 @@ class PublishingSchedulingAgent {scheduleEntry.status = 'reconciliation_required';scheduleEntry.error = 'Upload outcome is unknown; verify the YouTube channel before retrying';await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'reconciliation_required', scheduleEntry.error);error.code = 'UPLOAD_OUTCOME_UNKNOWN';error.status = 409;} else {scheduleEntry.status = 'failed';scheduleEntry.error = error.message;await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'failed', error.message);}throw error;}@@ -177,6 +183,7 @@ class PublishingSchedulingAgent {scheduleEntry.youtubeUrl = `https://www.youtube.com/watch?v=${uploadResult.id}`;await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'published');// Remove from queuethis.publishQueue = this.publishQueue.filter(entry => entry.productionId !== scheduleEntry.productionId);@@ -271,6 +278,7 @@ class PublishingSchedulingAgent {scheduleEntry.status = 'reconciliation_required';scheduleEntry.error = 'The recorded YouTube video ID could not be verified';await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'reconciliation_required', scheduleEntry.error);const error = new Error('The recorded upload could not be verified on YouTube. Resolve it before attempting another upload.');error.status = 409;error.code = 'UPLOAD_OUTCOME_UNKNOWN';@@ -281,11 +289,24 @@ class PublishingSchedulingAgent {scheduleEntry.youtubeUrl = scheduleEntry.youtubeUrl || `https://www.youtube.com/watch?v=${scheduleEntry.youtubeId}`;scheduleEntry.error = null;await this.db.updateScheduleEntry(scheduleEntry);+ await this.syncShortStatus(scheduleEntry, 'published');this.publishQueue = this.publishQueue.filter(entry => entry.productionId !== scheduleEntry.productionId);this.logger.success(`Reconciled existing YouTube upload: ${scheduleEntry.youtubeUrl}`);return scheduleEntry;}+ async syncShortStatus(scheduleEntry, status, error = null) {+ const clipId = scheduleEntry.metadata?.shortClipId;+ if (!clipId || !this.db.updateShortClip) return null;+ return this.db.updateShortClip(clipId, {+ status,+ scheduleId: scheduleEntry.id,+ youtubeId: scheduleEntry.youtubeId || null,+ youtubeUrl: scheduleEntry.youtubeUrl || null,+ error+ });+ }+async getVideoStream(videoPath) {try {const stats = await fs.stat(videoPath);diff --git a/dashboard/app.js b/dashboard/app.jsindex e97e025..602999d 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -603,6 +603,46 @@ function renderSceneEditor(item, canReview = true) {</section>`;}+function renderShortsStudio(item) {+ if (!item.assets?.finalVideo?.path || item.assets.finalVideo.simulated) return '';+ const clips = item.shorts || [];+ const parentApproved = item.review_status === 'approved';+ return `<section class="shorts-studio">+ <div class="panel-heading shorts-heading">+ <div><p class="eyebrow">SHORTS REPURPOSING STUDIO</p><h3>Turn one production into vertical reach</h3><p>Create local 9:16 excerpts with mobile captions. Drafts inherit the source production's evidence and still require separate approval.</p></div>+ <button type="button" class="button secondary small" data-propose-shorts="${escapeHTML(item.id)}">${clips.length ? 'Refresh drafts' : 'Create 3 Short drafts'}</button>+ </div>+ <div class="shorts-evidence ${parentApproved ? 'ready' : ''}">+ <span>${parentApproved ? '✓ Source production approved' : 'Source approval required before scheduling'}</span>+ <span>${escapeHTML(item.provenance?.status === 'verified' ? 'Evidence verified' : item.provenance?.status === 'not_required' ? 'No factual claims declared' : 'Evidence review incomplete')}</span>+ <span>Local render · no new provider call</span>+ </div>+ ${clips.length ? `<div class="shorts-grid">${clips.map(clip => {+ const locked = ['scheduled', 'uploading', 'published', 'reconciliation_required'].includes(clip.status);+ const rendered = Boolean(clip.assetUrls?.video);+ return `<article class="short-card" data-short-card="${escapeHTML(clip.id)}">+ <div class="short-preview">${rendered+ ? `<video controls preload="metadata"><source src="${escapeHTML(clip.assetUrls.video)}" type="video/mp4"></video>`+ : `<div class="short-placeholder"><strong>9:16</strong><span>${escapeHTML(label(clip.layout))} layout</span></div>`}</div>+ <div class="short-editor">+ <div class="scene-status-row">${statusChip(clip.status)}<span>${Number(clip.duration || 0).toFixed(0)}s</span><span>${escapeHTML((clip.sourceSceneLabels || []).join(' + '))}</span></div>+ <label><span>Short title</span><input data-short-field="title" maxlength="100" value="${escapeHTML(clip.title)}" ${locked ? 'disabled' : ''}></label>+ <label><span>Description and parent-video CTA</span><textarea data-short-field="description" rows="3" maxlength="5000" ${locked ? 'disabled' : ''}>${escapeHTML(clip.description)}</textarea></label>+ <label><span>Tags</span><input data-short-field="tags" value="${escapeHTML((clip.tags || []).join(', '))}" ${locked ? 'disabled' : ''}></label>+ <div class="form-grid two">+ <label><span>Vertical layout</span><select data-short-field="layout" ${locked ? 'disabled' : ''}><option value="blur" ${clip.layout === 'blur' ? 'selected' : ''}>Blurred canvas</option><option value="crop" ${clip.layout === 'crop' ? 'selected' : ''}>Center crop</option><option value="stacked" ${clip.layout === 'stacked' ? 'selected' : ''}>Stacked focus</option></select></label>+ <label><span>Publish time</span><input data-short-field="publishTime" type="datetime-local" value="${toLocalInput(clip.publishTime)}" ${locked ? 'disabled' : ''}></label>+ <label><span>Privacy</span><select data-short-field="privacyStatus" ${locked ? 'disabled' : ''}><option value="private" ${clip.privacyStatus === 'private' ? 'selected' : ''}>Private</option><option value="unlisted" ${clip.privacyStatus === 'unlisted' ? 'selected' : ''}>Unlisted</option><option value="public" ${clip.privacyStatus === 'public' ? 'selected' : ''}>Public</option></select></label>+ </div>+ <p class="short-rationale">${escapeHTML(clip.rationale || '')}${clip.error ? `<br><span class="danger-text">${escapeHTML(clip.error)}</span>` : ''}</p>+ ${clip.youtubeUrl ? `<a class="source-link" href="${escapeHTML(clip.youtubeUrl)}" target="_blank" rel="noopener">Open published Short ↗</a>` : ''}+ ${!locked ? `<div class="short-actions"><button type="button" class="text-button" data-short-save>Save draft</button><button type="button" class="button secondary small" data-short-render>${rendered ? 'Render again' : 'Render 9:16'}</button><button type="button" class="button primary small" data-short-approve ${!parentApproved || clip.status !== 'rendered' ? 'disabled' : ''} title="${!parentApproved ? 'Approve the source production first' : clip.status !== 'rendered' ? 'Render this Short first' : 'Confirm and schedule this Short'}">Approve & schedule</button></div>` : ''}+ </div>+ </article>`;+ }).join('')}</div>` : '<p class="empty-inline">No Short drafts yet. Create three candidates from the current scene timeline without calling a paid provider.</p>'}+ </section>`;+}+async function openContent(productionId) {$('#loading').classList.add('active');try {@@ -637,6 +677,7 @@ async function openContent(productionId) {</div></div>${renderSceneEditor(item, canReview)}+ ${renderShortsStudio(item)}${renderProvenanceEditor(item.provenance, canReview)}<div class="form-grid two"><label><span>Publish time</span><input name="publishTime" type="datetime-local" value="${toLocalInput(publishTime)}"></label>@@ -692,6 +733,18 @@ function sceneFormData(card) {};}+function shortFormData(card) {+ const publishTime = card.querySelector('[data-short-field="publishTime"]')?.value;+ return {+ title: card.querySelector('[data-short-field="title"]')?.value,+ description: card.querySelector('[data-short-field="description"]')?.value,+ tags: card.querySelector('[data-short-field="tags"]')?.value,+ layout: card.querySelector('[data-short-field="layout"]')?.value,+ publishTime: publishTime ? new Date(publishTime).toISOString() : undefined,+ privacyStatus: card.querySelector('[data-short-field="privacyStatus"]')?.value+ };+}+async function refreshContentDialog(productionId, message) {if (message) showToast(message);if ($('#content-dialog').open) $('#content-dialog').close();@@ -838,6 +891,55 @@ document.addEventListener('click', async event => {await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});}+ const proposeShorts = event.target.closest('[data-propose-shorts]');+ if (proposeShorts) {+ const productionId = proposeShorts.dataset.proposeShorts;+ const replacing = Boolean(document.querySelector('[data-short-card]'));+ if (replacing && !confirm('Replace the current editable Short drafts? Rendered draft files will remain on disk but their manifest will be replaced.')) return;+ try {+ await api(`/api/content/${encodeURIComponent(productionId)}/shorts/propose`, {+ method: 'POST', body: JSON.stringify({ count: 3, replace: replacing })+ });+ await refreshContentDialog(productionId, 'Three local Short drafts created from the current scene timeline.');+ } catch (error) {+ showToast(error.message, 'error');+ }+ return;+ }++ const shortAction = event.target.closest('[data-short-save], [data-short-render], [data-short-approve]');+ if (shortAction) {+ const card = shortAction.closest('[data-short-card]');+ const productionId = $('#content-review-form')?.dataset.productionId;+ const clipId = card?.dataset.shortCard;+ if (!productionId || !clipId) return;+ try {+ const values = shortFormData(card);+ await api(`/api/content/${encodeURIComponent(productionId)}/shorts/${encodeURIComponent(clipId)}`, {+ method: 'PATCH', body: JSON.stringify(values)+ });+ if (shortAction.matches('[data-short-save]')) {+ await refreshContentDialog(productionId, 'Short draft saved.');+ return;+ }+ if (shortAction.matches('[data-short-render]')) {+ await api(`/api/content/${encodeURIComponent(productionId)}/shorts/${encodeURIComponent(clipId)}/render`, {+ method: 'POST', body: '{}'+ });+ await refreshContentDialog(productionId, 'Vertical Short rendered locally with mobile captions.');+ return;+ }+ if (!confirm('Confirm the inherited evidence, media rights, privacy, and publish time for this Short?')) return;+ await api(`/api/content/${encodeURIComponent(productionId)}/shorts/${encodeURIComponent(clipId)}/approve`, {+ method: 'POST', body: JSON.stringify({ ...values, confirmed: true })+ });+ await refreshContentDialog(productionId, 'Short approved and added to the publishing schedule.');+ } catch (error) {+ showToast(error.message, 'error');+ }+ return;+ }+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]');diff --git a/dashboard/styles.css b/dashboard/styles.cssindex e49e51a..186de36 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -228,6 +228,24 @@ label small { color: var(--muted); font-weight: 400; }.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); }+.shorts-studio { display: grid; gap: 14px; border: 1px solid rgba(204,121,255,.3); background: rgba(204,121,255,.045); border-radius: 12px; padding: 14px; }+.shorts-heading { align-items: flex-start; margin: 0; }+.shorts-heading h3 { font-size: 17px; margin: 2px 0 0; }+.shorts-heading p:not(.eyebrow) { color: var(--muted); font-size: 12px; line-height: 1.45; margin: 6px 0 0; max-width: 680px; }+.shorts-evidence { display: flex; flex-wrap: wrap; gap: 7px; }+.shorts-evidence span { color: var(--amber); background: rgba(245,185,68,.09); border: 1px solid rgba(245,185,68,.2); border-radius: 999px; padding: 5px 9px; font-size: 10px; }+.shorts-evidence.ready span { color: var(--green); background: rgba(72,213,151,.07); border-color: rgba(72,213,151,.2); }+.shorts-grid { display: grid; gap: 13px; }+.short-card { display: grid; grid-template-columns: minmax(150px, 210px) minmax(0, 1fr); gap: 14px; border: 1px solid var(--line); border-radius: 11px; padding: 12px; background: rgba(7,10,14,.5); }+.short-preview { display: grid; place-items: center; width: 100%; max-height: 420px; aspect-ratio: 9 / 16; overflow: hidden; border: 1px solid var(--line); border-radius: 10px; background: #080a0d; }+.short-preview video { width: 100%; height: 100%; object-fit: contain; }+.short-placeholder { display: grid; place-items: center; gap: 4px; color: var(--muted); text-align: center; }+.short-placeholder strong { color: var(--text); font-size: 30px; letter-spacing: -.04em; }+.short-placeholder span { font-size: 10px; text-transform: uppercase; letter-spacing: .09em; }+.short-editor { display: grid; align-content: start; gap: 10px; min-width: 0; }+.short-rationale { color: var(--muted); font-size: 10px; line-height: 1.5; margin: 0; }+.short-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; border-top: 1px solid var(--line); padding-top: 10px; }+.short-actions .text-button, .short-actions .button { min-height: 42px; }.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; }@@ -282,6 +300,8 @@ label small { color: var(--muted); font-weight: 400; }.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; }+ .short-card { grid-template-columns: 1fr; }+ .short-preview { max-width: 230px; justify-self: center; }.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.jsindex 9fde2fc..ec7636a 100644--- a/database/db.js+++ b/database/db.js@@ -348,6 +348,35 @@ class Database {FOREIGN KEY (production_id) REFERENCES productions(id),FOREIGN KEY (scene_id) REFERENCES production_scenes(id))`,+ `CREATE TABLE IF NOT EXISTS shorts_clips (+ id TEXT PRIMARY KEY,+ production_id TEXT NOT NULL,+ position INTEGER NOT NULL,+ title TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ tags TEXT NOT NULL DEFAULT '[]',+ source_scene_ids TEXT NOT NULL DEFAULT '[]',+ start_seconds REAL NOT NULL DEFAULT 0,+ duration REAL NOT NULL DEFAULT 30,+ layout TEXT NOT NULL DEFAULT 'blur',+ rationale TEXT,+ status TEXT NOT NULL DEFAULT 'proposed',+ output_path TEXT,+ captions_path TEXT,+ publish_time TEXT,+ privacy_status TEXT DEFAULT 'private',+ inherited_evidence TEXT NOT NULL DEFAULT '{}',+ rendered_at TEXT,+ approved_at TEXT,+ schedule_id TEXT,+ youtube_id TEXT,+ youtube_url TEXT,+ error TEXT,+ 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 channel_profiles (id TEXT PRIMARY KEY,channel_name TEXT,@@ -696,6 +725,7 @@ class Database {const provenance = await this.getContentProvenance(productionId);const scenes = await this.listProductionScenes(productionId);const sceneRevisions = scenes.length ? await this.listProductionSceneRevisions(productionId, 50) : [];+ const shorts = await this.listShortClips(productionId);return {...row,assets: JSON.parse(row.assets || '{}'),@@ -712,7 +742,8 @@ class Database {summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }},scenes,- sceneRevisions+ sceneRevisions,+ shorts};}@@ -1079,6 +1110,88 @@ class Database {} : null;}+ async replaceShortClips(productionId, clips = []) {+ await this.executeQuery('DELETE FROM shorts_clips WHERE production_id = ?', [productionId]);+ for (const [position, clip] of clips.entries()) {+ const id = clip.id || this.generateId('short');+ await this.executeQuery(+ `INSERT INTO shorts_clips (+ id, production_id, position, title, description, tags, source_scene_ids,+ start_seconds, duration, layout, rationale, status, output_path, captions_path,+ publish_time, privacy_status, inherited_evidence, rendered_at, approved_at,+ schedule_id, youtube_id, youtube_url, error+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ [+ id, productionId, position, clip.title, clip.description || '', JSON.stringify(clip.tags || []),+ JSON.stringify(clip.sourceSceneIds || []), Number(clip.startSeconds || 0), Number(clip.duration || 30),+ clip.layout || 'blur', clip.rationale || null, clip.status || 'proposed', clip.outputPath || null,+ clip.captionsPath || null, clip.publishTime || null, clip.privacyStatus || 'private',+ JSON.stringify(clip.inheritedEvidence || {}), clip.renderedAt || null, clip.approvedAt || null,+ clip.scheduleId || null, clip.youtubeId || null, clip.youtubeUrl || null, clip.error || null+ ]+ );+ }+ return this.listShortClips(productionId);+ }++ async listShortClips(productionId) {+ const rows = await this.getAllRows(+ 'SELECT * FROM shorts_clips WHERE production_id = ? ORDER BY position, created_at',+ [productionId]+ );+ return rows.map(row => this.parseShortClip(row));+ }++ async getShortClip(id) {+ return this.parseShortClip(await this.getRow('SELECT * FROM shorts_clips WHERE id = ?', [id]));+ }++ async updateShortClip(id, changes = {}) {+ const current = await this.getShortClip(id);+ if (!current) return null;+ const next = { ...current, ...changes };+ await this.executeQuery(+ `UPDATE shorts_clips SET+ title = ?, description = ?, tags = ?, source_scene_ids = ?, start_seconds = ?,+ duration = ?, layout = ?, rationale = ?, status = ?, output_path = ?, captions_path = ?,+ publish_time = ?, privacy_status = ?, inherited_evidence = ?, rendered_at = ?, approved_at = ?,+ schedule_id = ?, youtube_id = ?, youtube_url = ?, error = ?, updated_at = datetime('now')+ WHERE id = ?`,+ [+ next.title, next.description || '', JSON.stringify(next.tags || []), JSON.stringify(next.sourceSceneIds || []),+ Number(next.startSeconds || 0), Number(next.duration || 30), next.layout || 'blur', next.rationale || null,+ next.status || 'proposed', next.outputPath || null, next.captionsPath || null, next.publishTime || null,+ next.privacyStatus || 'private', JSON.stringify(next.inheritedEvidence || {}), next.renderedAt || null,+ next.approvedAt || null, next.scheduleId || null, next.youtubeId || null, next.youtubeUrl || null,+ next.error || null, id+ ]+ );+ return this.getShortClip(id);+ }++ parseShortClip(row) {+ if (!row) return null;+ return {+ ...row,+ productionId: row.production_id,+ position: Number(row.position),+ tags: JSON.parse(row.tags || '[]'),+ sourceSceneIds: JSON.parse(row.source_scene_ids || '[]'),+ startSeconds: Number(row.start_seconds || 0),+ duration: Number(row.duration || 0),+ outputPath: row.output_path || null,+ captionsPath: row.captions_path || null,+ publishTime: row.publish_time || null,+ privacyStatus: row.privacy_status || 'private',+ inheritedEvidence: JSON.parse(row.inherited_evidence || '{}'),+ renderedAt: row.rendered_at || null,+ approvedAt: row.approved_at || null,+ scheduleId: row.schedule_id || null,+ youtubeId: row.youtube_id || null,+ youtubeUrl: row.youtube_url || null+ };+ }+async markInterruptedJobs() {await this.executeQuery(`UPDATE generation_jobs SET status = 'interrupted',@@ -1639,24 +1752,35 @@ class Database {}async getPublishedContentContext(youtubeId) {- const row = await this.getRow(- `SELECT sch.production_id, sch.published_at, sch.title, ps.strategy, ps.script, ps.thumbnail, ps.seo,- cr.editor_data- FROM publish_schedule sch- LEFT JOIN production_snapshots ps ON ps.production_id = sch.production_id- LEFT JOIN content_reviews cr ON cr.production_id = sch.production_id- WHERE sch.youtube_id = ? ORDER BY sch.published_at DESC LIMIT 1`,+ const schedule = await this.getRow(+ `SELECT production_id, published_at, title, metadata+ FROM publish_schedule WHERE youtube_id = ? ORDER BY published_at DESC LIMIT 1`,[youtubeId]);- if (!row) return {};+ if (!schedule) return {};+ const metadata = JSON.parse(schedule.metadata || '{}');+ const sourceProductionId = metadata.sourceProductionId || schedule.production_id;+ const row = await this.getRow(+ `SELECT ps.strategy, ps.script, ps.thumbnail, ps.seo, cr.editor_data+ FROM production_snapshots ps+ LEFT JOIN content_reviews cr ON cr.production_id = ps.production_id+ WHERE ps.production_id = ?`,+ [sourceProductionId]+ ) || {};const editorData = JSON.parse(row.editor_data || '{}');const thumbnail = JSON.parse(row.thumbnail || '{}');const selectedThumbnail = editorData.packagingExperiment?.thumbnailVariants?.[editorData.selectedThumbnailVariant];+ const isShort = metadata.contentType === 'short';+ const strategy = JSON.parse(row.strategy || '{}');return {- productionId: row.production_id,- publishedAt: row.published_at,- title: editorData.title || row.title,- strategy: JSON.parse(row.strategy || '{}'),+ productionId: sourceProductionId,+ shortClipId: metadata.shortClipId || null,+ contentFormat: isShort ? 'short' : 'long_form',+ publishedAt: schedule.published_at,+ title: isShort ? schedule.title : editorData.title || schedule.title,+ strategy: isShort+ ? { ...strategy, contentType: 'shorts', requestedStyle: 'shorts', requestedLengthKey: 'short' }+ : strategy,script: JSON.parse(row.script || '{}'),thumbnail: selectedThumbnail?.concept ? { ...thumbnail, concept: selectedThumbnail.concept } : thumbnail,seo: JSON.parse(row.seo || '{}')diff --git a/index.js b/index.jsindex 601f1db..0cfbee1 100644--- a/index.js+++ b/index.js@@ -22,6 +22,7 @@ const { ProductionReadinessService } = require('./utils/production-readiness-serconst { GenerationRecoveryService, GENERATION_STAGES } = require('./utils/generation-recovery-service');const { ProvenanceService } = require('./utils/provenance-service');const { SceneRepairService } = require('./utils/scene-repair-service');+const { ShortsRepurposingService } = require('./utils/shorts-repurposing-service');const { version } = require('./package.json');const chalk = require('chalk');@@ -42,6 +43,7 @@ class YouTubeAutomationAgent {this.recovery = null;this.provenance = null;this.scenes = null;+ this.shorts = null;this.setupRequired = false;}@@ -98,6 +100,7 @@ class YouTubeAutomationAgent {this.agents.production?.aiVideoGenerator,{ logger: this.logger });+ this.shorts = new ShortsRepurposingService(this.db, this.agents.publishing, { logger: this.logger });// Show which pipeline stages will run for real vs. be simulatedconst capabilities = await this.logCapabilitySummary();@@ -399,7 +402,8 @@ class YouTubeAutomationAgent {if (!this.agents.publishing) return res.status(503).json({ success: false, error: 'YouTube publishing is not configured' });const { contentId } = req.params;const bundle = await this.db.getProductionBundle(contentId);- if (!bundle || bundle.review_status !== 'approved') {+ const short = bundle ? null : await this.db.getShortClip(contentId);+ if ((!bundle || bundle.review_status !== 'approved') && (!short || !['scheduled', 'uploading', 'reconciliation_required'].includes(short.status))) {return res.status(409).json({ success: false, error: 'Content must pass review and be approved before publishing' });}const result = await this.agents.publishing.publishContent(contentId);@@ -566,6 +570,62 @@ class YouTubeAutomationAgent {}});+ this.app.post('/api/content/:productionId/shorts/propose', protect, async (req, res) => {+ try {+ if (!this.shorts) return res.status(503).json({ error: 'Shorts repurposing requires completed setup' });+ const result = await this.shorts.propose(req.params.productionId, req.body || {});+ return res.json({ success: true, result });+ } catch (error) {+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });+ }+ });++ this.app.patch('/api/content/:productionId/shorts/:clipId', protect, async (req, res) => {+ try {+ if (!this.shorts) return res.status(503).json({ error: 'Shorts repurposing requires completed setup' });+ const result = await this.shorts.update(req.params.productionId, req.params.clipId, req.body || {});+ return res.json({ success: true, result });+ } catch (error) {+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });+ }+ });++ this.app.post('/api/content/:productionId/shorts/:clipId/render', protect, async (req, res) => {+ try {+ if (!this.shorts) return res.status(503).json({ error: 'Shorts repurposing requires completed setup' });+ const result = await this.shorts.render(req.params.productionId, req.params.clipId);+ return res.status(202).json({ success: true, result });+ } catch (error) {+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });+ }+ });++ this.app.post('/api/content/:productionId/shorts/:clipId/approve', protect, async (req, res) => {+ try {+ if (!this.shorts) return res.status(503).json({ error: 'Shorts repurposing requires completed setup' });+ const result = await this.shorts.approve(req.params.productionId, req.params.clipId, req.body || {});+ return res.json({ success: true, result });+ } catch (error) {+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });+ }+ });++ this.app.get('/api/content/:productionId/shorts/:clipId/asset/:kind', async (req, res) => {+ try {+ const clip = await this.db.getShortClip(req.params.clipId);+ if (!clip || clip.productionId !== req.params.productionId) return res.status(404).json({ error: 'Short asset not found' });+ const filePath = req.params.kind === 'video' ? clip.outputPath : req.params.kind === 'captions' ? clip.captionsPath : null;+ if (!filePath) return res.status(404).json({ error: 'Short asset not found' });+ const resolved = path.resolve(filePath);+ const shortsRoot = path.resolve(__dirname, 'data', 'shorts');+ if (!resolved.startsWith(`${shortsRoot}${path.sep}`)) return res.status(403).json({ error: 'Short asset path is not allowed' });+ await fs.access(resolved);+ return res.sendFile(resolved);+ } catch (_error) {+ return res.status(404).json({ error: 'Short asset not found' });+ }+ });+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' });@@ -1320,11 +1380,20 @@ class YouTubeAutomationAgent {decorateContentBundle(bundle) {const experiment = bundle.editorData?.packagingExperiment;+ const sceneLabels = new Map((bundle.scenes || []).map(scene => [scene.id, scene.label]));return {...bundle,scenes: (bundle.scenes || []).map(scene => this.scenes? this.scenes.decorateScene(scene, bundle.id): scene),+ shorts: (bundle.shorts || []).map(clip => ({+ ...clip,+ sourceSceneLabels: clip.sourceSceneIds.map(id => sceneLabels.get(id)).filter(Boolean),+ assetUrls: {+ video: clip.outputPath ? `/api/content/${bundle.id}/shorts/${clip.id}/asset/video` : null,+ captions: clip.captionsPath ? `/api/content/${bundle.id}/shorts/${clip.id}/asset/captions` : null+ }+ })),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,diff --git a/test.js b/test.jsindex bd4196a..298e48c 100644--- a/test.js+++ b/test.js@@ -29,6 +29,7 @@ class SystemTest {{ 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: 'Shorts Repurposing Studio', test: () => this.testShortsRepurposingStudio() },{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },@@ -1102,6 +1103,118 @@ class SystemTest {this.logger.info('Narration reliability and recovery test completed successfully');}+ async testShortsRepurposingStudio() {+ const fs = require('fs').promises;+ const os = require('os');+ const { runFFmpeg } = require('./utils/ffmpeg');+ const { ShortsRepurposingService } = require('./utils/shorts-repurposing-service');+ const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');+ const { ChannelLearningEngine } = require('./utils/channel-learning-engine');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-shorts-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'shorts.db');+ await db.initialize();++ try {+ const productionId = 'prod-shorts-studio';+ const sourceVideo = path.join(directory, 'source.mp4');+ const audioPath = path.join(directory, 'narration.m4a');+ const thumbnailPath = path.join(directory, 'thumbnail.jpg');+ await runFFmpeg([+ '-y', '-f', 'lavfi', '-i', 'color=c=#203a5f:s=640x360:r=24:d=4',+ '-f', 'lavfi', '-i', 'sine=frequency=440:duration=4',+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', sourceVideo+ ]);+ await fs.writeFile(audioPath, Buffer.from('narration evidence'));+ await fs.writeFile(thumbnailPath, Buffer.from('thumbnail evidence'));+ const production = {+ id: productionId, status: 'scheduled',+ strategy: { topic: 'Repurpose one production', contentType: 'tutorial' },+ script: { title: 'Repurpose one production', fullScript: 'A complete source script for producing several useful vertical excerpts from one approved production.'.repeat(4) },+ seo: {+ title: 'Repurpose one production',+ description: 'A detailed source description for a safe and efficient vertical repurposing workflow.',+ tags: ['repurposing', 'shorts', 'workflow']+ },+ assets: {+ finalVideo: { path: sourceVideo, simulated: false, duration: 4 },+ audio: { path: audioPath, status: 'ready', simulated: false, provider: 'fixture-tts' },+ thumbnail: { path: thumbnailPath }+ },+ timeline: {}, priority: 50,+ scheduledPublishTime: new Date(Date.now() + 86400000).toISOString()+ };+ await db.saveProductionData(production);+ await db.saveProductionSnapshot(production);+ await db.saveContentReview(productionId, {+ status: 'approved', editorData: { factChecked: true, rightsConfirmed: true },+ qualityChecks: [], reviewedAt: new Date().toISOString()+ });+ await db.saveContentProvenance(productionId, {+ sources: [], claims: [], containsSyntheticMedia: true, status: 'not_required',+ summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }+ });+ await db.replaceProductionScenes(productionId, [+ { id: 'short-source-1', label: 'Hook', scriptText: 'One strong idea can reach more than one audience.', prompt: 'Opening', duration: 1.4, assetType: 'video', assetPath: sourceVideo, audioPath, status: 'ready', narrationStatus: 'current', rightsConfirmed: true },+ { id: 'short-source-2', label: 'Method', scriptText: 'Use the approved scene evidence to build a vertical excerpt.', prompt: 'Method', duration: 1.3, assetType: 'video', assetPath: sourceVideo, audioPath, status: 'ready', narrationStatus: 'current', rightsConfirmed: true },+ { id: 'short-source-3', label: 'Result', scriptText: 'Render locally and review every Short before it reaches the schedule.', prompt: 'Result', duration: 1.3, assetType: 'video', assetPath: sourceVideo, audioPath, status: 'ready', narrationStatus: 'current', rightsConfirmed: true }+ ]);++ const publishing = new PublishingSchedulingAgent(db, {});+ const service = new ShortsRepurposingService(db, publishing, {+ dataRoot: path.join(directory, 'shorts'), width: 360, height: 640, logger: this.logger+ });+ const proposed = await service.propose(productionId, { count: 3 });+ if (proposed.length !== 3 || proposed.some(clip => !clip.sourceSceneIds.length || clip.status !== 'proposed')) {+ throw new Error('Short drafts did not preserve source-scene identity');+ }+ const edited = await service.update(productionId, proposed[0].id, {+ title: 'One approved video, three vertical moments', layout: 'blur',+ tags: ['Shorts', 'repurposing', 'workflow']+ });+ if (edited.title.length > 100 || edited.layout !== 'blur') throw new Error('Short draft edits did not persist');+ const rendered = await service.render(productionId, edited.id);+ if (rendered.status !== 'rendered' || !rendered.outputPath || !rendered.captionsPath) {+ throw new Error('Local vertical rendering did not persist its MP4 and captions');+ }+ await runFFmpeg(['-v', 'error', '-i', rendered.outputPath, '-f', 'null', '-']);++ let approvalBlocked = false;+ try {+ await service.approve(productionId, rendered.id, {});+ } catch (error) {+ approvalBlocked = error.code === 'SHORT_APPROVAL_REQUIRED';+ }+ if (!approvalBlocked) throw new Error('Short scheduling bypassed explicit approval confirmation');+ const scheduled = await service.approve(productionId, rendered.id, {+ confirmed: true, publishTime: new Date(Date.now() + 172800000).toISOString(), privacyStatus: 'private'+ });+ const schedule = await db.getLatestScheduleEntry(rendered.id);+ if (+ scheduled.status !== 'scheduled' || !schedule || schedule.metadata.contentType !== 'short' ||+ schedule.metadata.sourceProductionId !== productionId || schedule.metadata.containsSyntheticMedia !== true+ ) {+ throw new Error('Approved Short did not inherit evidence into an independent schedule entry');+ }+ schedule.status = 'published';+ schedule.youtubeId = 'youtube-short-1';+ schedule.youtubeUrl = 'https://www.youtube.com/shorts/youtube-short-1';+ schedule.publishedAt = new Date().toISOString();+ await db.updateScheduleEntry(schedule);+ await publishing.syncShortStatus(schedule, 'published');+ const published = await db.getShortClip(rendered.id);+ const context = await db.getPublishedContentContext('youtube-short-1');+ const attributes = new ChannelLearningEngine(db).extractAttributes({ videoDetails: { title: published.title } }, context);+ if (published.status !== 'published' || context.contentFormat !== 'short' || attributes.surface !== 'shorts' || attributes.format !== 'shorts') {+ throw new Error('Published Short did not remain separate in analytics learning context');+ }+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }+ this.logger.info('Shorts Repurposing Studio test completed successfully');+ }+async testProvenanceDesk() {const fs = require('fs').promises;const os = require('os');diff --git a/utils/channel-learning-engine.js b/utils/channel-learning-engine.jsindex 5c20bc8..467887c 100644--- a/utils/channel-learning-engine.js+++ b/utils/channel-learning-engine.js@@ -10,11 +10,11 @@ class ChannelLearningEngine {async capture(performanceReport, context = {}, measurementWindow = 'rolling') {const metrics = this.normalizeMetrics(performanceReport);const attributes = this.extractAttributes(performanceReport, context);- const prior = await this.db.listPerformanceSnapshots({+ const prior = (await this.db.listPerformanceSnapshots({measurementWindow,reliableOnly: true,excludeVideoId: performanceReport.videoId- });+ })).filter(snapshot => (snapshot.contentAttributes?.surface || 'long_form') === attributes.surface);const baseline = this.calculateBaseline(prior);const simulated = Boolean(performanceReport.analytics?.simulated);const confidence = simulated ? 'unverified' : this.confidenceFor(metrics);@@ -65,7 +65,10 @@ class ChannelLearningEngine {const hook = this.text(script.hook || script.introduction || '');return {topic: strategy.topic || '',- format: this.slug(strategy.requestedStyle || strategy.contentType || 'unknown'),+ surface: context.contentFormat === 'short' ? 'shorts' : 'long_form',+ format: context.contentFormat === 'short'+ ? 'shorts'+ : this.slug(strategy.requestedStyle || strategy.contentType || 'unknown'),length: this.slug(strategy.requestedLengthKey || strategy.requestedLength || 'unknown'),hookLength: hook ? (this.wordCount(hook) <= 40 ? 'concise' : 'extended') : 'unknown',titleLength: title ? (this.wordCount(title) <= 9 ? 'concise' : 'long') : 'unknown',diff --git a/utils/shorts-repurposing-service.js b/utils/shorts-repurposing-service.jsnew file mode 100644index 0000000..701d72d--- /dev/null+++ b/utils/shorts-repurposing-service.js@@ -0,0 +1,381 @@+const fs = require('fs').promises;+const path = require('path');+const { runFFmpeg } = require('./ffmpeg');+const { Logger } = require('./logger');++const LAYOUTS = new Set(['blur', 'crop', 'stacked']);++function clamp(value, minimum, maximum) {+ return Math.min(maximum, Math.max(minimum, Number(value) || minimum));+}++function sentence(value = '') {+ return String(value).trim().split(/(?<=[.!?])\s+/)[0]?.trim() || '';+}++function truncate(value, maximum) {+ const normalized = String(value || '').replace(/\s+/g, ' ').trim();+ if (normalized.length <= maximum) return normalized;+ return `${normalized.slice(0, Math.max(0, maximum - 1)).trim()}…`;+}++function srtTime(seconds) {+ const milliseconds = Math.max(0, Math.round(Number(seconds || 0) * 1000));+ const hours = Math.floor(milliseconds / 3600000);+ const minutes = Math.floor((milliseconds % 3600000) / 60000);+ const secs = Math.floor((milliseconds % 60000) / 1000);+ const millis = milliseconds % 1000;+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')},${String(millis).padStart(3, '0')}`;+}++class ShortsRepurposingService {+ constructor(db, publishing, options = {}) {+ this.db = db;+ this.publishing = publishing;+ this.logger = options.logger || new Logger('ShortsRepurposing');+ this.dataRoot = options.dataRoot || path.join(__dirname, '..', 'data', 'shorts');+ this.width = Number(options.width || 1080);+ this.height = Number(options.height || 1920);+ this.runFFmpeg = options.runFFmpeg || runFFmpeg;+ }++ async propose(productionId, input = {}) {+ const bundle = await this.requireSource(productionId);+ const existing = await this.db.listShortClips(productionId);+ if (existing.length && input.replace !== true) return existing;+ if (existing.some(clip => ['approved', 'scheduled', 'uploading', 'published', 'reconciliation_required'].includes(clip.status))) {+ const error = new Error('Approved, scheduled, or published Shorts cannot be replaced');+ error.status = 409;+ throw error;+ }++ const count = Math.round(clamp(input.count || 3, 1, 5));+ const sourceScenes = bundle.scenes || [];+ const scenes = sourceScenes.filter(scene =>+ scene.assetPath && scene.status === 'ready' &&+ ['current', 'intentional_silence'].includes(scene.narrationStatus)+ );+ if (!scenes.length || scenes.length !== sourceScenes.length) {+ const error = new Error('Every source scene must be rebuilt and current before creating Short drafts');+ error.status = 409;+ throw error;+ }++ const sourceTitle = bundle.editorData?.title || bundle.seo?.title || bundle.script?.title || bundle.strategy?.topic || 'Untitled video';+ const windows = this.selectWindows(scenes, count);+ const baseTime = this.nextPublishBase(bundle);+ const inheritedEvidence = this.inheritedEvidence(bundle);+ const clips = windows.map((window, position) => {+ const lead = window.scenes[0];+ const hook = sentence(lead.scriptText) || lead.label || sourceTitle;+ const title = truncate(hook, 96);+ return {+ productionId,+ position,+ title,+ description: truncate(`A quick takeaway from ${sourceTitle}. Watch the full video on this channel. #Shorts`, 5000),+ tags: [...new Set([...(bundle.seo?.tags || []), 'Shorts'])].slice(0, 15),+ sourceSceneIds: window.scenes.map(scene => scene.id),+ startSeconds: window.startSeconds,+ duration: window.duration,+ layout: position === 1 ? 'crop' : position === 2 ? 'stacked' : 'blur',+ rationale: `Selected from ${window.scenes.map(scene => scene.label).join(', ')} as a self-contained vertical excerpt.`,+ status: 'proposed',+ publishTime: new Date(baseTime.getTime() + position * 86400000).toISOString(),+ privacyStatus: 'private',+ inheritedEvidence+ };+ });+ return this.db.replaceShortClips(productionId, clips);+ }++ selectWindows(scenes, requestedCount) {+ const timeline = [];+ let cursor = 0;+ for (const scene of scenes) {+ const duration = clamp(scene.duration || 5, 1, 180);+ timeline.push({ ...scene, startSeconds: cursor, duration });+ cursor += duration;+ }+ const count = Math.min(requestedCount, timeline.length);+ const anchorIndexes = [];+ for (let index = 0; index < count; index++) {+ anchorIndexes.push(Math.min(timeline.length - 1, Math.floor(index * timeline.length / count)));+ }+ return [...new Set(anchorIndexes)].map(anchorIndex => {+ const selected = [timeline[anchorIndex]];+ let total = selected[0].duration;+ let next = anchorIndex + 1;+ while (total < 20 && next < timeline.length && total + timeline[next].duration <= 60) {+ selected.push(timeline[next]);+ total += timeline[next].duration;+ next++;+ }+ let previous = anchorIndex - 1;+ while (total < 15 && previous >= 0 && total + timeline[previous].duration <= 60) {+ selected.unshift(timeline[previous]);+ total += timeline[previous].duration;+ previous--;+ }+ return {+ scenes: selected,+ startSeconds: selected[0].startSeconds,+ duration: Math.min(180, total)+ };+ });+ }++ async update(productionId, clipId, input = {}) {+ const clip = await this.requireClip(productionId, clipId);+ if (['approved', 'scheduled', 'uploading', 'published', 'reconciliation_required'].includes(clip.status)) {+ const error = new Error('This Short is locked after approval');+ error.status = 409;+ throw error;+ }+ const changes = {};+ if (input.title !== undefined) {+ const title = String(input.title).trim();+ if (!title || title.length > 100) throw new Error('Short title must be between 1 and 100 characters');+ changes.title = title;+ }+ if (input.description !== undefined) changes.description = String(input.description).trim().slice(0, 5000);+ if (input.tags !== undefined) {+ const tags = Array.isArray(input.tags) ? input.tags : String(input.tags).split(',');+ changes.tags = [...new Set(tags.map(tag => String(tag).trim()).filter(Boolean))].slice(0, 30);+ }+ if (input.layout !== undefined) {+ if (!LAYOUTS.has(input.layout)) throw new Error('Short layout must be blur, crop, or stacked');+ changes.layout = input.layout;+ }+ if (input.publishTime !== undefined) {+ const date = new Date(input.publishTime);+ if (Number.isNaN(date.getTime())) throw new Error('Short publish time is invalid');+ changes.publishTime = date.toISOString();+ }+ if (input.privacyStatus !== undefined) {+ if (!['private', 'unlisted', 'public'].includes(input.privacyStatus)) throw new Error('Short privacy is invalid');+ changes.privacyStatus = input.privacyStatus;+ }+ if (clip.status === 'rendered' && Object.keys(changes).some(key => ['layout'].includes(key))) {+ changes.status = 'proposed';+ changes.outputPath = null;+ changes.captionsPath = null;+ }+ return this.db.updateShortClip(clipId, changes);+ }++ async render(productionId, clipId) {+ const bundle = await this.requireSource(productionId);+ const clip = await this.requireClip(productionId, clipId);+ if (['approved', 'scheduled', 'uploading', 'published', 'reconciliation_required'].includes(clip.status)) {+ const error = new Error('This Short is locked after approval');+ error.status = 409;+ throw error;+ }+ const sourceVideo = bundle.assets?.finalVideo?.path;+ await this.requireFile(sourceVideo, 'The approved source MP4 is missing');+ const sourceScenes = (bundle.scenes || []).filter(scene => clip.sourceSceneIds.includes(scene.id));+ if (!sourceScenes.length) throw new Error('The selected source scenes no longer exist');++ const directory = path.join(this.dataRoot, productionId);+ await fs.mkdir(directory, { recursive: true });+ const outputPath = path.join(directory, `${clip.id}.mp4`);+ const captionsPath = path.join(directory, `${clip.id}.srt`);+ await fs.writeFile(captionsPath, this.buildCaptions(sourceScenes, clip.duration), 'utf8');+ await this.db.updateShortClip(clip.id, { status: 'rendering', error: null });++ try {+ const filter = this.videoFilter(clip.layout, captionsPath);+ await this.runFFmpeg([+ '-y', '-ss', String(clip.startSeconds), '-i', sourceVideo, '-t', String(clip.duration),+ '-filter_complex', filter, '-map', '[shortv]', '-map', '0:a:0?',+ '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '21',+ '-c:a', 'aac', '-b:a', '160k', '-movflags', '+faststart', '-shortest', outputPath+ ]);+ await this.runFFmpeg(['-v', 'error', '-i', outputPath, '-f', 'null', '-']);+ const stats = await fs.stat(outputPath);+ if (!stats.isFile() || stats.size <= 0) throw new Error('FFmpeg returned an empty Short');+ return this.db.updateShortClip(clip.id, {+ status: 'rendered', outputPath, captionsPath, error: null,+ renderedAt: new Date().toISOString()+ });+ } catch (error) {+ await this.db.updateShortClip(clip.id, { status: 'failed', error: error.message });+ throw error;+ }+ }++ videoFilter(layout, captionsPath) {+ const escapedCaptions = path.resolve(captionsPath)+ .replaceAll('\\', '/')+ .replace(':', '\\:')+ .replaceAll("'", "\\'");+ const subtitles = `subtitles='${escapedCaptions}':force_style='FontName=Arial,FontSize=18,Bold=1,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=3,Shadow=1,Alignment=2,MarginV=170'`;+ if (layout === 'crop') {+ return `[0:v]scale=${this.width}:${this.height}:force_original_aspect_ratio=increase,crop=${this.width}:${this.height},${subtitles},fps=30,format=yuv420p[shortv]`;+ }+ if (layout === 'stacked') {+ const foregroundHeight = Math.round(this.height * 0.56);+ const y = Math.round(this.height * 0.13);+ return `[0:v]split=2[bg][fg];` ++ `[bg]scale=${this.width}:${this.height}:force_original_aspect_ratio=increase,crop=${this.width}:${this.height},boxblur=28:3[soft];` ++ `[fg]scale=${this.width}:${foregroundHeight}:force_original_aspect_ratio=decrease[front];` ++ `[soft][front]overlay=(W-w)/2:${y},${subtitles},fps=30,format=yuv420p[shortv]`;+ }+ return `[0:v]split=2[bg][fg];` ++ `[bg]scale=${this.width}:${this.height}:force_original_aspect_ratio=increase,crop=${this.width}:${this.height},boxblur=28:3[soft];` ++ `[fg]scale=${this.width}:${this.height}:force_original_aspect_ratio=decrease[front];` ++ `[soft][front]overlay=(W-w)/2:(H-h)/2,${subtitles},fps=30,format=yuv420p[shortv]`;+ }++ buildCaptions(scenes, duration) {+ const chunks = [];+ for (const scene of scenes) {+ const words = String(scene.scriptText || scene.label || '').trim().split(/\s+/).filter(Boolean);+ for (let index = 0; index < words.length; index += 7) chunks.push(words.slice(index, index + 7).join(' '));+ }+ if (!chunks.length) chunks.push('Watch the full video for more.');+ const segment = Number(duration || 1) / chunks.length;+ return chunks.map((text, index) => {+ const start = index * segment;+ const end = Math.min(Number(duration || 1), (index + 1) * segment);+ const captionEnd = Math.min(Number(duration || 1), Math.max(start + 0.5, end));+ return `${index + 1}\n${srtTime(start)} --> ${srtTime(captionEnd)}\n${text}\n`;+ }).join('\n');+ }++ async approve(productionId, clipId, input = {}) {+ if (input.confirmed !== true) {+ const error = new Error('Confirm the inherited evidence and Short schedule before approval');+ error.status = 409;+ error.code = 'SHORT_APPROVAL_REQUIRED';+ throw error;+ }+ const bundle = await this.requireSource(productionId);+ const clip = await this.requireClip(productionId, clipId);+ if (bundle.review_status !== 'approved') {+ const error = new Error('Approve the source production before scheduling its Shorts');+ error.status = 409;+ throw error;+ }+ const evidence = this.inheritedEvidence(bundle);+ if (!evidence.ready) {+ const error = new Error(`Source evidence is incomplete: ${evidence.blockingReasons.join(', ')}`);+ error.status = 409;+ throw error;+ }+ if (clip.status !== 'rendered') {+ const error = new Error('Render the current Short draft before approval');+ error.status = 409;+ throw error;+ }+ await this.requireFile(clip.outputPath, 'The rendered Short MP4 is missing');+ const publishTime = new Date(input.publishTime || clip.publishTime);+ if (Number.isNaN(publishTime.getTime())) throw new Error('Choose a valid Short publish time');+ const privacyStatus = input.privacyStatus || clip.privacyStatus || 'private';+ if (!['private', 'unlisted', 'public'].includes(privacyStatus)) throw new Error('Short privacy is invalid');+ const parentUrl = bundle.schedule?.youtube_url || bundle.schedule?.youtubeUrl;+ const description = parentUrl && !clip.description.includes(parentUrl)+ ? `${clip.description}\n\nWatch the full video: ${parentUrl}`.slice(0, 5000)+ : clip.description;+ const audio = bundle.assets?.audio || {};+ const schedule = await this.publishing.scheduleContent({+ id: clip.id,+ script: { title: clip.title },+ seo: {+ title: clip.title,+ description,+ tags: [...new Set([...(clip.tags || []), 'Shorts'])]+ },+ assets: {+ finalVideo: { path: clip.outputPath, simulated: false, aspectRatio: '9:16', duration: clip.duration },+ audio,+ captions: clip.captionsPath ? { path: clip.captionsPath } : null,+ thumbnail: null+ },+ scheduledPublishTime: publishTime.toISOString(),+ priority: 60,+ privacyStatus,+ containsSyntheticMedia: evidence.containsSyntheticMedia,+ contentType: 'short',+ sourceProductionId: productionId,+ shortClipId: clip.id+ });+ if (!schedule) {+ const error = new Error('The Short could not be scheduled because its rendered media or narration evidence is incomplete');+ error.status = 409;+ throw error;+ }+ return this.db.updateShortClip(clip.id, {+ status: 'scheduled', publishTime: publishTime.toISOString(), privacyStatus,+ inheritedEvidence: evidence, approvedAt: new Date().toISOString(), scheduleId: schedule.id,+ error: null+ });+ }++ inheritedEvidence(bundle) {+ const blockingReasons = [];+ if (bundle.review_status !== 'approved') blockingReasons.push('source approval');+ if (!['verified', 'not_required'].includes(bundle.provenance?.status || 'not_required')) blockingReasons.push('provenance review');+ const unlicensed = (bundle.scenes || []).filter(scene => scene.assetOrigin === 'uploaded' && !scene.rightsConfirmed);+ if (unlicensed.length) blockingReasons.push('media rights');+ const stale = (bundle.scenes || []).filter(scene =>+ !['ready'].includes(scene.status) || !['current', 'intentional_silence'].includes(scene.narrationStatus)+ );+ if (stale.length) blockingReasons.push('current scene evidence');+ return {+ ready: blockingReasons.length === 0,+ blockingReasons,+ sourceReviewStatus: bundle.review_status || 'needs_review',+ provenanceStatus: bundle.provenance?.status || 'not_required',+ rightsConfirmed: unlicensed.length === 0,+ containsSyntheticMedia: bundle.provenance?.containsSyntheticMedia === true,+ capturedAt: new Date().toISOString()+ };+ }++ nextPublishBase(bundle) {+ const sourceTime = new Date(bundle.schedule?.publish_time || bundle.schedule?.published_at || bundle.scheduled_publish_time || Date.now());+ const minimum = new Date(Date.now() + 3600000);+ const candidate = Number.isNaN(sourceTime.getTime()) ? minimum : new Date(sourceTime.getTime() + 86400000);+ return candidate > minimum ? candidate : minimum;+ }++ async requireSource(productionId) {+ const bundle = await this.db.getProductionBundle(productionId);+ if (!bundle) {+ const error = new Error('Source production not found');+ error.status = 404;+ throw error;+ }+ if (!bundle.assets?.finalVideo?.path || bundle.assets.finalVideo.simulated) {+ const error = new Error('A real source MP4 is required before creating Shorts');+ error.status = 409;+ throw error;+ }+ return bundle;+ }++ async requireClip(productionId, clipId) {+ const clip = await this.db.getShortClip(clipId);+ if (!clip || clip.productionId !== productionId) {+ const error = new Error('Short draft not found');+ error.status = 404;+ throw error;+ }+ return clip;+ }++ async requireFile(filePath, message) {+ try {+ const stats = await fs.stat(filePath);+ if (!stats.isFile() || stats.size <= 0) throw new Error(message);+ } catch (_error) {+ const error = new Error(message);+ error.status = 409;+ throw error;+ }+ }+}++module.exports = { ShortsRepurposingService, LAYOUTS };