🎬 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
fix: resolve reported production issues
darkzOGx124a1ed18e47
diff --git a/.env.example b/.env.exampleindex b13af87..44db0b6 100644--- a/.env.example+++ b/.env.example@@ -53,12 +53,14 @@# FFmpeg (optional override; resolution order: FFMPEG_PATH > bundled ffmpeg-static > system PATH)# FFMPEG_PATH=-# DarkzSEO discoverability preflight (optional, advisory)-# Install DarkzSEO 1.4+ into Python, or point to a sibling/source checkout.+# DarkzSEO discoverability preflight (bundled and advisory; external checkout optional)# DARKZSEO_PYTHON=python# DARKZSEO_PATH=../darkzseo/darkzseo.py# DARKZSEO_TIMEOUT_MS=30000+# Optional OAuth loopback override; Desktop app credentials are required.+# YOUTUBE_REDIRECT_URI=http://127.0.0.1+# Azure Speech TTS (optional alternative)# AZURE_SPEECH_KEY=your-azure-speech-key-here# AZURE_SPEECH_REGION=eastusdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 010c1b6..3a214e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@## Unreleased+- Bundled the DarkzSEO-compatible content audit so the preflight no longer depends on the unpublished 1.4 Python package; external 1.4+ checkouts remain opt-in through `DARKZSEO_PATH`+- Fixed regenerated narration timing, CTA metadata and template-placeholder speech leaks, configured visual-style propagation, and null manual strategy contexts+- Added explicit reschedule, publish-now, and delete-schedule controls while keeping generated content when a schedule is removed+- Fixed YouTube OAuth to use the configured loopback redirect URI instead of generating a mismatched callback+## v2.10.0 — 2026-08-24- Added a versioned DarkzSEO discoverability preflight over a shell-free Python stdin/stdout adapter, with explicit unavailable and schema-mismatch statesdiff --git a/README.md b/README.mdindex c024e28..4ff350b 100644--- a/README.md+++ b/README.md@@ -20,12 +20,12 @@ Research topics → write scripts → generate narration and visuals → assembl- **DarkzSEO Discoverability Preflight:** send a canonical content package—not the private dashboard—through versioned GEO, AIO, AEO, and web-search checks after metadata and provenance are assembled.- **Reviewable evidence:** persist stable rule IDs, severity, engine/schema identity, fingerprints, and operator decisions in SQLite. Keep a finding actionable or dismiss a false positive with a reason that carries into matching future audits.-- **Safe local adapter boundary:** invoke DarkzSEO through JSON-only stdin/stdout without a shell or inherited API secrets. Missing Python, timeouts, and schema drift stay explicit and non-blocking.+- **Safe local adapter boundary:** run the bundled content checks without Python; optional external DarkzSEO checkouts still use JSON-only stdin/stdout without a shell or inherited API secrets.- **Controlled Growth Experiments Studio:** rotate only approved title/thumbnail arms, measure real interval evidence, restore the control, and require a separate decision before adopting a winner.- **Outcome & ROI Studio:** align the operator with a measurable KPI, target window, budget, and available revenue/cost evidence without converting missing economics into false zeroes.- **Platform-ready foundation:** audits already retain their target platform, providing the durable contract for planned TikTok and Instagram/Reels publishing and analytics adapters.-DarkzSEO is optional. Install DarkzSEO 1.4+ into Python or set `DARKZSEO_PATH`; when it is unavailable, AgentTube records the reason and keeps the existing approval workflow operational.+The content preflight works out of the box. Set `DARKZSEO_PATH` only when developing against a separate DarkzSEO 1.4+ checkout.See the complete release history in [CHANGELOG.md](CHANGELOG.md).@@ -97,17 +97,17 @@ Use the altered or synthetic media control only when the video contains realisti### Review discoverability guidance-Every saved production receives an optional **DarkzSEO Discoverability Preflight** in Review Studio after metadata and provenance are assembled. The adapter sends a canonical content package—not the private dashboard—to DarkzSEO's versioned JSON API and stores the engine version, schema version, severity summary, stable rule IDs, and individual findings in SQLite.+Every saved production receives an optional **DarkzSEO Discoverability Preflight** in Review Studio after metadata and provenance are assembled. The bundled content auditor reviews a canonical content package—not the private dashboard—and stores the engine version, schema version, severity summary, stable rule IDs, and individual findings in SQLite.-Findings are advisory in this release. Keep a useful recommendation as actionable, or dismiss a false positive with a reviewer reason that carries forward to matching findings on later audits. Missing Python, an unavailable DarkzSEO installation, timeouts, and schema mismatches remain explicit without blocking publication or silently changing scripts and metadata.+Findings are advisory in this release. Keep a useful recommendation as actionable, or dismiss a false positive with a reviewer reason that carries forward to matching findings on later audits. The bundled audit requires no Python package and never silently changes scripts or metadata.-For local development with a sibling checkout:+To test a separate DarkzSEO 1.4+ checkout instead of the bundled auditor:```bash-python -m pip install -e ../darkzseo+DARKZSEO_PATH=../darkzseo/darkzseo.py npm start```-Alternatively set `DARKZSEO_PATH` to `darkzseo.py`. The adapter uses a shell-free Python child process, sends content JSON over stdin, and reads JSON-only stdout. DarkzSEO 1.4 or newer is required.+The optional external adapter uses a shell-free Python child process, sends content JSON over stdin, and reads JSON-only stdout. The public PyPI `darkzseo` 1.3.3 package has a different site-audit CLI and is not used by AgentTube.### What you need@@ -115,7 +115,7 @@ Alternatively set `DARKZSEO_PATH` to `darkzseo.py`. The adapter uses a shell-fre- A Google account and YouTube Data API credentials- At least one AI text provider key- FFmpeg, installed automatically through `ffmpeg-static`-- Python 3.9+ and DarkzSEO 1.4+ for the optional discoverability preflight+- Python 3.9+ only when explicitly testing an external DarkzSEO checkoutGemini offers free access for supported text and TTS usage. Gemini AI image generation currently requires paid-tier access; without an image provider, Lumen can assemble gradient-based visuals instead.@@ -266,8 +266,8 @@ Long-form productions use hybrid assembly: Lumen generates bounded provider clip1. Create a project in [Google Cloud Console](https://console.cloud.google.com/)2. Enable **YouTube Data API v3**-3. Create an OAuth 2.0 client (Desktop app)-4. Save the JSON as `config/credentials.json`+3. Create an OAuth 2.0 client (**Desktop app**, not Web application)+4. Save the JSON as `config/credentials.json`; AgentTube uses its configured loopback redirect URI exactly#### OpenAIdiff --git a/agents/production-management-agent.js b/agents/production-management-agent.jsindex 9980b9b..6109a2c 100644--- a/agents/production-management-agent.js+++ b/agents/production-management-agent.js@@ -302,9 +302,11 @@ class ProductionManagementAgent {// Generate visual assets using DALL-Econst visualPrompts = this.createVisualPromptsFromScript(script);const visualAssets = [];+ const profile = await this.db.getChannelProfile?.() || {};+ const visualStyle = profile.visual_style || 'ethereal';for (const prompt of visualPrompts) {- const assets = await this.aiVideoGenerator.generateVisualAssets(prompt, 'ethereal', 1);+ const assets = await this.aiVideoGenerator.generateVisualAssets(prompt, visualStyle, 1);visualAssets.push(...assets);}@@ -659,20 +661,20 @@ class ProductionManagementAgent {const prompts = [];// Title prompt- prompts.push(`${script.title}, ethereal storytelling, mystical background`);+ prompts.push(`${script.title}, clear visual storytelling`);// Content-based promptsif (script.mainContent && script.mainContent.sections) {script.mainContent.sections.forEach(section => {if (section.title) {- prompts.push(`${section.title}, ethereal dreamscape, creative visualization`);+ prompts.push(`${section.title}, relevant explanatory visual`);}});}// Ensure we have at least 3 promptswhile (prompts.length < 3) {- prompts.push('ethereal dreamscape, mystical storytelling, creative visualization');+ prompts.push(`${script.title || 'Video topic'}, supporting explanatory visual`);}return prompts.slice(0, 5); // Limit to 5 for cost controldiff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.jsindex 1ef0d54..efd563f 100644--- a/agents/publishing-scheduling-agent.js+++ b/agents/publishing-scheduling-agent.js@@ -98,7 +98,7 @@ class PublishingSchedulingAgent {}}- async publishContent(contentId) {+ async publishContent(contentId, options = {}) {try {let productionBundle = null;if (this.db.getLatestReadinessRun) {@@ -158,7 +158,7 @@ class PublishingSchedulingAgent {let uploadResult;try {- uploadResult = await this.uploadToYouTube(scheduleEntry);+ uploadResult = await this.uploadToYouTube(scheduleEntry, options);} catch (error) {if (scheduleEntry.uploadAttempted && this.isUploadOutcomeUnknown(error)) {scheduleEntry.status = 'reconciliation_required';@@ -196,7 +196,7 @@ class PublishingSchedulingAgent {}}- async uploadToYouTube(scheduleEntry) {+ async uploadToYouTube(scheduleEntry, options = {}) {const { metadata } = scheduleEntry;const validation = assertValidYouTubeMetadata(metadata.seo);if (validation.warnings.length) {@@ -205,6 +205,9 @@ class PublishingSchedulingAgent {const safeMetadata = validation.value;// Prepare video metadata+ const requestedPrivacy = metadata.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private';+ const scheduledFor = new Date(scheduleEntry.publishTime);+ const futureSchedule = !options.publishNow && Number.isFinite(scheduledFor.getTime()) && scheduledFor.getTime() > Date.now() + 60000;const videoMetadata = {snippet: {title: safeMetadata.title,@@ -215,12 +218,12 @@ class PublishingSchedulingAgent {defaultAudioLanguage: safeMetadata.defaultAudioLanguage},status: {- privacyStatus: metadata.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',- publishAt: scheduleEntry.publishTime,+ privacyStatus: futureSchedule ? 'private' : requestedPrivacy,selfDeclaredMadeForKids: false,containsSyntheticMedia: metadata.containsSyntheticMedia === true}};+ if (futureSchedule) videoMetadata.status.publishAt = scheduleEntry.publishTime;// Resolve the file before marking the network upload as attempted.const videoStream = await this.getVideoStream(metadata.video.path);@@ -628,24 +631,18 @@ class PublishingSchedulingAgent {async emergencyPublish(contentId, delayMinutes = 0) {// For urgent publishing needsthis.logger.info(`Emergency publish requested: ${contentId}`);-- const entry = this.publishQueue.find(e =>- e.productionId === contentId || e.id === contentId- );-- if (!entry) {- throw new Error(`Content not found: ${contentId}`);- }-+if (delayMinutes > 0) {+ const entry = this.publishQueue.find(e => e.productionId === contentId || e.id === contentId) ||+ await this.db.getLatestScheduleEntry?.(contentId);+ if (!entry) throw new Error(`Content not found: ${contentId}`);const newPublishTime = new Date(Date.now() + (delayMinutes * 60 * 1000));entry.publishTime = newPublishTime.toISOString();await this.db.updateScheduleEntry(entry);this.logger.info(`Emergency scheduled for: ${entry.publishTime}`);return entry;- } else {- return await this.publishContent(contentId);}+ return this.publishContent(contentId, { publishNow: true });}async pauseScheduledContent(contentId) {@@ -683,6 +680,53 @@ class PublishingSchedulingAgent {this.logger.info(`Content resumed: ${entry.title}`);return entry;}++ async rescheduleContent(contentId, newPublishTime) {+ const publishTime = new Date(newPublishTime);+ if (!Number.isFinite(publishTime.getTime()) || publishTime.getTime() <= Date.now()) {+ const error = new Error('Choose a future publish time');+ error.status = 400;+ throw error;+ }+ const entry = this.publishQueue.find(item => item.productionId === contentId || item.id === contentId) ||+ await this.db.getLatestScheduleEntry?.(contentId);+ if (!entry) {+ const error = new Error(`Scheduled content not found: ${contentId}`);+ error.status = 404;+ throw error;+ }+ if (['uploading', 'uploaded', 'published', 'reconciliation_required'].includes(entry.status)) {+ const error = new Error(`Content cannot be rescheduled while it is ${entry.status}`);+ error.status = 409;+ throw error;+ }+ entry.publishTime = publishTime.toISOString();+ entry.status = 'scheduled';+ entry.error = null;+ await this.db.updateScheduleEntry(entry);+ if (!this.publishQueue.some(item => item.id === entry.id)) this.publishQueue.push(entry);+ this.publishQueue.sort((a, b) => new Date(a.publishTime) - new Date(b.publishTime));+ return entry;+ }++ async deleteScheduledContent(contentId) {+ const entry = this.publishQueue.find(item => item.productionId === contentId || item.id === contentId) ||+ await this.db.getLatestScheduleEntry?.(contentId);+ if (!entry) {+ const error = new Error(`Scheduled content not found: ${contentId}`);+ error.status = 404;+ throw error;+ }+ if (['uploading', 'uploaded', 'published', 'reconciliation_required'].includes(entry.status)) {+ const error = new Error(`The schedule cannot be deleted while content is ${entry.status}`);+ error.status = 409;+ throw error;+ }+ await this.db.deleteScheduleEntry(entry.id);+ this.publishQueue = this.publishQueue.filter(item => item.id !== entry.id);+ await this.syncShortStatus(entry, 'rendered');+ return entry;+ }}module.exports = { PublishingSchedulingAgent };diff --git a/config/credentials.example.json b/config/credentials.example.jsonindex d5e410b..42d38f9 100644--- a/config/credentials.example.json+++ b/config/credentials.example.json@@ -3,7 +3,7 @@"client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com","client_secret": "YOUR_CLIENT_SECRET","redirect_uris": [- "urn:ietf:wg:oauth:2.0:oob"+ "http://127.0.0.1"]},"openai": {diff --git a/dashboard/app.js b/dashboard/app.jsindex 6c75f95..f4b44d0 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -994,7 +994,7 @@ async function openContent(productionId) {const title = data.title || item.seo?.title || item.script?.title || item.strategy?.topic || 'Untitled content';const description = data.description || item.seo?.description || '';const tags = data.tags || item.seo?.tags || [];- const publishTime = data.publishTime || item.schedule?.publish_time || item.scheduled_publish_time;+ const publishTime = item.schedule?.publish_time || data.publishTime || item.scheduled_publish_time;const canReview = !['published'].includes(item.schedule?.status);const experiment = data.packagingExperiment;const selectedTitleVariant = Number(data.selectedTitleVariant || 0);@@ -1031,6 +1031,7 @@ async function openContent(productionId) {<label class="toggle"><input name="factChecked" type="checkbox" ${data.factChecked ? 'checked' : ''}><span></span> Facts and claims reviewed</label><label class="toggle"><input name="rightsConfirmed" type="checkbox" ${data.rightsConfirmed ? 'checked' : ''}><span></span> Media rights confirmed</label></div>+ ${item.schedule && !['published', 'uploading', 'uploaded', 'reconciliation_required'].includes(item.schedule.status) ? `<div class="form-actions"><button type="button" class="button secondary" data-reschedule-content="${escapeHTML(item.id)}">Reschedule</button><button type="button" class="button primary" data-publish-now-content="${escapeHTML(item.id)}">Publish now</button><button type="button" class="button danger" data-delete-schedule="${escapeHTML(item.id)}">Delete schedule</button></div>` : ''}${canReview ? `<div class="form-actions"><button type="button" class="button primary" data-approve-content="${escapeHTML(item.id)}">Approve & schedule</button><button type="button" class="button secondary" data-save-content="${escapeHTML(item.id)}">Save draft</button><button type="button" class="button danger" data-reject-content="${escapeHTML(item.id)}">Reject</button><button type="button" class="button ghost" data-retry-content="${escapeHTML(item.id)}">Regenerate</button></div>` : `<a class="button secondary" href="${escapeHTML(item.schedule?.youtube_url || '#')}" target="_blank" rel="noopener">Open on YouTube</a>`}</form>`;$('#content-review-form').dataset.productionId = item.id;@@ -1550,6 +1551,37 @@ document.addEventListener('click', async event => {} catch (_error) { /* toast already shown */ }}+ const reschedule = event.target.closest('[data-reschedule-content]');+ if (reschedule) {+ const publishTime = contentFormData().publishTime;+ if (!publishTime) return showToast('Choose a future publish time first.', 'error');+ try {+ await mutate(`/api/content/${encodeURIComponent(reschedule.dataset.rescheduleContent)}/schedule`, 'PATCH', { publishTime }, 'Content rescheduled.');+ await openContent(reschedule.dataset.rescheduleContent);+ } catch (_error) { /* toast already shown */ }+ return;+ }++ const publishNow = event.target.closest('[data-publish-now-content]');+ if (publishNow) {+ if (!confirm('Publish this video to YouTube now using the selected privacy setting?')) return;+ try {+ await mutate(`/api/content/${encodeURIComponent(publishNow.dataset.publishNowContent)}/publish-now`, 'POST', {}, 'Content published.');+ $('#content-dialog').close();+ } catch (_error) { /* toast already shown */ }+ return;+ }++ const deleteSchedule = event.target.closest('[data-delete-schedule]');+ if (deleteSchedule) {+ if (!confirm('Delete this schedule entry? The generated content and assets will be kept.')) return;+ try {+ await mutate(`/api/content/${encodeURIComponent(deleteSchedule.dataset.deleteSchedule)}/schedule`, 'DELETE', undefined, 'Schedule deleted; generated content was kept.');+ await openContent(deleteSchedule.dataset.deleteSchedule);+ } catch (_error) { /* toast already shown */ }+ return;+ }+const reject = event.target.closest('[data-reject-content]');if (reject) {const notes = prompt('Why are you rejecting this content?', 'Needs a different angle');diff --git a/database/db.js b/database/db.jsindex ba62182..3f15dfd 100644--- a/database/db.js+++ b/database/db.js@@ -1811,6 +1811,10 @@ class Database {);}+ async deleteScheduleEntry(id) {+ await this.executeQuery('DELETE FROM publish_schedule WHERE id = ?', [id]);+ }+async getLatestScheduleEntry(productionId) {const row = await this.getRow('SELECT * FROM publish_schedule WHERE production_id = ? ORDER BY created_at DESC LIMIT 1',diff --git a/index.js b/index.jsindex 8bc5cf6..ad96736 100644--- a/index.js+++ b/index.js@@ -988,6 +988,39 @@ class YouTubeAutomationAgent {}});+ this.app.patch('/api/content/:productionId/schedule', protect, async (req, res) => {+ try {+ if (!this.agents.publishing) return res.status(503).json({ error: 'Publishing requires completed setup' });+ const result = await this.agents.publishing.rescheduleContent(req.params.productionId, req.body?.publishTime);+ await this.db.updateProductionStatus(req.params.productionId, 'scheduled');+ 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/publish-now', protect, async (req, res) => {+ try {+ if (!this.agents.publishing) return res.status(503).json({ error: 'Publishing requires completed setup' });+ const result = await this.agents.publishing.emergencyPublish(req.params.productionId);+ await this.db.updateProductionStatus(req.params.productionId, result.status);+ 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.delete('/api/content/:productionId/schedule', protect, async (req, res) => {+ try {+ if (!this.agents.publishing) return res.status(503).json({ error: 'Publishing requires completed setup' });+ const result = await this.agents.publishing.deleteScheduledContent(req.params.productionId);+ await this.db.updateProductionStatus(req.params.productionId, 'approved');+ 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/discoverability/findings/:findingId', protect, async (req, res) => {try {const finding = await this.discoverability.reviewFinding(req.params.findingId, req.body || {});@@ -1408,7 +1441,8 @@ class YouTubeAutomationAgent {async generateContent(topic = null, style = null, length = 'medium', options = {}) {this.logger.info('Starting content generation pipeline...');- const { jobId = null, strategyContext = {} } = options;+ const { jobId = null, strategyContext: rawStrategyContext = {} } = options;+ const strategyContext = rawStrategyContext || {};const profile = await this.db.getChannelProfile() || {};const lengthLabels = { short: '2-4 minutes', medium: '8-12 minutes', long: '15-20 minutes' };diff --git a/modern-auth.js b/modern-auth.jsindex 10712f3..d451cfd 100644--- a/modern-auth.js+++ b/modern-auth.js@@ -19,9 +19,8 @@ class ModernAuth {try {const credentials = JSON.parse(fs.readFileSync(this.credentialsPath));- // Use a random high port to avoid conflicts- const port = 8000 + Math.floor(Math.random() * 1000);- const redirectUri = `http://localhost:${port}/callback`;+ const redirect = this.resolveRedirect(credentials);+ const redirectUri = redirect.uri;const oauth2Client = new google.auth.OAuth2(credentials.youtube.client_id,@@ -37,8 +36,17 @@ class ModernAuth {'https://www.googleapis.com/auth/youtube.force-ssl'];- // Start a temporary local server- await this.startTempServer(port, oauth2Client);+ const authResult = new Promise((resolve, reject) => {+ this.resolveAuth = resolve;+ this.rejectAuth = reject;+ this.authTimeout = setTimeout(() => {+ this.cleanup();+ reject(new Error('Authentication timeout (5 minutes)'));+ }, 300000);+ });++ // Start a temporary local server at the exact redirect URI used in the OAuth request.+ await this.startTempServer(redirect, oauth2Client);// Generate auth URLconst authUrl = oauth2Client.generateAuthUrl({@@ -60,33 +68,52 @@ class ModernAuth {if (openCommands[process.platform]) {exec(openCommands[process.platform], () => {});}- console.log(chalk.yellow(`\n⚡ A temporary server is running on port ${port}`));+ console.log(chalk.yellow(`\n⚡ A temporary server is running on port ${redirect.port}`));console.log(chalk.yellow('After authorization, you\'ll be redirected automatically.'));console.log(chalk.gray('Waiting for authorization...'));// The server will handle the rest- return new Promise((resolve, reject) => {- this.resolveAuth = resolve;- this.rejectAuth = reject;-- // Set timeout- setTimeout(() => {- this.cleanup();- reject(new Error('Authentication timeout (5 minutes)'));- }, 300000); // 5 minutes- });+ return authResult;} catch (error) {+ this.cleanup();console.error(chalk.red('Authentication failed:'), error.message);throw error;}}- async startTempServer(port, oauth2Client) {+ resolveRedirect(credentials) {+ const explicitRedirect = process.env.YOUTUBE_REDIRECT_URI;+ const configured = [explicitRedirect, ...(credentials.youtube?.redirect_uris || [])].filter(Boolean);+ const legacyGeneratedRedirect = /^http:\/\/localhost:8080\/(?:oauth2callback|callback)\/?$/i;+ let redirect = null;+ for (const value of configured) {+ if (!explicitRedirect && legacyGeneratedRedirect.test(value)) continue;+ try {+ const candidate = new URL(value);+ if (candidate.protocol === 'http:' && ['localhost', '127.0.0.1', '::1'].includes(candidate.hostname)) {+ redirect = candidate;+ break;+ }+ } catch (_error) {+ // Ignore obsolete out-of-band and malformed redirect values.+ }+ }+ redirect ||= new URL('http://127.0.0.1/');+ if (!redirect.port) redirect.port = String(8000 + Math.floor(Math.random() * 1000));+ return {+ uri: redirect.toString(),+ hostname: redirect.hostname,+ port: Number(redirect.port),+ pathname: redirect.pathname || '/'+ };+ }++ async startTempServer(redirect, oauth2Client) {this.server = http.createServer(async (req, res) => {- const url = new URL(req.url, `http://localhost:${port}`);+ const url = new URL(req.url, redirect.uri);- if (url.pathname === '/callback') {+ if (url.pathname === redirect.pathname) {const code = url.searchParams.get('code');const error = url.searchParams.get('error');@@ -148,11 +175,18 @@ class ModernAuth {}});- this.server.listen(port, 'localhost');- console.log(chalk.gray(`Temporary OAuth server started on port ${port}`));+ await new Promise((resolve, reject) => {+ this.server.once('error', reject);+ this.server.listen(redirect.port, redirect.hostname, resolve);+ });+ console.log(chalk.gray(`Temporary OAuth server started on ${redirect.uri}`));}cleanup() {+ if (this.authTimeout) {+ clearTimeout(this.authTimeout);+ this.authTimeout = null;+ }if (this.server) {this.server.close();this.server = null;@@ -226,4 +260,4 @@ if (require.main === module) {runAuth();}-module.exports = { ModernAuth };\ No newline at end of file+module.exports = { ModernAuth };diff --git a/test.js b/test.jsindex a88a5c8..a735ca3 100644--- a/test.js+++ b/test.js@@ -37,6 +37,7 @@ class SystemTest {{ name: 'Shorts Repurposing Studio', test: () => this.testShortsRepurposingStudio() },{ name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },{ name: 'DarkzSEO Discoverability Preflight', test: () => this.testDiscoverabilityPreflight() },+ { name: 'Open Issue Regressions', test: () => this.testOpenIssueRegressions() },{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },@@ -1191,8 +1192,15 @@ class SystemTest {fullScript: 'A complete factual-review-safe script for testing selective scene repair without replacing the entire production.',hook: { text: 'Fix one weak moment without starting over.' },introduction: { greeting: 'Hello.', topicIntro: 'Scene repair matters.', valueProposition: 'Save time and credits.' },- mainContent: { sections: [{ title: 'Selective repair', content: 'Keep the scenes that work and replace only the scene that does not.' }] },- conclusion: { recap: ['Preserve good work.'], finalThought: 'Review the repaired timeline.' }+ mainContent: { sections: [+ { title: 'Selective repair', content: 'Keep the scenes that work and replace only the scene that does not.' },+ { title: 'Examples', content: ['Example 1: [Specific case study]', 'A real example without template markers.'] }+ ] },+ conclusion: { recap: ['Preserve good work.'], finalThought: 'Review the repaired timeline.' },+ callToAction: {+ type: 'call_to_action', duration: '15 seconds', subscribe: 'Subscribe.', like: 'Like.',+ comment: 'Comment.', nextVideo: 'Watch the next video.'+ }},seo: { title: 'Repair one scene', description: 'A detailed description of selective scene repair for video production workflows.', tags: ['video', 'repair', 'workflow'] },strategy: { topic: 'Selective scene repair' },@@ -1214,11 +1222,20 @@ class SystemTest {sources: [], claims: [], containsSyntheticMedia: false, status: 'not_required',summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }});+ await db.saveChannelProfile({ channelName: 'Test channel', visualStyle: 'animated' });const manifest = buildInitialSceneManifest(production, { actualProvider: 'slideshow', model: 'local-ffmpeg' });if (manifest.length < 3 || manifest.some(scene => scene.assetPath !== imagePath)) {throw new Error('Initial scene manifest did not preserve the script structure and visual assets');}+ const examplesScene = manifest.find(scene => scene.label === 'Examples');+ const ctaScene = manifest.find(scene => scene.label === 'Call to action');+ if (/\[[^\]]*\]/.test(examplesScene?.scriptText || '') || examplesScene?.scriptText !== 'A real example without template markers.') {+ throw new Error('Template placeholders leaked into scene narration');+ }+ if (ctaScene?.scriptText !== 'Subscribe. Like. Comment. Watch the next video.') {+ throw new Error('Call-to-action metadata leaked into spoken narration');+ }await db.replaceProductionScenes(production.id, manifest);for (const scene of await db.listProductionScenes(production.id)) {await db.updateProductionScene(production.id, scene.id, {@@ -1235,10 +1252,12 @@ class SystemTest {id: 'seedance', model: 'seedance-test',normalizeRequest: request => ({ ...request, duration: Math.min(4, Number(request.duration || 4)) })};+ let useSlideshow = false;+ let regeneratedVisualStyle = null;const fakeGenerator = {mediaGeneration: {settings: async () => ({ provider: 'seedance', order: ['seedance'], clipDuration: 4, resolution: '720p', aspectRatio: '16:9' }),- registry: { select: () => fakeProvider, get: () => fakeProvider },+ registry: { select: () => useSlideshow ? { id: 'slideshow' } : fakeProvider, get: () => fakeProvider },generateClip: async ({ outputPath }) => {await fs.mkdir(path.dirname(outputPath), { recursive: true });await fs.writeFile(outputPath, Buffer.from('generated scene video'));@@ -1246,7 +1265,7 @@ class SystemTest {},isValidVideo: async () => true},- generateVisualAssets: async () => [imagePath],+ generateVisualAssets: async (_prompt, style) => { regeneratedVisualStyle = style; return [imagePath]; },async generateTTSAudio(_text, outputPath) {await fs.writeFile(outputPath, Buffer.from('scene narration'));this.lastNarrationResult = {@@ -1291,6 +1310,11 @@ class SystemTest {) {throw new Error('Confirmed selective regeneration did not persist visual and narration evidence');}+ useSlideshow = true;+ await service.regenerate(production.id, roundTrip[1].id);+ if (regeneratedVisualStyle !== 'animated') {+ throw new Error('Scene regeneration ignored the configured channel visual style');+ }const second = roundTrip[1];const replacement = await sharp({ create: { width: 320, height: 180, channels: 3, background: '#ad3d45' } }).png().toBuffer();@@ -1405,7 +1429,9 @@ class SystemTest {},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 });+ const service = new SceneRepairService(db, generator, {+ dataRoot: directory, logger: this.logger, getMediaDuration: async () => 5.25+ });let confirmationBlocked = false;try {@@ -1429,7 +1455,7 @@ class SystemTest {if (recovered.narrationStatus !== 'current' || recovered.narrationProvider !== 'openai' ||recovered.narrationModel !== 'gpt-4o-mini-tts' || recovered.narrationTaskId !== 'tts-task-1' ||- recovered.status !== 'needs_rebuild'+ recovered.status !== 'needs_rebuild' || recovered.duration !== 5.75) {throw new Error('Narration-only recovery did not preserve provider evidence and rebuild state');}@@ -1713,6 +1739,7 @@ class SystemTest {const fs = require('fs').promises;const os = require('os');const { DiscoverabilityService } = require('./utils/discoverability-service');+ const { DarkzSEOAdapter } = require('./utils/discoverability-adapters/darkzseo');const { OperatorService } = require('./utils/operator-service');const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-discoverability-'));const db = new Database();@@ -1740,6 +1767,18 @@ class SystemTest {};try {+ const bundledReport = await new DarkzSEOAdapter({ scriptPath: null }).audit({+ id: 'bundled-audit', platform: 'youtube', brand: 'AgentTube', title: 'Best workflow review',+ description: 'A useful comparison.', transcript: 'Detailed content '.repeat(100),+ sections: [{ title: 'What should you choose?', content: 'answer '.repeat(61) }]+ });+ if (+ bundledReport.engine.version !== '1.4.0-bundled' ||+ !bundledReport.findings.some(finding => finding.ruleId === 'aio.comparison_intent') ||+ !bundledReport.findings.some(finding => finding.ruleId === 'aio.direct_answer')+ ) {+ throw new Error('The bundled discoverability audit did not provide the public content contract');+ }await db.saveProductionData({id: productionId, status: 'needs_review', assets: {}, timeline: {},scheduledPublishTime: null, priority: 50, estimatedDuration: '1:00'@@ -1832,6 +1871,72 @@ class SystemTest {this.logger.info('DarkzSEO discoverability preflight test completed successfully');}+ async testOpenIssueRegressions() {+ const { ModernAuth } = require('./modern-auth');+ const { ProductionManagementAgent } = require('./agents/production-management-agent');+ const { YouTubeAutomationAgent } = require('./index');++ const auth = new ModernAuth();+ const fixedRedirect = auth.resolveRedirect({+ youtube: { redirect_uris: ['http://127.0.0.1'] }+ });+ if (fixedRedirect.hostname !== '127.0.0.1' || fixedRedirect.port < 8000 || fixedRedirect.pathname !== '/') {+ throw new Error('OAuth did not use a desktop-app loopback redirect with a local dynamic port');+ }++ const visualStyles = [];+ const productionAgent = Object.create(ProductionManagementAgent.prototype);+ productionAgent.db = { getChannelProfile: async () => ({ visual_style: 'animated' }) };+ productionAgent.logger = this.logger;+ productionAgent.aiVideoGenerator = {+ generateVisualAssets: async (prompt, style) => {+ visualStyles.push({ prompt, style });+ return [`asset-${visualStyles.length}.png`];+ }+ };+ const productionData = {+ script: { title: 'Configured visuals', mainContent: { sections: [{ title: 'Clear demonstration' }] } },+ assets: {}, timeline: {}, estimatedDuration: '1:00'+ };+ await productionAgent.generateVideoContent(productionData);+ if (!visualStyles.length || visualStyles.some(item => item.style !== 'animated' || /ethereal|mystical|dreamscape/i.test(item.prompt))) {+ throw new Error('Initial scene generation mixed hardcoded ethereal cues with the configured visual style');+ }++ const pipeline = new YouTubeAutomationAgent();+ pipeline.db = {+ getChannelProfile: async () => ({}),+ saveProductionData: async data => data.id,+ saveProductionSnapshot: async () => {},+ getSetting: async () => 'true',+ saveContentReview: async () => {},+ updateProductionStatus: async () => {}+ };+ pipeline.provenance = { initialize: async () => ({ sources: [], claims: [], status: 'not_required' }) };+ pipeline.operator = {+ runQualityChecks: async () => ({ passed: true, score: 100, checks: [], blockingFailures: [] }),+ notify: async () => {}+ };+ pipeline.preparePackagingExperiment = async () => null;+ pipeline.agents = {+ strategy: { generateContentStrategy: async () => ({ topic: 'Null context', angle: 'Original angle' }) },+ scriptWriter: { generateScript: async strategy => ({ title: strategy.topic, fullScript: 'Complete script.' }) },+ thumbnailDesigner: { generateThumbnail: async () => ({ path: 'thumbnail.png' }) },+ seoOptimizer: { optimize: async script => ({ title: script.title, description: 'Description', tags: ['test'] }) },+ production: { processContent: async input => ({+ id: 'null-context-production', status: 'ready', ...input, assets: {}, timeline: {},+ scheduledPublishTime: new Date(Date.now() + 86400000).toISOString(), priority: 50+ }) },+ publishing: { scheduleContent: async () => null }+ };+ const generated = await pipeline.generateContent(null, null, 'short', { strategyContext: null });+ if (generated.contentId !== 'null-context-production') {+ throw new Error('A null manual strategy context still prevented generation');+ }++ this.logger.info('Open issue regression test completed successfully');+ }+async testResumableGenerationCheckpoints() {const fs = require('fs').promises;const os = require('os');@@ -2173,6 +2278,40 @@ class SystemTest {throw new Error('A recorded YouTube upload was not reconciled idempotently');}+ let deletedScheduleId = null;+ const scheduleActions = new PublishingSchedulingAgent({+ updateScheduleEntry: async () => {},+ deleteScheduleEntry: async id => { deletedScheduleId = id; }+ }, {});+ scheduleActions.publishQueue = [{+ id: 'schedule-actions', productionId: 'prod-actions', title: 'Actions', status: 'scheduled',+ publishTime: new Date(Date.now() + 3600000).toISOString(), metadata: { audio: intentionalAudio }+ }];+ const future = new Date(Date.now() + 7200000).toISOString();+ const rescheduled = await scheduleActions.rescheduleContent('prod-actions', future);+ if (rescheduled.publishTime !== future || rescheduled.status !== 'scheduled') {+ throw new Error('Scheduled content could not be rescheduled');+ }+ await scheduleActions.deleteScheduledContent('prod-actions');+ if (deletedScheduleId !== 'schedule-actions' || scheduleActions.publishQueue.length) {+ throw new Error('Deleting a schedule did not preserve content while removing the queue entry');+ }++ let uploadMetadata = null;+ const immediate = new PublishingSchedulingAgent({ updateScheduleEntry: async () => {} }, {});+ immediate.youtube = {+ videos: { insert: async request => { uploadMetadata = request.requestBody; return { data: { id: 'youtube-now' } }; } },+ thumbnails: { set: async () => {} }, captions: { insert: async () => {} }+ };+ immediate.getVideoStream = async () => ({ fixture: true });+ await immediate.uploadToYouTube({+ id: 'schedule-now', publishTime: new Date().toISOString(),+ metadata: { seo: { title: 'Publish now', description: 'Immediate upload.', tags: ['test'] }, video: { path: 'fixture.mp4' }, privacyStatus: 'public' }+ }, { publishNow: true });+ if (uploadMetadata?.status?.privacyStatus !== 'public' || uploadMetadata?.status?.publishAt !== undefined) {+ throw new Error('Publish now still sent a stale scheduled publishAt value');+ }+this.logger.info('Publishing safety test completed successfully');}@@ -2362,7 +2501,9 @@ class SystemTest {}async testFFmpegResolution() {- const { getFFmpegPath, checkFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');+ const fs = require('fs').promises;+ const os = require('os');+ const { getFFmpegPath, getMediaDuration, checkFFmpeg, runFFmpeg, ffmpegInstallHint } = require('./utils/ffmpeg');const ffmpegPath = getFFmpegPath();if (typeof ffmpegPath !== 'string' || ffmpegPath.length === 0) {@@ -2378,6 +2519,18 @@ class SystemTest {throw new Error('ffmpegInstallHint did not return install guidance');}+ if (available) {+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-duration-'));+ try {+ const audioPath = path.join(directory, 'duration.m4a');+ await runFFmpeg(['-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', '-c:a', 'aac', audioPath]);+ const duration = await getMediaDuration(audioPath);+ if (duration < 0.9 || duration > 1.2) throw new Error(`Media duration probe returned ${duration}`);+ } finally {+ await fs.rm(directory, { recursive: true, force: true });+ }+ }+this.logger.info(`FFmpeg resolution test completed (binary: ${ffmpegPath}, available: ${available})`);}diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex 95a2723..ccd30a0 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -301,7 +301,8 @@ class AIVideoGenerator {abstract: "abstract art, geometric shapes, gradient colors, artistic composition"};- const enhancement = styleEnhancements[style] || styleEnhancements.ethereal;+ const normalizedStyle = String(style || '').trim().toLowerCase();+ const enhancement = styleEnhancements[normalizedStyle] || String(style || '').trim() || styleEnhancements.ethereal;return `${prompt}, ${enhancement}, high quality, 16:9 aspect ratio, digital art`;}diff --git a/utils/discoverability-adapters/darkzseo.js b/utils/discoverability-adapters/darkzseo.jsindex 24eb926..3b763dc 100644--- a/utils/discoverability-adapters/darkzseo.js+++ b/utils/discoverability-adapters/darkzseo.js@@ -2,11 +2,150 @@ const { spawn } = require('child_process');const fs = require('fs');const path = require('path');+const AUTHORITY_DOMAINS = [+ '.gov', '.edu', 'wikipedia.org', 'statista.com', 'nature.com',+ 'ncbi.nlm.nih.gov', 'scholar.google.com', 'pubmed.gov', 'cdc.gov',+ 'who.int', 'nih.gov', 'ieee.org', 'acm.org'+];+const COMPARISON_KEYWORDS = new Set(['vs', 'versus', 'best', 'compare', 'comparison', 'top', 'review']);+const QUESTION_WORDS = new Set(['what', 'how', 'why', 'when', 'where', 'which', 'who', 'can', 'does', 'is', 'are']);+const UNIT_PATTERN = /\b\d+\s*(kg|lbs?|oz|g|in|cm|mm|ft|m|km|mi|°[cf]|mph|kph|gb|mb|tb)\b/i;++function text(value) {+ if (Array.isArray(value)) return value.map(text).filter(Boolean).join(' ');+ if (value && typeof value === 'object') return text(value.text || value.content || value.description || '');+ return String(value || '').trim();+}++function words(value) {+ return text(value).match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu) || [];+}++function syllables(value) {+ let word = String(value || '').toLowerCase().replace(/[^a-z]/g, '');+ if (word.length <= 3) return 1;+ if (word.endsWith('e')) word = word.slice(0, -1);+ const groups = word.match(/[aeiouy]+/g);+ return Math.max(1, groups?.length || 1);+}++function hasAuthoritySource(sources) {+ return sources.some(source => {+ try {+ const hostname = new URL(String(source?.url || '')).hostname.toLowerCase();+ return AUTHORITY_DOMAINS.some(domain => hostname.endsWith(domain) || hostname.includes(domain));+ } catch (_error) {+ return false;+ }+ });+}++function auditContent(contentPackage = {}) {+ const target = String(contentPackage.id || contentPackage.contentId || '<content>');+ const platform = String(contentPackage.platform || 'generic').toLowerCase();+ const applicability = platform === 'generic' ? ['content'] : [platform, 'content'];+ const title = text(contentPackage.title);+ const description = text(contentPackage.description);+ const transcript = text(contentPackage.transcript || contentPackage.script);+ const brand = text(contentPackage.brand || 'Brand');+ const sources = Array.isArray(contentPackage.sources) ? contentPackage.sources : [];+ const sections = Array.isArray(contentPackage.sections) ? contentPackage.sections : [];+ const opening = words(`${title} ${description} ${transcript}`).slice(0, 200).join(' ');+ const combined = [title, description, transcript].filter(Boolean).join('\n');+ const findings = [];+ const addFinding = (ruleId, category, severity, message, remediation) => findings.push({+ ruleId, category, severity, file: target, message, remediation, applicability,+ timestamp: new Date().toISOString()+ });++ if (brand && brand.toLowerCase() !== 'brand' && !opening.toLowerCase().includes(brand.toLowerCase())) {+ addFinding(+ 'geo.entity_salience', 'GEO', 'MEDIUM',+ `Entity Salience: Brand "${brand}" missing from title/intro`,+ 'Mention the brand naturally in the title, description, or opening 200 words.'+ );+ }+ if (words(transcript).length >= 1000 && !hasAuthoritySource(sources)) {+ addFinding(+ 'geo.trust_network', 'GEO', 'HIGH',+ 'Trust Network: Long content lacks authority links',+ 'Attach at least one reviewer-verified authority source to long-form factual content.'+ );+ }+ if (title.toLowerCase().split(/\s+/).some(word => COMPARISON_KEYWORDS.has(word)) && !contentPackage.hasComparisonTable) {+ addFinding(+ 'aio.comparison_intent', 'AIO', 'HIGH',+ 'Comparison Intent Gap: Missing structured comparison',+ 'Add a clearly structured comparison segment with consistent criteria and an explicit conclusion.'+ );+ }+ transcript.split(/\n\s*\n+/).map(part => part.trim()).filter(Boolean).forEach((paragraph, index) => {+ if (words(paragraph).length > 150) {+ addFinding(+ 'aio.skimmability', 'AIO', 'MEDIUM',+ `Skimmability: Paragraph ${index + 1} exceeds 150 words`,+ 'Break the transcript section into shorter spoken beats or chapter-aligned paragraphs.'+ );+ }+ });+ for (const section of sections) {+ if (!section || typeof section !== 'object') continue;+ const heading = text(section.title || section.heading);+ const answer = text(section.content || section.text);+ const headingWords = heading.toLowerCase().split(/\s+/).filter(Boolean);+ if (!headingWords.length || (!QUESTION_WORDS.has(headingWords[0]) && !heading.endsWith('?'))) continue;+ if (!answer || words(answer).length > 60) {+ addFinding(+ 'aio.direct_answer', 'AIO', 'MEDIUM',+ `Direct Answer Void: Answer for "${heading.slice(0, 40)}" should be under 60 words`,+ 'Open the section with a direct answer under 60 words before adding detail.'+ );+ }+ const answerWords = words(answer);+ if (answerWords.length && answerWords.filter(word => syllables(word) >= 3).length / answerWords.length > 0.2) {+ addFinding(+ 'aeo.simplicity', 'AEO', 'MEDIUM',+ `Simplicity Score: Answer for "${heading.slice(0, 40)}" is too complex`,+ 'Use shorter words and sentences in the direct-answer portion of this section.'+ );+ }+ }+ if (UNIT_PATTERN.test(combined) && !contentPackage.unitsExplained) {+ addFinding(+ 'aeo.unit_clarity', 'AEO', 'LOW',+ 'Unit Clarity: Units appear without an explanatory expansion',+ 'Expand or explain the unit on first mention in narration, captions, or description.'+ );+ }++ const severity = { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0, INFO: 0 };+ const category = { SEO: 0, GEO: 0, AIO: 0, AEO: 0 };+ for (const finding of findings) {+ severity[finding.severity]++;+ category[finding.category]++;+ }+ const blocking = findings.some(finding => ['CRITICAL', 'HIGH'].includes(finding.severity));+ return {+ schemaVersion: '1.0',+ engine: { name: 'darkzseo', version: '1.4.0-bundled' },+ mode: 'content',+ target,+ status: blocking ? 'attention_required' : findings.length ? 'advisory' : 'passed',+ generatedAt: new Date().toISOString(),+ itemsScanned: 1,+ totalFindings: findings.length,+ summary: { severity, category },+ findings+ };+}+class DarkzSEOAdapter {constructor(options = {}) {this.spawnProcess = options.spawnProcess || spawn;this.python = options.python || process.env.DARKZSEO_PYTHON || (process.platform === 'win32' ? 'python' : 'python3');- this.scriptPath = options.scriptPath || this.resolveScriptPath();+ this.scriptPath = Object.prototype.hasOwnProperty.call(options, 'scriptPath')+ ? options.scriptPath+ : this.resolveScriptPath();this.timeoutMs = Number(options.timeoutMs || process.env.DARKZSEO_TIMEOUT_MS || 30000);this.maxOutputBytes = Number(options.maxOutputBytes || 2 * 1024 * 1024);}@@ -18,10 +157,10 @@ class DarkzSEOAdapter {}command() {- const target = this.scriptPath ? [this.scriptPath] : ['-m', 'darkzseo'];+ if (!this.scriptPath) return null;return {executable: this.python,- args: [...target, '--mode', 'content', '--input-json', '-', '--json-stdout', '--no-html', '--fail-on', 'none']+ args: [this.scriptPath, '--mode', 'content', '--input-json', '-', '--json-stdout', '--no-html', '--fail-on', 'none']};}@@ -39,6 +178,11 @@ class DarkzSEOAdapter {async audit(contentPackage) {const command = this.command();+ if (!command) return auditContent(contentPackage);+ return this.auditExternal(command, contentPackage);+ }++ async auditExternal(command, contentPackage) {return new Promise((resolve, reject) => {const child = this.spawnProcess(command.executable, command.args, {shell: false,@@ -106,4 +250,4 @@ class DarkzSEOAdapter {}}-module.exports = { DarkzSEOAdapter };+module.exports = { DarkzSEOAdapter, auditContent };diff --git a/utils/discoverability-service.js b/utils/discoverability-service.jsindex 36c602f..7967ce0 100644--- a/utils/discoverability-service.js+++ b/utils/discoverability-service.js@@ -15,7 +15,8 @@ class DiscoverabilityService {const provenance = production.provenance || {};const sourceSections = Array.isArray(script.sections)? script.sections- : Array.isArray(script.mainContent) ? script.mainContent : [];+ : Array.isArray(script.mainContent?.sections) ? script.mainContent.sections+ : Array.isArray(script.mainContent) ? script.mainContent : [];const sections = sourceSections.length? sourceSections.map(section => ({title: section.title || section.heading || '',diff --git a/utils/ffmpeg.js b/utils/ffmpeg.jsindex 48ab2c5..827b5e4 100644--- a/utils/ffmpeg.js+++ b/utils/ffmpeg.js@@ -1,4 +1,5 @@const { execFile } = require('child_process');+const fs = require('fs');const { promisify } = require('util');const execFileAsync = promisify(execFile);@@ -44,6 +45,40 @@ async function runFFmpeg(args) {return execFileAsync(getFFmpegPath(), args, { maxBuffer: 32 * 1024 * 1024 });}+function getFFprobePath() {+ if (process.env.FFPROBE_PATH) return process.env.FFPROBE_PATH;+ const ffmpegPath = getFFmpegPath();+ if (ffmpegPath !== 'ffmpeg') {+ const candidate = ffmpegPath.replace(/ffmpeg(\.exe)?$/i, 'ffprobe$1');+ if (candidate !== ffmpegPath && fs.existsSync(candidate)) return candidate;+ }+ return 'ffprobe';+}++async function getMediaDuration(filePath) {+ try {+ const { stdout } = await execFileAsync(getFFprobePath(), [+ '-v', 'error', '-show_entries', 'format=duration',+ '-of', 'default=noprint_wrappers=1:nokey=1', filePath+ ]);+ const duration = Number(String(stdout || '').trim());+ if (Number.isFinite(duration) && duration > 0) return duration;+ } catch (_error) {+ // The bundled ffmpeg-static package does not include ffprobe; use FFmpeg's metadata output below.+ }++ try {+ await runFFmpeg(['-i', filePath]);+ } catch (error) {+ const match = String(error.stderr || '').match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/i);+ if (match) {+ const duration = Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]);+ if (Number.isFinite(duration) && duration > 0) return duration;+ }+ }+ throw new Error(`Could not determine media duration for ${filePath}`);+}+function ffmpegInstallHint() {const hints = {win32: 'winget install Gyan.FFmpeg (then restart your terminal)',@@ -55,4 +90,4 @@ function ffmpegInstallHint() {return `FFmpeg not found. Install it with: ${platformHint} — or run "npm install" again to fetch the bundled ffmpeg-static binary, or set FFMPEG_PATH to your ffmpeg executable.`;}-module.exports = { getFFmpegPath, checkFFmpeg, runFFmpeg, ffmpegInstallHint };+module.exports = { getFFmpegPath, getFFprobePath, getMediaDuration, checkFFmpeg, runFFmpeg, ffmpegInstallHint };diff --git a/utils/scene-repair-service.js b/utils/scene-repair-service.jsindex e622a89..7176a1d 100644--- a/utils/scene-repair-service.js+++ b/utils/scene-repair-service.js@@ -2,15 +2,15 @@ const crypto = require('crypto');const fs = require('fs').promises;const path = require('path');const sharp = require('sharp');-const { runFFmpeg } = require('./ffmpeg');+const { getMediaDuration, runFFmpeg } = require('./ffmpeg');const { ProvenanceService } = require('./provenance-service');const VIDEO_EXTENSIONS = new Set(['.mp4']);const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']);function textFromSection(section = {}) {- if (typeof section.content === 'string') return section.content;- if (Array.isArray(section.content)) return section.content.filter(item => typeof item === 'string' && !item.startsWith('[')).join(' ');+ if (typeof section.content === 'string') return /\[[^\]]*\]/.test(section.content) ? '' : section.content;+ if (Array.isArray(section.content)) return section.content.filter(item => typeof item === 'string' && !/\[[^\]]*\]/.test(item)).join(' ');if (Array.isArray(section.items)) return section.items.map(item => `${item.title || ''}. ${item.description || ''}`).join(' ');if (Array.isArray(section.steps)) return section.steps.map(item => `${item.title || ''}. ${item.description || ''}`).join(' ');return '';@@ -53,7 +53,9 @@ function scriptScenes(script = {}) {});}if (script.callToAction) {- const scriptText = Object.values(script.callToAction).filter(value => typeof value === 'string').join(' ');+ const cta = script.callToAction;+ const scriptText = [cta.subscribe, cta.like, cta.comment, cta.nextVideo]+ .filter(value => typeof value === 'string').join(' ');if (scriptText) scenes.push({label: 'Call to action', scriptText,prompt: `${scriptText}. Clean closing visual with open composition, no captions or on-screen text.`@@ -126,6 +128,7 @@ class SceneRepairService {this.mediaGeneration = videoGenerator?.mediaGeneration;this.logger = options.logger || { info() {}, warn() {}, error() {} };this.dataRoot = options.dataRoot || path.join(__dirname, '..', 'data');+ this.getMediaDuration = options.getMediaDuration || getMediaDuration;}async ensureManifest(bundle) {@@ -278,11 +281,13 @@ class SceneRepairService {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 duration = await this.narrationDuration(generatedPath, scene);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,+ duration,narrationStatus: 'current',narrationProvider: evidence.provider || 'configured-tts',narrationModel: evidence.model || null,@@ -424,7 +429,8 @@ class SceneRepairService {containsSyntheticMedia: true};} else {- const assets = await this.videoGenerator.generateVisualAssets(scene.prompt, 'ethereal', 1);+ const profile = await this.db.getChannelProfile?.() || {};+ const assets = await this.videoGenerator.generateVisualAssets(scene.prompt, profile.visual_style || 'ethereal', 1);const assetPath = assets[0];if (!assetPath || !IMAGE_EXTENSIONS.has(path.extname(assetPath).toLowerCase()) || !await this.pathExists(assetPath)) {throw this.error('No real replacement image was generated; configure an image provider or upload an asset', 422, 'SCENE_ASSET_UNAVAILABLE');@@ -441,7 +447,7 @@ class SceneRepairService {}const evidence = this.videoGenerator.lastNarrationResult || {};narration = {- audioPath: generatedPath, narrationStatus: 'current',+ audioPath: generatedPath, duration: await this.narrationDuration(generatedPath, scene), 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 || {}@@ -512,6 +518,15 @@ class SceneRepairService {return next;}+ async narrationDuration(audioPath, scene) {+ try {+ return Math.max(2, (await this.getMediaDuration(audioPath)) + 0.5);+ } catch (error) {+ this.logger.warn(`Could not measure narration duration for scene ${scene.id}, keeping previous duration: ${error.message}`);+ return scene.duration;+ }+ }+async rebuild(productionId) {const bundle = await this.getEditableBundle(productionId);const scenes = await this.db.listProductionScenes(productionId);diff --git a/walkthrough.js b/walkthrough.jsindex 4437966..686bc78 100644--- a/walkthrough.js+++ b/walkthrough.js@@ -456,7 +456,7 @@ class SetupWalkthrough {this.cm.credentials.youtube = {client_id: answers.clientId.trim(),client_secret: (answers.clientSecret || '').trim(),- redirect_uris: ['http://localhost:8080/oauth2callback']+ redirect_uris: ['http://127.0.0.1']};await this.cm.saveCredentials();