Skip to content

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

v2.5: Add operator workflow and approval-first publishing

darkzOGx9ba3d8e3459e
diff --git a/.env.example b/.env.example
index e1b3c53..bda75fb 100644
--- a/.env.example
+++ b/.env.example
@@ -60,6 +60,12 @@ DEFAULT_DELAY_BETWEEN_POSTS=60000
# Optional. If set, mutating API routes require this value in the x-api-key header.
API_KEY=
+# Optional. Generation jobs run one at a time by default to control API spend.
+MAX_CONCURRENT_JOBS=1
+
+# Optional Slack/Discord-compatible webhook for failures and review alerts.
+# NOTIFICATION_WEBHOOK_URL=https://hooks.example.com/...
+
# Analytics & Monitoring
ENABLE_ANALYTICS=true
ANALYTICS_DB_PATH=./data/analytics.db
diff --git a/README.md b/README.md
index d3c7824..4b4b554 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,14 @@
# YouTube Automation Agent
+## What's New in v2.5
+
+- **Operator-first dashboard** — live jobs, content pipeline, review queue, calendar, idea backlog, analytics, and channel setup in one responsive console
+- **Asynchronous generation** — generation returns immediately with a persistent job ID; progress, errors, cancellation, and restart interruptions are visible
+- **Approval-first publishing** — generated content must pass quality checks, factual review, media-rights confirmation, and human approval before it can be scheduled by default
+- **Review studio** — preview real video and thumbnail assets, edit title/description/tags/privacy/schedule, reject, retry, or approve
+- **Brand guardrails** — channel goal, audience, voice, CTA, visual direction, timezone, and blocked-topic policy guide generation and quality review
+- **Actionable operations** — pause/resume automation, webhook-ready notifications, real activity history, and warning-free linting
+
## What's New in v2.4
- **Guided walkthrough for first-time setup** — `npm run walkthrough` (also offered when you run `npm run setup`). It explains every choice in plain English, shows exactly where to get each key (and opens the page in your browser), **live-tests keys the moment you paste them**, walks you click-by-click through Google Cloud for the YouTube connection, and signs you in via your browser instead of copy-pasting auth codes. Every step is skippable and progress is saved — re-run it any time.
@@ -228,20 +237,27 @@ The scheduler runs automatically after `npm start`. Content generation at 06:00,
# health check
curl http://localhost:3456/health
-# generate a video on demand (send x-api-key if API_KEY is set in .env)
+# queue a video-generation job (send x-api-key if API_KEY is set in .env)
curl -X POST http://localhost:3456/generate \
-H "Content-Type: application/json" \
-H "x-api-key: $API_KEY" \
-d '{"topic": "Top 10 Life Hacks", "style": "list"}'
+# inspect the returned background job
+curl http://localhost:3456/api/jobs/:jobId
+
# view schedule
curl http://localhost:3456/schedule
# get analytics
curl http://localhost:3456/analytics
-# publish a specific content item
-curl -X POST http://localhost:3456/publish/:contentId
+# inspect, edit, and approve content before scheduling
+curl http://localhost:3456/api/content/:contentId
+curl -X POST http://localhost:3456/api/content/:contentId/approve \
+ -H "Content-Type: application/json" \
+ -H "x-api-key: $API_KEY" \
+ -d '{"privacyStatus":"private","factChecked":true,"rightsConfirmed":true}'
```
## Production Pipeline
diff --git a/agents/analytics-optimization-agent.js b/agents/analytics-optimization-agent.js
index b65c906..d1726a9 100644
--- a/agents/analytics-optimization-agent.js
+++ b/agents/analytics-optimization-agent.js
@@ -34,7 +34,16 @@ class AnalyticsOptimizationAgent {
try {
const history = await this.db.getAnalyticsHistory();
history.forEach(record => {
- this.performanceData.set(record.videoId, record);
+ const normalized = {
+ ...record,
+ videoId: record.videoId || record.video_id,
+ analyzedAt: record.analyzedAt || record.analyzed_at,
+ performance: record.performance || {
+ score: record.performance_score || 0,
+ grade: record.performance_grade || 'N/A'
+ }
+ };
+ this.performanceData.set(normalized.videoId, normalized);
});
this.logger.info(`Loaded ${this.performanceData.size} historical records`);
} catch (error) {
@@ -621,7 +630,7 @@ class AnalyticsOptimizationAgent {
}
// Simulation methods for when API is not available
- getSimulatedAnalytics(videoId) {
+ getSimulatedAnalytics(_videoId) {
return {
views: { totalViews: Math.floor(Math.random() * 50000), averageCTR: Math.random() * 10 },
watchTime: { averageViewPercentage: Math.random() * 100 },
@@ -709,4 +718,4 @@ class AnalyticsOptimizationAgent {
}
}
-module.exports = { AnalyticsOptimizationAgent };
\ No newline at end of file
+module.exports = { AnalyticsOptimizationAgent };
diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.js
index 6b4f3da..023dbde 100644
--- a/agents/content-strategy-agent.js
+++ b/agents/content-strategy-agent.js
@@ -1,4 +1,3 @@
-const axios = require('axios');
const { Logger } = require('../utils/logger');
const { AITextService } = require('../utils/ai-text-service');
@@ -557,4 +556,4 @@ Avoid fabricated claims and unsupported numbers.`;
}
}
-module.exports = { ContentStrategyAgent };
\ No newline at end of file
+module.exports = { ContentStrategyAgent };
diff --git a/agents/production-management-agent.js b/agents/production-management-agent.js
index 138e83c..e7acdc1 100644
--- a/agents/production-management-agent.js
+++ b/agents/production-management-agent.js
@@ -291,7 +291,7 @@ class ProductionManagementAgent {
this.logger.info('Generating AI video content...');
try {
- const { strategy, script } = productionData;
+ const { script } = productionData;
// Generate visual assets using DALL-E
const visualPrompts = this.createVisualPromptsFromScript(script);
@@ -336,7 +336,7 @@ class ProductionManagementAgent {
// Content sections
if (script.mainContent && script.mainContent.sections) {
- script.mainContent.sections.forEach((section, index) => {
+ script.mainContent.sections.forEach((section) => {
// Section title
elements.push({
type: 'section_title',
@@ -413,7 +413,6 @@ class ProductionManagementAgent {
this.logger.info('Generating AI audio narration...');
try {
- const { script } = productionData;
const audioPath = path.join(__dirname, '..', 'data', 'audio', `${productionData.id}_narration.mp3`);
// Read the TTS script
@@ -693,4 +692,4 @@ class ProductionManagementAgent {
}
}
-module.exports = { ProductionManagementAgent };
\ No newline at end of file
+module.exports = { ProductionManagementAgent };
diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.js
index 9a07059..857300d 100644
--- a/agents/publishing-scheduling-agent.js
+++ b/agents/publishing-scheduling-agent.js
@@ -61,7 +61,8 @@ class PublishingSchedulingAgent {
seo: productionData.seo,
thumbnail: productionData.assets.thumbnail,
video: productionData.assets.finalVideo,
- captions: productionData.assets.captions
+ captions: productionData.assets.captions,
+ privacyStatus: productionData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'
},
createdAt: new Date().toISOString()
};
@@ -127,7 +128,7 @@ class PublishingSchedulingAgent {
defaultAudioLanguage: metadata.seo.metadata.language
},
status: {
- privacyStatus: process.env.DEFAULT_PRIVACY_STATUS || 'private',
+ privacyStatus: metadata.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',
publishAt: scheduleEntry.publishTime,
selfDeclaredMadeForKids: false
}
@@ -281,9 +282,6 @@ class PublishingSchedulingAgent {
async getChannelAnalytics() {
try {
// Get channel analytics for the last 30 days
- const endDate = new Date();
- const startDate = new Date(endDate.getTime() - (30 * 24 * 60 * 60 * 1000));
-
const response = await this.youtube.channels.list({
part: 'statistics',
mine: true
@@ -482,4 +480,4 @@ class PublishingSchedulingAgent {
}
}
-module.exports = { PublishingSchedulingAgent };
\ No newline at end of file
+module.exports = { PublishingSchedulingAgent };
diff --git a/agents/script-writer-agent.js b/agents/script-writer-agent.js
index ab1faf8..910a0aa 100644
--- a/agents/script-writer-agent.js
+++ b/agents/script-writer-agent.js
@@ -120,9 +120,12 @@ Topic: ${strategy.topic}
Style/content type: ${strategy.contentType}
Angle: ${strategy.angle}
Target audience: ${strategy.targetAudience}
-Desired length: ${process.env.DEFAULT_VIDEO_LENGTH || '8-12 minutes'}
+Desired length: ${strategy.requestedLength || process.env.DEFAULT_VIDEO_LENGTH || '8-12 minutes'}
Tone: ${template.tone}
Pacing: ${template.pacing}
+Brand voice: ${strategy.brandVoice || 'clear, credible, and engaging'}
+Channel goal: ${strategy.channelGoal || 'help the viewer understand and act'}
+Preferred call to action: ${strategy.callToAction || 'invite the viewer to subscribe'}
Keywords: ${(strategy.keywords || []).join(', ')}
Avoid fabricated statistics, unsupported claims, and fake urgency.`;
@@ -342,7 +345,7 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
return propositions[strategy.contentType] || `everything about ${strategy.topic}`;
}
- getCredibilityStatement(strategy) {
+ getCredibilityStatement(_strategy) {
const statements = [
"I've spent months researching this topic",
"After working with hundreds of people on this",
@@ -442,11 +445,11 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
return titles[stepNumber - 1] || `Advanced ${topic} Techniques`;
}
- generateStepDescription(topic, stepNumber) {
+ generateStepDescription(topic, _stepNumber) {
return `This step involves understanding the key aspects of ${topic} and how to apply them effectively. Pay special attention to the details here, as they make all the difference.`;
}
- generateProTip(topic) {
+ generateProTip(_topic) {
const tips = [
`Pro tip: Start small and scale gradually`,
`Remember: Consistency is more important than perfection`,
@@ -458,7 +461,7 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
return tips[Math.floor(Math.random() * tips.length)];
}
- async generateDemonstration(strategy) {
+ async generateDemonstration(_strategy) {
return {
type: 'demonstration',
title: 'Live Demo',
@@ -559,7 +562,7 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
return impacts[Math.floor(Math.random() * impacts.length)];
}
- async generatePros(strategy) {
+ async generatePros(_strategy) {
return {
type: 'pros',
title: 'The Benefits',
@@ -574,7 +577,7 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
};
}
- async generateCons(strategy) {
+ async generateCons(_strategy) {
return {
type: 'cons',
title: 'Things to Consider',
@@ -756,4 +759,4 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;
}
}
-module.exports = { ScriptWriterAgent };
\ No newline at end of file
+module.exports = { ScriptWriterAgent };
diff --git a/dashboard/app.js b/dashboard/app.js
new file mode 100644
index 0000000..9b02725
--- /dev/null
+++ b/dashboard/app.js
@@ -0,0 +1,483 @@
+const ui = {
+ state: null,
+ currentView: 'overview',
+ refreshing: false,
+ toastTimer: null
+};
+
+const $ = selector => document.querySelector(selector);
+const $$ = selector => Array.from(document.querySelectorAll(selector));
+
+function escapeHTML(value) {
+ return String(value ?? '')
+ .replaceAll('&', '&')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#039;');
+}
+
+function apiKey() {
+ return localStorage.getItem('yaa_api_key') || '';
+}
+
+function requestApiKey() {
+ const key = prompt('Enter the API_KEY value from your .env. It stays in this browser only.', apiKey());
+ if (key !== null) localStorage.setItem('yaa_api_key', key.trim());
+ return key;
+}
+
+async function api(url, options = {}, retry = true) {
+ const key = apiKey();
+ const response = await fetch(url, {
+ ...options,
+ headers: {
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(key ? { 'x-api-key': key } : {}),
+ ...(options.headers || {})
+ }
+ });
+ if (response.status === 401 && retry && requestApiKey() !== null) return api(url, options, false);
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ const error = new Error(data.error || response.statusText || 'Request failed');
+ error.data = data;
+ throw error;
+ }
+ return data;
+}
+
+function showToast(message, type = 'success') {
+ const toast = $('#toast');
+ toast.textContent = message;
+ toast.className = `toast ${type}`;
+ clearTimeout(ui.toastTimer);
+ ui.toastTimer = setTimeout(() => toast.classList.add('hidden'), 4200);
+}
+
+function empty(message) {
+ return `<div class="empty">${escapeHTML(message)}</div>`;
+}
+
+function formatDate(value, includeTime = true) {
+ if (!value) return 'Not scheduled';
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return 'Not scheduled';
+ return new Intl.DateTimeFormat(undefined, {
+ month: 'short', day: 'numeric',
+ ...(ui.state?.profile?.timezone ? { timeZone: ui.state.profile.timezone } : {}),
+ ...(includeTime ? { hour: 'numeric', minute: '2-digit' } : {})
+ }).format(date);
+}
+
+function timeAgo(value) {
+ if (!value) return '';
+ const seconds = Math.max(0, Math.floor((Date.now() - new Date(value).getTime()) / 1000));
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+function label(value) {
+ return String(value || 'unknown').replaceAll('_', ' ');
+}
+
+function statusChip(value) {
+ const safe = String(value || 'unknown').toLowerCase();
+ return `<span class="status ${escapeHTML(safe)}">${escapeHTML(label(safe))}</span>`;
+}
+
+async function refreshDashboard(silent = false) {
+ if (ui.refreshing) return;
+ ui.refreshing = true;
+ if (!silent) $('#loading').classList.add('active');
+ try {
+ ui.state = await api('/api/dashboard');
+ renderDashboard();
+ } catch (error) {
+ $('#system-label').textContent = 'Dashboard unavailable';
+ $('#system-dot').classList.remove('online');
+ if (!silent) showToast(error.message, 'error');
+ } finally {
+ ui.refreshing = false;
+ $('#loading').classList.remove('active');
+ }
+}
+
+function renderDashboard() {
+ const state = ui.state;
+ const reviews = state.pipeline.filter(item => ['needs_review', 'needs_attention'].includes(item.review_status));
+ const scheduled = state.schedule.filter(item => item.status === 'scheduled');
+ const activeJobs = state.jobs.filter(job => ['queued', 'running'].includes(job.status));
+
+ $('#brand-name').textContent = state.profile?.channel_name || 'Automation Studio';
+ $('#setup-banner').classList.toggle('hidden', !state.system.setupRequired);
+ $('#system-label').textContent = state.system.setupRequired
+ ? 'Setup required'
+ : state.system.automationPaused ? 'Automation paused' : `${state.system.agents.length} agents online`;
+ $('#system-dot').classList.toggle('online', state.system.initialized && !state.system.automationPaused && !state.system.setupRequired);
+ $('#automation-toggle').textContent = state.system.automationPaused ? 'Resume automation' : 'Pause automation';
+ $('#automation-toggle').disabled = state.system.setupRequired;
+ $('#generate-button').disabled = state.system.setupRequired;
+ $('#review-badge').textContent = reviews.length;
+ $('#review-badge').classList.toggle('hidden', reviews.length === 0);
+
+ $('#stat-review').textContent = reviews.length;
+ $('#stat-scheduled').textContent = scheduled.length;
+ $('#stat-published').textContent = state.stats.published || 0;
+ $('#stat-score').textContent = state.analytics.averagePerformanceScore ? `${state.analytics.averagePerformanceScore}/100` : '—';
+
+ renderReviews(reviews);
+ renderJobs(activeJobs.length ? activeJobs : state.jobs.slice(0, 5));
+ renderSchedule(state.schedule.slice(0, 5), '#next-schedule');
+ renderNotifications(state.notifications, state.events);
+ renderPipeline(state.pipeline);
+ renderCalendar(state.schedule);
+ renderIdeas(state.ideas);
+ renderAnalytics(state.analytics);
+ populateSettings(state.profile, state.settings);
+}
+
+function renderReviews(reviews) {
+ const container = $('#review-list');
+ if (!reviews.length) {
+ container.innerHTML = empty('Nothing is waiting. New content will appear here after quality review.');
+ return;
+ }
+ container.innerHTML = reviews.slice(0, 5).map(item => `
+ <article class="review-card">
+ ${item.hasThumbnail ? `<img class="review-thumb" src="/api/content/${encodeURIComponent(item.id)}/asset/thumbnail" alt="">` : '<div class="review-thumb"></div>'}
+ <div class="review-meta"><strong>${escapeHTML(item.title)}</strong><div class="meta-line">${statusChip(item.review_status)} · Quality ${qualityScore(item.qualityChecks)}%</div></div>
+ <button class="button secondary small" data-open-content="${escapeHTML(item.id)}">Review</button>
+ </article>`).join('');
+}
+
+function renderJobs(jobs) {
+ const container = $('#job-list');
+ if (!jobs.length) {
+ container.innerHTML = empty('No generation runs yet.');
+ return;
+ }
+ container.innerHTML = jobs.slice(0, 6).map(job => `
+ <article class="job-card">
+ <div class="job-meta">
+ <strong>${escapeHTML(job.title || job.topic || 'Agent-selected topic')}</strong>
+ <div class="meta-line">${statusChip(job.status)} · ${escapeHTML(label(job.stage))} · ${timeAgo(job.updated_at)}</div>
+ <div class="progress"><i style="width:${Math.max(0, Math.min(100, job.progress || 0))}%"></i></div>
+ </div>
+ ${['queued', 'running'].includes(job.status) ? `<button class="text-button" data-cancel-job="${escapeHTML(job.id)}">Cancel</button>` : ''}
+ </article>`).join('');
+}
+
+function renderSchedule(schedule, selector) {
+ const container = $(selector);
+ if (!schedule.length) {
+ container.innerHTML = empty('No approved videos are scheduled.');
+ return;
+ }
+ container.innerHTML = schedule.map(item => `
+ <div class="timeline-item">
+ <div class="date-chip"><small>${escapeHTML(new Date(item.publish_time).toLocaleDateString(undefined, { month: 'short' }))}</small><strong>${escapeHTML(new Date(item.publish_time).getDate())}</strong></div>
+ <div class="timeline-meta"><strong>${escapeHTML(item.title)}</strong><div class="meta-line">${formatDate(item.publish_time)} · ${statusChip(item.status)}</div></div>
+ <button class="text-button" data-open-content="${escapeHTML(item.production_id)}">View</button>
+ </div>`).join('');
+}
+
+function renderNotifications(notifications, events) {
+ const items = notifications.length
+ ? notifications
+ : events.map(event => ({ level: event.status === 'error' ? 'error' : 'info', title: label(event.event_type), message: event.data?.error || label(event.status), created_at: event.created_at }));
+ const container = $('#notification-list');
+ if (!items.length) {
+ container.innerHTML = empty('No activity has been recorded yet.');
+ return;
+ }
+ container.innerHTML = items.slice(0, 7).map(item => `
+ <div class="activity ${escapeHTML(item.level || 'info')}"><i></i><p><strong>${escapeHTML(item.title)}</strong><br><span class="meta-line">${escapeHTML(item.message)}</span></p><small>${timeAgo(item.created_at)}</small></div>`).join('');
+}
+
+function currentPipelineFilter() {
+ return $('#pipeline-filter').value || 'all';
+}
+
+function renderPipeline(items) {
+ const filter = currentPipelineFilter();
+ const filtered = filter === 'all' ? items : items.filter(item =>
+ item.review_status === filter || item.schedule_status === filter || item.status === filter
+ );
+ const container = $('#pipeline-list');
+ if (!filtered.length) {
+ container.innerHTML = empty('No content matches this view.');
+ return;
+ }
+ container.innerHTML = filtered.map(item => {
+ const state = item.schedule_status || item.review_status || item.status;
+ const next = nextAction(item);
+ return `<article class="pipeline-item" data-open-content="${escapeHTML(item.id)}">
+ <div class="pipeline-title"><strong>${escapeHTML(item.title)}</strong><span>${escapeHTML(item.topic || 'No topic recorded')} · ${formatDate(item.created_at)}</span></div>
+ <div class="pipeline-col"><span>State</span><strong>${statusChip(state)}</strong></div>
+ <div class="pipeline-col"><span>Quality</span><strong>${qualityScore(item.qualityChecks)} / 100</strong></div>
+ <button class="button secondary small">${escapeHTML(next)} →</button>
+ </article>`;
+ }).join('');
+}
+
+function qualityScore(checks) {
+ if (!Array.isArray(checks) || !checks.length) return 0;
+ return Math.round((checks.filter(check => check.passed).length / checks.length) * 100);
+}
+
+function nextAction(item) {
+ if (item.schedule_status === 'published') return 'View';
+ if (item.review_status === 'needs_attention') return 'Fix issues';
+ if (item.review_status === 'needs_review') return 'Review';
+ if (item.schedule_status === 'scheduled') return 'Scheduled';
+ return 'Inspect';
+}
+
+function renderCalendar(schedule) {
+ renderSchedule(schedule, '#calendar-list');
+}
+
+function renderIdeas(ideas) {
+ const container = $('#idea-list');
+ if (!ideas.length) {
+ container.innerHTML = empty('Add promising topics here before spending generation credits.');
+ return;
+ }
+ container.innerHTML = ideas.map(idea => `
+ <article class="idea-card">
+ <div class="idea-meta"><strong>${escapeHTML(idea.topic)}</strong><div class="meta-line">${escapeHTML(idea.angle || idea.rationale || 'No angle added')} · ${statusChip(idea.status)}</div></div>
+ ${idea.status === 'backlog' ? `<button class="button secondary small" data-generate-idea="${escapeHTML(idea.id)}">Generate</button>` : ''}
+ </article>`).join('');
+}
+
+function renderAnalytics(analytics) {
+ $('#analytics-total').textContent = analytics.totalVideos || 0;
+ $('#analytics-score').textContent = analytics.averagePerformanceScore ? `${analytics.averagePerformanceScore}/100` : '—';
+ const insights = Array.isArray(analytics.insights) ? analytics.insights : [];
+ $('#analytics-action').textContent = insights[0] || (analytics.totalVideos
+ ? 'Keep collecting results; recommendations get stronger with more published videos.'
+ : 'Publish and analyze the first video to unlock performance recommendations.');
+ const performers = Array.isArray(analytics.topPerformers) ? analytics.topPerformers : [];
+ $('#top-performers').innerHTML = performers.length ? performers.map(item => `
+ <article class="performer-card"><strong>${escapeHTML(item.videoDetails?.title || item.title || 'Untitled video')}</strong><div class="meta-line">Performance ${escapeHTML(item.performance?.score ?? item.performance_score ?? '—')} / 100</div></article>`).join('') : empty('No analyzed videos yet.');
+}
+
+function populateSettings(profile = {}, settings = {}) {
+ const form = $('#profile-form');
+ const mapping = {
+ channelName: profile.channel_name,
+ goal: profile.goal,
+ targetAudience: profile.target_audience,
+ brandVoice: profile.brand_voice,
+ defaultStyle: profile.default_style,
+ callToAction: profile.call_to_action,
+ visualStyle: profile.visual_style,
+ timezone: profile.timezone,
+ bannedTopics: (profile.bannedTopics || []).join(', ')
+ };
+ for (const [name, value] of Object.entries(mapping)) {
+ if (form.elements[name] && document.activeElement !== form.elements[name]) form.elements[name].value = value || '';
+ }
+ $('#approval-required').checked = settings.approval_required !== 'false';
+ $('#notifications-enabled').checked = settings.notification_enabled !== 'false';
+}
+
+function switchView(view) {
+ ui.currentView = view;
+ $$('.nav-item').forEach(item => item.classList.toggle('active', item.dataset.view === view));
+ $$('.view').forEach(item => item.classList.toggle('active', item.id === `${view}-view`));
+ const titles = {
+ overview: ['OPERATOR OVERVIEW', 'Know what happens next.'],
+ pipeline: ['CONTENT OPERATIONS', 'From idea to published.'],
+ calendar: ['EDITORIAL PLANNING', 'Plan before you generate.'],
+ analytics: ['PERFORMANCE', 'Turn results into the next move.'],
+ settings: ['CHANNEL GUARDRAILS', 'Make every agent sound like you.']
+ };
+ $('#view-eyebrow').textContent = titles[view][0];
+ $('#view-title').textContent = titles[view][1];
+ location.hash = view;
+}
+
+async function openContent(productionId) {
+ $('#loading').classList.add('active');
+ try {
+ const item = await api(`/api/content/${encodeURIComponent(productionId)}`);
+ const data = item.editorData || {};
+ 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 canReview = !['published'].includes(item.schedule?.status);
+ $('#content-detail').innerHTML = `
+ <div class="dialog-heading"><div><p class="eyebrow">CONTENT REVIEW</p><h2>${escapeHTML(title)}</h2><div class="meta-line">${statusChip(item.schedule?.status || item.review_status || item.status)} · Quality ${qualityScore(item.qualityChecks)}%</div></div><button type="button" class="close-button" data-close>×</button></div>
+ <div class="content-layout">
+ <div>
+ <div class="preview">${item.assetUrls.video ? `<video controls preload="metadata" poster="${item.assetUrls.thumbnail || ''}"><source src="${item.assetUrls.video}" type="video/mp4"></video>` : item.assetUrls.thumbnail ? `<img src="${item.assetUrls.thumbnail}" alt="Generated thumbnail">` : '<div class="preview-placeholder">No playable preview was produced.</div>'}</div>
+ <div class="quality-grid">${(item.qualityChecks || []).map(check => `<div class="quality-check ${check.passed ? 'pass' : 'fail'}">${check.passed ? '✓' : '×'} ${escapeHTML(check.message)}</div>`).join('') || '<div class="quality-check">No quality results recorded.</div>'}</div>
+ ${item.review_notes ? `<p class="callout">${escapeHTML(item.review_notes)}</p>` : ''}
+ </div>
+ <form id="content-review-form" class="editor">
+ <label><span>Title</span><input name="title" maxlength="100" value="${escapeHTML(title)}" required></label>
+ <label><span>Description</span><textarea name="description" rows="7">${escapeHTML(description)}</textarea></label>
+ <label><span>Tags</span><input name="tags" value="${escapeHTML(tags.join(', '))}"></label>
+ <div class="form-grid two">
+ <label><span>Publish time</span><input name="publishTime" type="datetime-local" value="${toLocalInput(publishTime)}"></label>
+ <label><span>Privacy</span><select name="privacyStatus"><option value="private" ${data.privacyStatus === 'private' ? 'selected' : ''}>Private</option><option value="unlisted" ${data.privacyStatus === 'unlisted' ? 'selected' : ''}>Unlisted</option><option value="public" ${data.privacyStatus === 'public' ? 'selected' : ''}>Public</option></select></label>
+ </div>
+ <div class="settings-row">
+ <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>
+ ${canReview ? `<div class="form-actions"><button type="button" class="button primary" data-approve-content="${escapeHTML(item.id)}">Approve & schedule</button><button type="button" class="button secondary" data-save-content="${escapeHTML(item.id)}">Save draft</button><button type="button" class="button danger" data-reject-content="${escapeHTML(item.id)}">Reject</button><button type="button" class="button ghost" data-retry-content="${escapeHTML(item.id)}">Regenerate</button></div>` : `<a class="button secondary" href="${escapeHTML(item.schedule?.youtube_url || '#')}" target="_blank" rel="noopener">Open on YouTube</a>`}
+ </form>
+ </div>`;
+ $('#content-dialog').showModal();
+ } catch (error) {
+ showToast(error.message, 'error');
+ } finally {
+ $('#loading').classList.remove('active');
+ }
+}
+
+function toLocalInput(value) {
+ if (!value) return '';
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return '';
+ const offset = date.getTimezoneOffset() * 60000;
+ return escapeHTML(new Date(date.getTime() - offset).toISOString().slice(0, 16));
+}
+
+function contentFormData() {
+ const form = $('#content-review-form');
+ const values = Object.fromEntries(new FormData(form));
+ return {
+ title: values.title,
+ description: values.description,
+ tags: values.tags,
+ publishTime: values.publishTime ? new Date(values.publishTime).toISOString() : undefined,
+ privacyStatus: values.privacyStatus,
+ factChecked: form.elements.factChecked?.checked || false,
+ rightsConfirmed: form.elements.rightsConfirmed?.checked || false
+ };
+}
+
+async function mutate(url, method, body, successMessage) {
+ $('#loading').classList.add('active');
+ try {
+ const result = await api(url, { method, body: body === undefined ? undefined : JSON.stringify(body) });
+ showToast(successMessage);
+ await refreshDashboard(true);
+ return result;
+ } catch (error) {
+ const failures = error.data?.quality?.blockingFailures;
+ showToast(failures ? `${error.message}: ${failures.join(', ')}` : error.message, 'error');
+ throw error;
+ } finally {
+ $('#loading').classList.remove('active');
+ }
+}
+
+document.addEventListener('click', async event => {
+ const nav = event.target.closest('[data-view]');
+ if (nav) return switchView(nav.dataset.view);
+ const go = event.target.closest('[data-go]');
+ if (go) return switchView(go.dataset.go);
+ if (event.target.closest('[data-close]')) return event.target.closest('dialog').close();
+
+ const open = event.target.closest('[data-open-content]');
+ if (open) return openContent(open.dataset.openContent);
+
+ const cancel = event.target.closest('[data-cancel-job]');
+ if (cancel && confirm('Cancel this generation job after its current stage?')) {
+ await mutate(`/api/jobs/${encodeURIComponent(cancel.dataset.cancelJob)}/cancel`, 'POST', {}, 'Cancellation requested.').catch(() => {});
+ }
+
+ const idea = event.target.closest('[data-generate-idea]');
+ if (idea) {
+ await mutate(`/api/ideas/${encodeURIComponent(idea.dataset.generateIdea)}/generate`, 'POST', { length: 'medium' }, 'Idea queued for generation.').catch(() => {});
+ }
+
+ const save = event.target.closest('[data-save-content]');
+ if (save) {
+ await mutate(`/api/content/${encodeURIComponent(save.dataset.saveContent)}`, 'PATCH', contentFormData(), 'Draft saved.').catch(() => {});
+ }
+
+ const approve = event.target.closest('[data-approve-content]');
+ if (approve) {
+ try {
+ await mutate(`/api/content/${encodeURIComponent(approve.dataset.approveContent)}/approve`, 'POST', contentFormData(), 'Content approved and scheduled.');
+ $('#content-dialog').close();
+ } catch (_error) { /* toast already shown */ }
+ }
+
+ const reject = event.target.closest('[data-reject-content]');
+ if (reject) {
+ const notes = prompt('Why are you rejecting this content?', 'Needs a different angle');
+ if (notes !== null) {
+ await mutate(`/api/content/${encodeURIComponent(reject.dataset.rejectContent)}/reject`, 'POST', { notes }, 'Content rejected.').catch(() => {});
+ $('#content-dialog').close();
+ }
+ }
+
+ const retry = event.target.closest('[data-retry-content]');
+ if (retry && confirm('Generate a fresh version using the same topic?')) {
+ await mutate(`/api/content/${encodeURIComponent(retry.dataset.retryContent)}/retry`, 'POST', {}, 'Regeneration started.').catch(() => {});
+ $('#content-dialog').close();
+ }
+});
+
+$('#generate-button').addEventListener('click', () => $('#generate-dialog').showModal());
+$('#add-idea-button').addEventListener('click', () => $('#idea-dialog').showModal());
+$('#refresh-button').addEventListener('click', () => refreshDashboard());
+$('#pipeline-filter').addEventListener('change', () => renderPipeline(ui.state?.pipeline || []));
+
+$('#automation-toggle').addEventListener('click', async () => {
+ const action = ui.state?.system.automationPaused ? 'resume' : 'pause';
+ await mutate(`/api/automation/${action}`, 'POST', {}, `Automation ${action}d.`).catch(() => {});
+});
+
+$('#generate-form').addEventListener('submit', async event => {
+ event.preventDefault();
+ const values = Object.fromEntries(new FormData(event.currentTarget));
+ try {
+ await mutate('/generate', 'POST', { ...values, topic: values.topic.trim() || null }, 'Generation job started.');
+ $('#generate-dialog').close();
+ event.currentTarget.reset();
+ } catch (_error) { /* toast already shown */ }
+});
+
+$('#idea-form').addEventListener('submit', async event => {
+ event.preventDefault();
+ const values = Object.fromEntries(new FormData(event.currentTarget));
+ try {
+ await mutate('/api/ideas', 'POST', values, 'Idea added to the backlog.');
+ $('#idea-dialog').close();
+ event.currentTarget.reset();
+ } catch (_error) { /* toast already shown */ }
+});
+
+$('#profile-form').addEventListener('submit', async event => {
+ event.preventDefault();
+ const values = Object.fromEntries(new FormData(event.currentTarget));
+ values.bannedTopics = values.bannedTopics.split(',').map(value => value.trim()).filter(Boolean);
+ try {
+ await mutate('/api/profile', 'PUT', values, 'Channel setup saved.');
+ await mutate('/api/settings', 'PUT', {
+ approval_required: $('#approval-required').checked,
+ notification_enabled: $('#notifications-enabled').checked,
+ channel_timezone: values.timezone
+ }, 'Operator settings saved.');
+ } catch (_error) { /* toast already shown */ }
+});
+
+$('#api-key-button').addEventListener('click', () => {
+ if (requestApiKey() !== null) showToast('Dashboard API key saved in this browser.');
+});
+
+const initialView = location.hash.slice(1);
+if (['overview', 'pipeline', 'calendar', 'analytics', 'settings'].includes(initialView)) switchView(initialView);
+refreshDashboard();
+setInterval(() => refreshDashboard(true), 8000);
diff --git a/dashboard/index.html b/dashboard/index.html
index cf689c2..d4ad1f3 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -1,447 +1,154 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Ethereal Dreamscript - YouTube Automation Dashboard</title>
- <style>
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
-
- body {
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- color: #333;
- min-height: 100vh;
- }
-
- .container {
- max-width: 1200px;
- margin: 0 auto;
- padding: 20px;
- }
-
- .header {
- text-align: center;
- color: white;
- margin-bottom: 30px;
- }
-
- .header h1 {
- font-size: 2.5em;
- margin-bottom: 10px;
- }
-
- .header p {
- font-size: 1.2em;
- opacity: 0.9;
- }
-
- .status-bar {
- background: rgba(255, 255, 255, 0.95);
- padding: 20px;
- border-radius: 15px;
- margin-bottom: 30px;
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- }
-
- .status-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 20px;
- margin-bottom: 20px;
- }
-
- .status-card {
- text-align: center;
- padding: 15px;
- background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
- border-radius: 10px;
- color: white;
- }
-
- .status-card h3 {
- font-size: 2em;
- margin-bottom: 5px;
- }
-
- .status-card p {
- opacity: 0.9;
- }
-
- .dashboard-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
- gap: 20px;
- }
-
- .dashboard-card {
- background: rgba(255, 255, 255, 0.95);
- padding: 25px;
- border-radius: 15px;
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- }
-
- .dashboard-card h2 {
- color: #667eea;
- margin-bottom: 15px;
- display: flex;
- align-items: center;
- gap: 10px;
- }
-
- .card-content {
- line-height: 1.6;
- }
-
- .loading {
- text-align: center;
- color: #666;
- font-style: italic;
- }
-
- .btn {
- background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
- color: white;
- padding: 10px 20px;
- border: none;
- border-radius: 5px;
- cursor: pointer;
- margin: 5px;
- transition: transform 0.2s;
- }
-
- .btn:hover {
- transform: translateY(-2px);
- }
-
- .schedule-item {
- background: #f8f9ff;
- padding: 10px;
- margin: 10px 0;
- border-radius: 5px;
- border-left: 4px solid #667eea;
- }
-
- .log-entry {
- font-family: 'Courier New', monospace;
- font-size: 0.9em;
- padding: 5px;
- margin: 2px 0;
- background: #f5f5f5;
- border-radius: 3px;
- }
-
- .success { color: #28a745; }
- .warning { color: #ffc107; }
- .error { color: #dc3545; }
- .info { color: #17a2b8; }
-
- .refresh-btn {
- position: fixed;
- bottom: 20px;
- right: 20px;
- width: 60px;
- height: 60px;
- border-radius: 50%;
- background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
- color: white;
- border: none;
- font-size: 1.5em;
- cursor: pointer;
- box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
- transition: transform 0.2s;
- }
-
- .refresh-btn:hover {
- transform: scale(1.1);
- }
- </style>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="color-scheme" content="dark">
+ <title>YouTube Automation Studio</title>
+ <link rel="stylesheet" href="/styles.css">
</head>
<body>
- <div class="container">
- <div class="header">
- <h1>🎬 Ethereal Dreamscript</h1>
- <p>YouTube Automation Dashboard</p>
+ <div class="app-shell">
+ <aside class="sidebar">
+ <a class="brand" href="#overview" aria-label="YouTube Automation Studio home">
+ <span class="brand-mark">▶</span>
+ <span><strong id="brand-name">Automation Studio</strong><small>YouTube operator console</small></span>
+ </a>
+ <nav aria-label="Main navigation">
+ <button class="nav-item active" data-view="overview"><span>⌂</span> Overview</button>
+ <button class="nav-item" data-view="pipeline"><span>≋</span> Pipeline <b id="review-badge" class="badge hidden">0</b></button>
+ <button class="nav-item" data-view="calendar"><span>□</span> Calendar & ideas</button>
+ <button class="nav-item" data-view="analytics"><span>⌁</span> Analytics</button>
+ <button class="nav-item" data-view="settings"><span>⚙</span> Channel setup</button>
+ </nav>
+ <div class="sidebar-footer">
+ <div class="system-pill"><i id="system-dot"></i><span id="system-label">Connecting…</span></div>
+ <button id="automation-toggle" class="button secondary full">Pause automation</button>
+ </div>
+ </aside>
+
+ <main>
+ <header class="topbar">
+ <div>
+ <p class="eyebrow" id="view-eyebrow">OPERATOR OVERVIEW</p>
+ <h1 id="view-title">Know what happens next.</h1>
+ </div>
+ <div class="top-actions">
+ <button id="refresh-button" class="icon-button" title="Refresh dashboard" aria-label="Refresh dashboard">↻</button>
+ <button id="generate-button" class="button primary">+ Create video</button>
+ </div>
+ </header>
+
+ <div id="loading" class="loading-bar"></div>
+ <div id="toast" class="toast hidden" role="status"></div>
+
+ <section id="overview-view" class="view active">
+ <div id="setup-banner" class="setup-banner hidden"><div><strong>Finish setup to activate your agents</strong><p>The operator console is ready, but generation and publishing stay disabled until credentials are configured.</p></div><code>npm run walkthrough</code></div>
+ <div class="stats-grid">
+ <article class="stat"><span>Needs review</span><strong id="stat-review">—</strong><small>waiting for a decision</small></article>
+ <article class="stat"><span>Scheduled</span><strong id="stat-scheduled">—</strong><small>next 30 days</small></article>
+ <article class="stat"><span>Published</span><strong id="stat-published">—</strong><small>all time</small></article>
+ <article class="stat"><span>Average score</span><strong id="stat-score">—</strong><small>recent content performance</small></article>
</div>
-
- <div class="status-bar">
- <div class="status-grid">
- <div class="status-card">
- <h3 id="system-status">🟢</h3>
- <p>System Status</p>
- </div>
- <div class="status-card">
- <h3 id="content-count">-</h3>
- <p>Content Generated</p>
- </div>
- <div class="status-card">
- <h3 id="published-count">-</h3>
- <p>Videos Published</p>
- </div>
- <div class="status-card">
- <h3 id="next-generation">-</h3>
- <p>Next Generation</p>
- </div>
- </div>
- <div style="text-align: center;">
- <button class="btn" onclick="generateContent()">🎬 Generate Content Now</button>
- <button class="btn" onclick="viewAnalytics()">📊 View Analytics</button>
- <button class="btn" onclick="viewSchedule()">📅 View Schedule</button>
- </div>
+
+ <div class="overview-grid">
+ <article class="panel review-panel">
+ <div class="panel-heading"><div><p class="eyebrow">DECISION QUEUE</p><h2>Ready for you</h2></div><button class="text-button" data-go="pipeline">View pipeline →</button></div>
+ <div id="review-list" class="card-list"></div>
+ </article>
+ <article class="panel">
+ <div class="panel-heading"><div><p class="eyebrow">ACTIVE WORK</p><h2>Generation jobs</h2></div></div>
+ <div id="job-list" class="card-list compact"></div>
+ </article>
</div>
-
- <div class="dashboard-grid">
- <div class="dashboard-card">
- <h2>📈 System Overview</h2>
- <div class="card-content">
- <div id="system-overview" class="loading">Loading system status...</div>
- </div>
- </div>
-
- <div class="dashboard-card">
- <h2>📅 Upcoming Schedule</h2>
- <div class="card-content">
- <div id="upcoming-schedule" class="loading">Loading schedule...</div>
- </div>
- </div>
-
- <div class="dashboard-card">
- <h2>🎯 Content Strategy</h2>
- <div class="card-content">
- <div id="content-strategy">
- <p><strong>Current Focus:</strong> Animated Storytelling</p>
- <p><strong>Target Audience:</strong> Creative individuals interested in storytelling and imagination</p>
- <p><strong>Content Types:</strong> Story-driven content, Explainers, Tutorials</p>
- <p><strong>Posting Frequency:</strong> Daily</p>
- <p><strong>Optimal Time:</strong> 2:00 PM</p>
- </div>
- </div>
- </div>
-
- <div class="dashboard-card">
- <h2>📊 Recent Activity</h2>
- <div class="card-content">
- <div id="recent-activity" class="loading">Loading activity...</div>
- </div>
- </div>
-
- <div class="dashboard-card">
- <h2>🤖 Agent Status</h2>
- <div class="card-content">
- <div id="agent-status" class="loading">Loading agent status...</div>
- </div>
- </div>
-
- <div class="dashboard-card">
- <h2>📈 Performance Metrics</h2>
- <div class="card-content">
- <div id="performance-metrics" class="loading">Loading metrics...</div>
- </div>
- </div>
+
+ <div class="overview-grid lower">
+ <article class="panel">
+ <div class="panel-heading"><div><p class="eyebrow">UP NEXT</p><h2>Publishing calendar</h2></div><button class="text-button" data-go="calendar">Open calendar →</button></div>
+ <div id="next-schedule" class="timeline"></div>
+ </article>
+ <article class="panel">
+ <div class="panel-heading"><div><p class="eyebrow">INBOX</p><h2>Recent activity</h2></div></div>
+ <div id="notification-list" class="activity-list"></div>
+ </article>
</div>
- </div>
-
- <button class="refresh-btn" onclick="refreshDashboard()" title="Refresh Dashboard">
- 🔄
- </button>
-
- <script>
- // Dashboard functionality
- async function loadDashboard() {
- try {
- // Load system health
- const healthResponse = await fetch('/health');
- const healthData = await healthResponse.json();
- updateSystemStatus(healthData);
-
- // Load schedule
- const scheduleResponse = await fetch('/schedule');
- const scheduleData = await scheduleResponse.json();
- updateSchedule(scheduleData);
-
- // Load analytics
- try {
- const analyticsResponse = await fetch('/analytics');
- const analyticsData = await analyticsResponse.json();
- updateMetrics(analyticsData);
- } catch (error) {
- console.log('Analytics not available yet');
- }
-
- } catch (error) {
- console.error('Dashboard load error:', error);
- document.getElementById('system-status').textContent = '🔴';
- }
- }
-
- function updateSystemStatus(data) {
- document.getElementById('system-status').textContent = data.status === 'healthy' ? '🟢' : '🔴';
-
- const overview = document.getElementById('system-overview');
- overview.innerHTML = `
- <p><strong>Status:</strong> ${data.initialized ? 'Initialized' : 'Initializing'}</p>
- <p><strong>Agents Active:</strong> ${data.agents ? data.agents.length : 0}/7</p>
- <p><strong>Uptime:</strong> ${formatUptime(data.uptime || 0)}</p>
- <p><strong>Last Updated:</strong> ${new Date().toLocaleTimeString()}</p>
- `;
-
- const agentStatus = document.getElementById('agent-status');
- if (data.agents) {
- agentStatus.innerHTML = data.agents.map(agent =>
- `<div class="schedule-item">✅ ${agent} Agent</div>`
- ).join('');
- }
- }
-
- function updateSchedule(data) {
- const schedule = document.getElementById('upcoming-schedule');
-
- if (data && data.length > 0) {
- schedule.innerHTML = data.slice(0, 3).map(item => `
- <div class="schedule-item">
- <strong>${item.title || 'Content Generation'}</strong><br>
- <small>${new Date(item.publishTime || item.scheduledTime).toLocaleString()}</small>
- </div>
- `).join('');
-
- // Update next generation time
- const nextItem = data[0];
- if (nextItem) {
- const nextTime = new Date(nextItem.publishTime || nextItem.scheduledTime);
- document.getElementById('next-generation').textContent =
- nextTime.toLocaleDateString() === new Date().toLocaleDateString()
- ? nextTime.toLocaleTimeString()
- : 'Tomorrow';
- }
- } else {
- schedule.innerHTML = `
- <div class="schedule-item">
- <strong>📅 Daily Content Generation</strong><br>
- <small>Scheduled for 6:00 AM daily</small>
- </div>
- <div class="schedule-item">
- <strong>📊 Analytics Collection</strong><br>
- <small>Scheduled for 9:00 AM daily</small>
- </div>
- <div class="schedule-item">
- <strong>🔧 Optimization Tasks</strong><br>
- <small>Scheduled for 10:00 PM daily</small>
- </div>
- `;
- document.getElementById('next-generation').textContent = '6:00 AM';
- }
- }
-
- function updateMetrics(data) {
- const metrics = document.getElementById('performance-metrics');
- if (data && data.totalVideos !== undefined) {
- document.getElementById('content-count').textContent = data.totalVideos || '0';
- document.getElementById('published-count').textContent = data.totalVideos || '0';
-
- metrics.innerHTML = `
- <p><strong>Average Performance:</strong> ${data.averagePerformanceScore || 'N/A'}</p>
- <p><strong>Total Content:</strong> ${data.totalVideos || 0}</p>
- <p><strong>System Health:</strong> Excellent</p>
- `;
- } else {
- metrics.innerHTML = `
- <p><strong>Status:</strong> System just started</p>
- <p><strong>First Content:</strong> Will generate within 24 hours</p>
- <p><strong>Automation:</strong> Active and ready</p>
- `;
- }
-
- // Update activity log
- const activity = document.getElementById('recent-activity');
- activity.innerHTML = `
- <div class="log-entry success">✅ System initialized successfully</div>
- <div class="log-entry info">ℹ️ All 7 agents are active</div>
- <div class="log-entry info">ℹ️ Content strategy loaded</div>
- <div class="log-entry info">ℹ️ Automation scheduler started</div>
- <div class="log-entry success">✅ Ready for content generation</div>
- `;
- }
-
- function formatUptime(seconds) {
- const hours = Math.floor(seconds / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
- return `${hours}h ${minutes}m`;
- }
-
- // API key handling for protected endpoints (API_KEY in .env)
- function getStoredApiKey() {
- return localStorage.getItem('yaa_api_key') || '';
- }
+ </section>
- function promptForApiKey() {
- const key = prompt('This server requires an API key (the API_KEY value from your .env):', getStoredApiKey());
- if (key === null) return null; // user cancelled
- localStorage.setItem('yaa_api_key', key.trim());
- return key.trim();
- }
+ <section id="pipeline-view" class="view">
+ <div class="section-intro"><div><h2>Content pipeline</h2><p>Every generated video, its real state, and the next available action.</p></div><select id="pipeline-filter"><option value="all">All content</option><option value="needs_review">Needs review</option><option value="needs_attention">Needs attention</option><option value="approved">Approved</option><option value="published">Published</option></select></div>
+ <div id="pipeline-list" class="pipeline-list"></div>
+ </section>
- async function postWithApiKey(url, body) {
- const doFetch = (key) => fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- ...(key ? { 'x-api-key': key } : {})
- },
- body: JSON.stringify(body)
- });
+ <section id="calendar-view" class="view">
+ <div class="split-heading"><div><h2>Calendar & idea backlog</h2><p>Shape the queue before generation starts.</p></div><button id="add-idea-button" class="button secondary">+ Add idea</button></div>
+ <div class="calendar-grid">
+ <article class="panel"><div class="panel-heading"><div><p class="eyebrow">SCHEDULED</p><h2>Upcoming releases</h2></div></div><div id="calendar-list" class="calendar-list"></div></article>
+ <article class="panel"><div class="panel-heading"><div><p class="eyebrow">BACKLOG</p><h2>Content ideas</h2></div></div><div id="idea-list" class="idea-list"></div></article>
+ </div>
+ </section>
+
+ <section id="analytics-view" class="view">
+ <div class="section-intro"><div><h2>Performance signals</h2><p>Data translated into decisions, not vanity metrics.</p></div></div>
+ <div class="stats-grid analytics-stats">
+ <article class="stat"><span>Analyzed videos</span><strong id="analytics-total">—</strong><small>last 30 days</small></article>
+ <article class="stat"><span>Performance score</span><strong id="analytics-score">—</strong><small>channel average</small></article>
+ <article class="stat wide"><span>Recommended action</span><strong id="analytics-action" class="recommendation">Collecting enough data to recommend a move.</strong></article>
+ </div>
+ <article class="panel"><div class="panel-heading"><div><p class="eyebrow">TOP PERFORMERS</p><h2>What is working</h2></div></div><div id="top-performers" class="card-list"></div></article>
+ </section>
- let response = await doFetch(getStoredApiKey());
- if (response.status === 401) {
- const key = promptForApiKey();
- if (key !== null) {
- response = await doFetch(key);
- }
- }
- return response;
- }
+ <section id="settings-view" class="view">
+ <div class="section-intro"><div><h2>Channel setup</h2><p>These guardrails guide every agent in the pipeline.</p></div></div>
+ <form id="profile-form" class="panel settings-form">
+ <div class="form-grid">
+ <label><span>Channel name</span><input name="channelName" maxlength="120" required></label>
+ <label><span>Default format</span><select name="defaultStyle"><option value="explainer">Explainer</option><option value="tutorial">Tutorial</option><option value="list">List</option><option value="review">Review</option><option value="story">Story</option></select></label>
+ <label class="full-row"><span>Channel goal</span><textarea name="goal" rows="2"></textarea></label>
+ <label class="full-row"><span>Target audience</span><textarea name="targetAudience" rows="2"></textarea></label>
+ <label><span>Brand voice</span><input name="brandVoice" placeholder="Clear, credible, engaging"></label>
+ <label><span>Timezone</span><input name="timezone" placeholder="America/Chicago"></label>
+ <label class="full-row"><span>Default call to action</span><input name="callToAction"></label>
+ <label class="full-row"><span>Visual direction</span><input name="visualStyle"></label>
+ <label class="full-row"><span>Blocked topics or terms</span><input name="bannedTopics" placeholder="term one, term two"><small>Quality review blocks content containing these terms.</small></label>
+ </div>
+ <div class="settings-row">
+ <label class="toggle"><input id="approval-required" type="checkbox"><span></span> Require approval before scheduling</label>
+ <label class="toggle"><input id="notifications-enabled" type="checkbox"><span></span> Save operator notifications</label>
+ </div>
+ <div class="form-actions"><button type="submit" class="button primary">Save channel setup</button><button id="api-key-button" type="button" class="button secondary">Set dashboard API key</button></div>
+ </form>
+ </section>
+ </main>
+ </div>
- async function generateContent() {
- if (!confirm('Generate content now? This will create a new video for your channel.')) {
- return;
- }
+ <dialog id="generate-dialog" class="dialog">
+ <form id="generate-form" method="dialog">
+ <div class="dialog-heading"><div><p class="eyebrow">NEW GENERATION JOB</p><h2>Create a video</h2></div><button type="button" class="close-button" data-close>×</button></div>
+ <label><span>Topic <small>optional—leave blank for agent selection</small></span><input name="topic" maxlength="200" placeholder="How small teams can automate repetitive work"></label>
+ <div class="form-grid two">
+ <label><span>Format</span><select name="style"><option value="explainer">Explainer</option><option value="tutorial">Tutorial</option><option value="list">List</option><option value="review">Review</option><option value="story">Story</option></select></label>
+ <label><span>Length</span><select name="length"><option value="short">Short · 2–4 min</option><option value="medium" selected>Medium · 8–12 min</option><option value="long">Long · 15–20 min</option></select></label>
+ </div>
+ <p class="callout">Generation runs in the background. You can follow each stage and cancel between stages.</p>
+ <div class="form-actions"><button type="submit" class="button primary">Start generation</button><button type="button" class="button ghost" data-close>Cancel</button></div>
+ </form>
+ </dialog>
- try {
- const response = await postWithApiKey('/generate', { topic: null, style: 'story' });
- const result = await response.json().catch(() => ({}));
+ <dialog id="content-dialog" class="dialog content-dialog">
+ <div id="content-detail"></div>
+ </dialog>
- if (!response.ok) {
- alert(`Content generation failed: ${result.error || response.statusText}`);
- return;
- }
+ <dialog id="idea-dialog" class="dialog">
+ <form id="idea-form" method="dialog">
+ <div class="dialog-heading"><div><p class="eyebrow">BACKLOG</p><h2>Add a content idea</h2></div><button type="button" class="close-button" data-close>×</button></div>
+ <label><span>Topic</span><input name="topic" maxlength="200" required></label>
+ <label><span>Angle</span><textarea name="angle" rows="3" placeholder="What makes this take distinctive?"></textarea></label>
+ <label><span>Why it is worth making</span><textarea name="rationale" rows="2"></textarea></label>
+ <label><span>Format</span><select name="style"><option value="explainer">Explainer</option><option value="tutorial">Tutorial</option><option value="list">List</option><option value="review">Review</option><option value="story">Story</option></select></label>
+ <div class="form-actions"><button type="submit" class="button primary">Add to backlog</button><button type="button" class="button ghost" data-close>Cancel</button></div>
+ </form>
+ </dialog>
- alert(`Content generation started! Title: ${result.result?.title || 'New Content'}`);
- refreshDashboard();
- } catch (error) {
- alert('Content generation failed. Please try again.');
- }
- }
-
- function viewAnalytics() {
- window.open('/analytics', '_blank');
- }
-
- function viewSchedule() {
- window.open('/schedule', '_blank');
- }
-
- function refreshDashboard() {
- loadDashboard();
- }
-
- // Auto-refresh every 30 seconds
- setInterval(refreshDashboard, 30000);
-
- // Load dashboard on page load
- loadDashboard();
- </script>
+ <script src="/app.js" defer></script>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/dashboard/styles.css b/dashboard/styles.css
new file mode 100644
index 0000000..de243b9
--- /dev/null
+++ b/dashboard/styles.css
@@ -0,0 +1,166 @@
+:root {
+ --bg: #090b0f;
+ --panel: #11151b;
+ --panel-soft: #151a22;
+ --line: #252c37;
+ --text: #f4f6f8;
+ --muted: #929baa;
+ --red: #ff4d5e;
+ --red-soft: rgba(255, 77, 94, .13);
+ --green: #48d597;
+ --amber: #f5b944;
+ --blue: #72a5ff;
+ --radius: 16px;
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+}
+* { box-sizing: border-box; }
+body { margin: 0; color: var(--text); background: radial-gradient(circle at 80% 0%, #17131b 0, var(--bg) 30%); min-height: 100vh; }
+button, input, select, textarea { font: inherit; }
+button { color: inherit; }
+.app-shell { display: grid; grid-template-columns: 248px 1fr; min-height: 100vh; }
+.sidebar { border-right: 1px solid var(--line); padding: 28px 18px; display: flex; flex-direction: column; position: sticky; top: 0; height: 100vh; background: rgba(9,11,15,.9); backdrop-filter: blur(18px); }
+.brand { display: flex; gap: 12px; align-items: center; color: var(--text); text-decoration: none; padding: 0 8px 34px; }
+.brand-mark { width: 38px; height: 38px; border-radius: 12px; background: var(--red); display: grid; place-items: center; box-shadow: 0 8px 24px rgba(255,77,94,.22); }
+.brand strong, .brand small { display: block; }
+.brand strong { max-width: 155px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.brand small { color: var(--muted); font-size: 11px; margin-top: 3px; }
+nav { display: grid; gap: 7px; }
+.nav-item { border: 0; background: transparent; color: var(--muted); text-align: left; padding: 12px 14px; border-radius: 10px; cursor: pointer; display: flex; gap: 12px; align-items: center; }
+.nav-item:hover, .nav-item.active { background: var(--panel-soft); color: var(--text); }
+.nav-item.active { box-shadow: inset 2px 0 var(--red); }
+.badge { margin-left: auto; border-radius: 999px; background: var(--red); color: white; font-size: 11px; padding: 2px 7px; }
+.sidebar-footer { margin-top: auto; display: grid; gap: 14px; }
+.system-pill { color: var(--muted); display: flex; align-items: center; gap: 8px; font-size: 13px; padding: 0 8px; }
+.system-pill i { width: 8px; height: 8px; border-radius: 50%; background: var(--amber); box-shadow: 0 0 10px currentColor; }
+.system-pill i.online { background: var(--green); }
+main { padding: 0 4vw 70px; min-width: 0; }
+.topbar { min-height: 132px; display: flex; align-items: center; justify-content: space-between; gap: 20px; }
+h1, h2, h3, p { margin-top: 0; }
+h1 { font-size: clamp(27px, 3vw, 42px); letter-spacing: -.04em; margin-bottom: 0; }
+h2 { letter-spacing: -.025em; margin-bottom: 0; }
+.eyebrow { color: var(--red); letter-spacing: .14em; font-size: 10px; font-weight: 800; margin-bottom: 8px; }
+.top-actions, .form-actions { display: flex; gap: 10px; align-items: center; }
+.button, .icon-button, .text-button, .close-button { border: 0; cursor: pointer; }
+.button { border-radius: 10px; padding: 11px 16px; font-weight: 700; }
+.button.primary { background: var(--red); color: white; box-shadow: 0 8px 24px rgba(255,77,94,.17); }
+.button.primary:hover { background: #ff6271; }
+.button.secondary { background: var(--panel-soft); border: 1px solid var(--line); }
+.button.ghost { background: transparent; color: var(--muted); }
+.button.danger { background: var(--red-soft); color: #ff8994; }
+.button.full { width: 100%; }
+.button.small { font-size: 12px; padding: 8px 10px; }
+.icon-button, .close-button { width: 42px; height: 42px; border-radius: 10px; background: var(--panel-soft); border: 1px solid var(--line); font-size: 22px; }
+.text-button { color: var(--muted); background: none; font-size: 13px; }
+.text-button:hover { color: var(--text); }
+.view { display: none; animation: enter .22s ease-out; }
+.view.active { display: block; }
+.setup-banner { display: flex; align-items: center; justify-content: space-between; gap: 20px; border: 1px solid rgba(245,185,68,.35); background: rgba(245,185,68,.08); border-radius: var(--radius); padding: 18px 20px; margin-bottom: 18px; }
+.setup-banner strong { color: #ffd67d; }
+.setup-banner p { color: var(--muted); margin: 5px 0 0; font-size: 13px; }
+.setup-banner code { background: #0b0e12; border: 1px solid var(--line); border-radius: 8px; padding: 9px 12px; white-space: nowrap; }
+@keyframes enter { from { opacity: 0; transform: translateY(5px); } }
+.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 18px; }
+.stat, .panel { border: 1px solid var(--line); background: linear-gradient(150deg, rgba(21,26,34,.96), rgba(13,16,21,.96)); border-radius: var(--radius); }
+.stat { padding: 20px; min-height: 128px; display: flex; flex-direction: column; }
+.stat span, .stat small { color: var(--muted); }
+.stat span { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }
+.stat strong { font-size: 36px; letter-spacing: -.04em; margin: auto 0 1px; }
+.stat small { font-size: 11px; }
+.overview-grid { display: grid; grid-template-columns: 1.5fr 1fr; gap: 18px; margin-bottom: 18px; }
+.overview-grid.lower { grid-template-columns: 1fr 1fr; }
+.panel { padding: 22px; }
+.panel-heading, .split-heading, .section-intro { display: flex; align-items: center; justify-content: space-between; gap: 20px; }
+.panel-heading { margin-bottom: 18px; }
+.panel-heading h2 { font-size: 19px; }
+.card-list, .activity-list, .timeline, .idea-list, .calendar-list { display: grid; gap: 10px; }
+.empty { color: var(--muted); border: 1px dashed var(--line); padding: 24px; border-radius: 12px; text-align: center; }
+.review-card, .job-card, .activity, .timeline-item, .idea-card, .performer-card { border: 1px solid var(--line); background: rgba(255,255,255,.018); border-radius: 12px; padding: 14px; }
+.review-card, .job-card, .timeline-item, .idea-card { display: flex; align-items: center; gap: 14px; }
+.review-thumb { width: 86px; aspect-ratio: 16/9; background: #222833; border-radius: 8px; object-fit: cover; }
+.review-meta, .job-meta, .timeline-meta, .idea-meta { min-width: 0; flex: 1; }
+.review-meta strong, .job-meta strong, .timeline-meta strong, .idea-meta strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.meta-line { color: var(--muted); font-size: 12px; margin-top: 5px; }
+.status { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; background: rgba(114,165,255,.12); color: var(--blue); }
+.status.needs_review, .status.queued { color: var(--amber); background: rgba(245,185,68,.12); }
+.status.needs_attention, .status.failed, .status.rejected { color: #ff8994; background: var(--red-soft); }
+.status.approved, .status.scheduled, .status.published, .status.completed { color: var(--green); background: rgba(72,213,151,.12); }
+.progress { height: 5px; border-radius: 99px; background: #262c35; margin-top: 9px; overflow: hidden; }
+.progress i { display: block; height: 100%; background: var(--red); border-radius: inherit; }
+.activity { display: grid; grid-template-columns: 8px 1fr auto; gap: 10px; align-items: start; }
+.activity i { width: 7px; height: 7px; background: var(--blue); border-radius: 50%; margin-top: 5px; }
+.activity.error i { background: var(--red); }
+.activity.warning i { background: var(--amber); }
+.activity.success i { background: var(--green); }
+.activity p { margin: 0; font-size: 13px; }
+.activity small { color: var(--muted); font-size: 10px; }
+.section-intro, .split-heading { margin-bottom: 24px; }
+.section-intro p, .split-heading p { color: var(--muted); margin: 7px 0 0; }
+select, input, textarea { width: 100%; border: 1px solid var(--line); background: #0d1015; color: var(--text); border-radius: 9px; padding: 11px 12px; outline: none; }
+input:focus, textarea:focus, select:focus { border-color: #636d7c; box-shadow: 0 0 0 3px rgba(114,165,255,.08); }
+.section-intro select { width: auto; min-width: 170px; }
+.pipeline-list { display: grid; gap: 10px; }
+.pipeline-item { display: grid; grid-template-columns: minmax(260px, 2fr) 1fr 1fr auto; gap: 18px; align-items: center; border: 1px solid var(--line); background: var(--panel); padding: 17px; border-radius: 13px; cursor: pointer; }
+.pipeline-item:hover { border-color: #3a4452; transform: translateY(-1px); }
+.pipeline-title strong { display: block; margin-bottom: 5px; }
+.pipeline-title span, .pipeline-col span { color: var(--muted); font-size: 11px; }
+.pipeline-col strong { display: block; font-size: 13px; margin-top: 4px; }
+.calendar-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
+.date-chip { min-width: 52px; text-align: center; border: 1px solid var(--line); border-radius: 9px; padding: 7px; }
+.date-chip strong, .date-chip small { display: block; }
+.date-chip strong { font-size: 19px; }
+.date-chip small { color: var(--red); font-size: 9px; text-transform: uppercase; }
+.analytics-stats { grid-template-columns: 1fr 1fr 2fr; }
+.stat.wide strong.recommendation { font-size: 19px; line-height: 1.35; letter-spacing: -.02em; }
+.settings-form { max-width: 920px; }
+.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
+.form-grid.two { grid-template-columns: 1fr 1fr; }
+label { display: grid; gap: 7px; color: var(--muted); font-size: 12px; }
+label > span { color: var(--text); font-weight: 700; }
+label small { color: var(--muted); font-weight: 400; }
+.full-row { grid-column: 1 / -1; }
+.settings-row { display: flex; flex-wrap: wrap; gap: 24px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); margin: 24px 0; padding: 18px 0; }
+.toggle { display: flex; align-items: center; gap: 9px; color: var(--text); cursor: pointer; }
+.toggle input { width: auto; }
+.dialog { width: min(560px, calc(100vw - 30px)); border: 1px solid var(--line); background: #11151b; color: var(--text); border-radius: 18px; padding: 24px; box-shadow: 0 30px 100px rgba(0,0,0,.55); }
+.dialog::backdrop { background: rgba(1,3,6,.76); backdrop-filter: blur(7px); }
+.dialog form { display: grid; gap: 18px; }
+.dialog-heading { display: flex; align-items: start; justify-content: space-between; }
+.dialog-heading h2 { font-size: 27px; }
+.content-dialog { width: min(980px, calc(100vw - 30px)); }
+.callout { background: rgba(114,165,255,.08); border: 1px solid rgba(114,165,255,.18); padding: 12px; border-radius: 10px; color: #b9d0fb; font-size: 12px; margin: 0; }
+.content-layout { display: grid; grid-template-columns: 1fr 1.15fr; gap: 22px; }
+.preview { background: #080a0d; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; aspect-ratio: 16/9; display: grid; place-items: center; }
+.preview video, .preview img { width: 100%; height: 100%; object-fit: contain; }
+.preview-placeholder { color: var(--muted); text-align: center; padding: 20px; }
+.editor { display: grid; gap: 14px; }
+.quality-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; margin: 18px 0; }
+.quality-check { font-size: 11px; color: var(--muted); border: 1px solid var(--line); border-radius: 8px; padding: 9px; }
+.quality-check.pass { color: var(--green); }
+.quality-check.fail { color: #ff8994; }
+.loading-bar { height: 2px; position: fixed; top: 0; left: 248px; right: 0; z-index: 10; overflow: hidden; }
+.loading-bar.active::after { content: ""; display: block; height: 100%; width: 35%; background: var(--red); animation: load 1s infinite ease-in-out; }
+@keyframes load { from { transform: translateX(-100%); } to { transform: translateX(400%); } }
+.toast { position: fixed; right: 28px; bottom: 28px; max-width: 380px; background: #202630; border: 1px solid #3b4554; border-radius: 11px; padding: 13px 16px; z-index: 30; box-shadow: 0 18px 50px rgba(0,0,0,.35); }
+.toast.error { border-color: var(--red); }
+.hidden { display: none !important; }
+@media (max-width: 900px) {
+ .app-shell { grid-template-columns: 1fr; }
+ .sidebar { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 16px; }
+ .brand { padding-bottom: 14px; }
+ nav { display: flex; overflow-x: auto; }
+ .nav-item { white-space: nowrap; }
+ .sidebar-footer { display: none; }
+ main { padding: 0 18px 60px; }
+ .loading-bar { left: 0; }
+ .stats-grid { grid-template-columns: 1fr 1fr; }
+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout { grid-template-columns: 1fr; }
+ .pipeline-item { grid-template-columns: 1fr auto; }
+ .pipeline-col { display: none; }
+}
+@media (max-width: 560px) {
+ .topbar { align-items: flex-start; padding: 25px 0; }
+ .top-actions .icon-button { display: none; }
+ .stats-grid, .form-grid, .form-grid.two, .quality-grid { grid-template-columns: 1fr; }
+ .full-row { grid-column: auto; }
+ .stat { min-height: 110px; }
+}
diff --git a/database/db.js b/database/db.js
index 1080604..a64fdec 100644
--- a/database/db.js
+++ b/database/db.js
@@ -184,6 +184,79 @@ class Database {
status TEXT NOT NULL,
data TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+ `CREATE TABLE IF NOT EXISTS generation_jobs (
+ id TEXT PRIMARY KEY,
+ topic TEXT,
+ style TEXT,
+ length TEXT DEFAULT 'medium',
+ source TEXT DEFAULT 'manual',
+ status TEXT DEFAULT 'queued',
+ stage TEXT DEFAULT 'queued',
+ progress INTEGER DEFAULT 0,
+ production_id TEXT,
+ title TEXT,
+ error TEXT,
+ details TEXT,
+ cancel_requested INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ completed_at TEXT
+ )`,
+ `CREATE TABLE IF NOT EXISTS production_snapshots (
+ production_id TEXT PRIMARY KEY,
+ strategy TEXT,
+ script TEXT,
+ thumbnail TEXT,
+ seo TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (production_id) REFERENCES productions(id)
+ )`,
+ `CREATE TABLE IF NOT EXISTS content_reviews (
+ production_id TEXT PRIMARY KEY,
+ status TEXT DEFAULT 'needs_review',
+ editor_data TEXT,
+ quality_checks TEXT,
+ review_notes TEXT,
+ reviewed_at TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (production_id) REFERENCES productions(id)
+ )`,
+ `CREATE TABLE IF NOT EXISTS channel_profiles (
+ id TEXT PRIMARY KEY,
+ channel_name TEXT,
+ goal TEXT,
+ target_audience TEXT,
+ brand_voice TEXT,
+ default_style TEXT,
+ call_to_action TEXT,
+ banned_topics TEXT,
+ visual_style TEXT,
+ timezone TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+ `CREATE TABLE IF NOT EXISTS content_ideas (
+ id TEXT PRIMARY KEY,
+ topic TEXT NOT NULL,
+ angle TEXT,
+ style TEXT,
+ status TEXT DEFAULT 'backlog',
+ rationale TEXT,
+ scheduled_for TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+ `CREATE TABLE IF NOT EXISTS notifications (
+ id TEXT PRIMARY KEY,
+ type TEXT NOT NULL,
+ level TEXT DEFAULT 'info',
+ title TEXT NOT NULL,
+ message TEXT NOT NULL,
+ data TEXT,
+ status TEXT DEFAULT 'unread',
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP
)`,
// System Settings
`CREATE TABLE IF NOT EXISTS settings (
@@ -212,6 +285,9 @@ class Database {
['thumbnail_ab_testing', 'false', 'Enable thumbnail A/B testing'],
['content_backup_enabled', 'true', 'Enable content backup'],
['notification_enabled', 'true', 'Enable system notifications'],
+ ['approval_required', 'true', 'Require human approval before scheduling generated content'],
+ ['automation_paused', 'false', 'Pause generation and publishing automation'],
+ ['channel_timezone', 'America/Chicago', 'Timezone used to present channel schedules'],
['max_daily_posts', '1', 'Maximum posts per day'],
['content_buffer_days', '3', 'Days of content to keep in buffer']
];
@@ -222,6 +298,24 @@ class Database {
[key, value, description]
);
}
+
+ await this.executeQuery(
+ `INSERT OR IGNORE INTO channel_profiles (
+ id, channel_name, goal, target_audience, brand_voice, default_style,
+ call_to_action, banned_topics, visual_style, timezone
+ ) VALUES ('default', ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [
+ process.env.CHANNEL_NAME || 'My YouTube Channel',
+ 'Grow a trusted, useful YouTube channel',
+ process.env.TARGET_AUDIENCE || 'General audience',
+ 'Clear, credible, and engaging',
+ 'explainer',
+ 'Subscribe for more useful videos.',
+ '[]',
+ 'Clean, high-contrast, and readable',
+ process.env.CHANNEL_TIMEZONE || 'America/Chicago'
+ ]
+ );
}
// Content Strategy methods
@@ -369,6 +463,253 @@ class Database {
}));
}
+ async saveProductionSnapshot(production) {
+ await this.executeQuery(
+ `INSERT OR REPLACE INTO production_snapshots (
+ production_id, strategy, script, thumbnail, seo
+ ) VALUES (?, ?, ?, ?, ?)`,
+ [
+ production.id,
+ JSON.stringify(production.strategy || {}),
+ JSON.stringify(production.script || {}),
+ JSON.stringify(production.thumbnail || {}),
+ JSON.stringify(production.seo || {})
+ ]
+ );
+ }
+
+ async updateProductionStatus(productionId, status) {
+ await this.executeQuery('UPDATE productions SET status = ? WHERE id = ?', [status, productionId]);
+ }
+
+ async getProductionBundle(productionId) {
+ const row = await this.getRow(
+ `SELECT p.*, ps.strategy, ps.script, ps.thumbnail, ps.seo,
+ cr.status AS review_status, cr.editor_data, cr.quality_checks,
+ cr.review_notes, cr.reviewed_at
+ FROM productions p
+ LEFT JOIN production_snapshots ps ON ps.production_id = p.id
+ LEFT JOIN content_reviews cr ON cr.production_id = p.id
+ WHERE p.id = ?`,
+ [productionId]
+ );
+ if (!row) return null;
+
+ const schedule = await this.getRow(
+ 'SELECT * FROM publish_schedule WHERE production_id = ? ORDER BY created_at DESC LIMIT 1',
+ [productionId]
+ );
+ return {
+ ...row,
+ assets: JSON.parse(row.assets || '{}'),
+ timeline: JSON.parse(row.timeline || '{}'),
+ strategy: JSON.parse(row.strategy || '{}'),
+ script: JSON.parse(row.script || '{}'),
+ thumbnail: JSON.parse(row.thumbnail || '{}'),
+ seo: JSON.parse(row.seo || '{}'),
+ editorData: JSON.parse(row.editor_data || '{}'),
+ qualityChecks: JSON.parse(row.quality_checks || '[]'),
+ schedule: schedule ? { ...schedule, metadata: JSON.parse(schedule.metadata || '{}') } : null
+ };
+ }
+
+ async getPipelineOverview(limit = 50) {
+ const rows = await this.getAllRows(
+ `SELECT p.id, p.status, p.assets, p.timeline, p.scheduled_publish_time,
+ p.priority, p.estimated_duration, p.created_at,
+ ps.strategy, ps.script, ps.seo,
+ cr.status AS review_status, cr.quality_checks,
+ sch.id AS schedule_id, sch.status AS schedule_status,
+ sch.publish_time, sch.youtube_url, sch.error_message
+ FROM productions p
+ LEFT JOIN production_snapshots ps ON ps.production_id = p.id
+ LEFT JOIN content_reviews cr ON cr.production_id = p.id
+ LEFT JOIN publish_schedule sch ON sch.id = (
+ SELECT id FROM publish_schedule WHERE production_id = p.id ORDER BY created_at DESC LIMIT 1
+ )
+ ORDER BY p.created_at DESC LIMIT ?`,
+ [limit]
+ );
+ return rows.map(row => {
+ const strategy = JSON.parse(row.strategy || '{}');
+ const script = JSON.parse(row.script || '{}');
+ const seo = JSON.parse(row.seo || '{}');
+ const assets = JSON.parse(row.assets || '{}');
+ return {
+ ...row,
+ strategy,
+ script,
+ seo,
+ assets,
+ timeline: JSON.parse(row.timeline || '{}'),
+ qualityChecks: JSON.parse(row.quality_checks || '[]'),
+ title: seo.title || script.title || strategy.topic || row.id,
+ topic: strategy.topic || '',
+ hasVideo: Boolean(assets.finalVideo?.path && !assets.finalVideo?.simulated),
+ hasThumbnail: Boolean(assets.thumbnail?.path)
+ };
+ });
+ }
+
+ async createGenerationJob(input = {}) {
+ const id = this.generateId('job');
+ await this.executeQuery(
+ `INSERT INTO generation_jobs (
+ id, topic, style, length, source, status, stage, progress, details
+ ) VALUES (?, ?, ?, ?, ?, 'queued', 'queued', 0, ?)`,
+ [id, input.topic || null, input.style || null, input.length || 'medium', input.source || 'manual', '{}']
+ );
+ return this.getGenerationJob(id);
+ }
+
+ async getGenerationJob(id) {
+ const row = await this.getRow('SELECT * FROM generation_jobs WHERE id = ?', [id]);
+ return row ? { ...row, details: JSON.parse(row.details || '{}'), cancelRequested: Boolean(row.cancel_requested) } : null;
+ }
+
+ async updateGenerationJob(id, changes = {}) {
+ const current = await this.getGenerationJob(id);
+ if (!current) return null;
+ const details = { ...(current.details || {}), ...(changes.details || {}) };
+ await this.executeQuery(
+ `UPDATE generation_jobs SET status = ?, stage = ?, progress = ?, production_id = ?,
+ title = ?, error = ?, details = ?, cancel_requested = ?, updated_at = datetime('now'),
+ completed_at = ? WHERE id = ?`,
+ [
+ changes.status ?? current.status,
+ changes.stage ?? current.stage,
+ changes.progress ?? current.progress,
+ changes.productionId ?? current.production_id,
+ changes.title ?? current.title,
+ changes.error === undefined ? current.error : changes.error,
+ JSON.stringify(details),
+ changes.cancelRequested === undefined ? current.cancel_requested : Number(changes.cancelRequested),
+ changes.completedAt === undefined ? current.completed_at : changes.completedAt,
+ id
+ ]
+ );
+ return this.getGenerationJob(id);
+ }
+
+ async listGenerationJobs(limit = 30) {
+ const rows = await this.getAllRows('SELECT * FROM generation_jobs ORDER BY created_at DESC LIMIT ?', [limit]);
+ return rows.map(row => ({ ...row, details: JSON.parse(row.details || '{}'), cancelRequested: Boolean(row.cancel_requested) }));
+ }
+
+ async markInterruptedJobs() {
+ await this.executeQuery(
+ `UPDATE generation_jobs SET status = 'interrupted', stage = 'interrupted',
+ error = 'The application restarted before this job finished', updated_at = datetime('now'),
+ completed_at = datetime('now') WHERE status IN ('queued', 'running')`
+ );
+ }
+
+ async saveContentReview(productionId, review = {}) {
+ await this.executeQuery(
+ `INSERT INTO content_reviews (
+ production_id, status, editor_data, quality_checks, review_notes, reviewed_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
+ ON CONFLICT(production_id) DO UPDATE SET
+ status = excluded.status, editor_data = excluded.editor_data,
+ quality_checks = excluded.quality_checks, review_notes = excluded.review_notes,
+ reviewed_at = excluded.reviewed_at, updated_at = datetime('now')`,
+ [
+ productionId,
+ review.status || 'needs_review',
+ JSON.stringify(review.editorData || {}),
+ JSON.stringify(review.qualityChecks || []),
+ review.reviewNotes || null,
+ review.reviewedAt || null
+ ]
+ );
+ return this.getProductionBundle(productionId);
+ }
+
+ async getChannelProfile() {
+ const row = await this.getRow("SELECT * FROM channel_profiles WHERE id = 'default'");
+ return row ? { ...row, bannedTopics: JSON.parse(row.banned_topics || '[]') } : null;
+ }
+
+ async saveChannelProfile(profile) {
+ const current = await this.getChannelProfile() || {};
+ await this.executeQuery(
+ `INSERT OR REPLACE INTO channel_profiles (
+ id, channel_name, goal, target_audience, brand_voice, default_style,
+ call_to_action, banned_topics, visual_style, timezone, created_at, updated_at
+ ) VALUES ('default', ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')), datetime('now'))`,
+ [
+ profile.channelName ?? current.channel_name ?? '',
+ profile.goal ?? current.goal ?? '',
+ profile.targetAudience ?? current.target_audience ?? '',
+ profile.brandVoice ?? current.brand_voice ?? '',
+ profile.defaultStyle ?? current.default_style ?? 'explainer',
+ profile.callToAction ?? current.call_to_action ?? '',
+ JSON.stringify(profile.bannedTopics ?? current.bannedTopics ?? []),
+ profile.visualStyle ?? current.visual_style ?? '',
+ profile.timezone ?? current.timezone ?? 'America/Chicago',
+ current.created_at || null
+ ]
+ );
+ return this.getChannelProfile();
+ }
+
+ async createContentIdea(idea) {
+ const id = this.generateId('idea');
+ await this.executeQuery(
+ `INSERT INTO content_ideas (id, topic, angle, style, status, rationale, scheduled_for)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ [id, idea.topic, idea.angle || null, idea.style || 'explainer', idea.status || 'backlog', idea.rationale || null, idea.scheduledFor || null]
+ );
+ return this.getRow('SELECT * FROM content_ideas WHERE id = ?', [id]);
+ }
+
+ async listContentIdeas() {
+ return this.getAllRows("SELECT * FROM content_ideas WHERE status != 'archived' ORDER BY COALESCE(scheduled_for, '9999-12-31'), created_at DESC");
+ }
+
+ async updateContentIdea(id, changes) {
+ const current = await this.getRow('SELECT * FROM content_ideas WHERE id = ?', [id]);
+ if (!current) return null;
+ await this.executeQuery(
+ `UPDATE content_ideas SET topic = ?, angle = ?, style = ?, status = ?,
+ rationale = ?, scheduled_for = ?, updated_at = datetime('now') WHERE id = ?`,
+ [
+ changes.topic ?? current.topic,
+ changes.angle ?? current.angle,
+ changes.style ?? current.style,
+ changes.status ?? current.status,
+ changes.rationale ?? current.rationale,
+ changes.scheduledFor === undefined ? current.scheduled_for : changes.scheduledFor,
+ id
+ ]
+ );
+ return this.getRow('SELECT * FROM content_ideas WHERE id = ?', [id]);
+ }
+
+ async createNotification(notification) {
+ const id = this.generateId('notice');
+ await this.executeQuery(
+ `INSERT INTO notifications (id, type, level, title, message, data)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ [id, notification.type || 'system', notification.level || 'info', notification.title, notification.message, JSON.stringify(notification.data || {})]
+ );
+ return id;
+ }
+
+ async listNotifications(limit = 20) {
+ const rows = await this.getAllRows('SELECT * FROM notifications ORDER BY created_at DESC LIMIT ?', [limit]);
+ return rows.map(row => ({ ...row, data: JSON.parse(row.data || '{}') }));
+ }
+
+ async markNotificationRead(id) {
+ await this.executeQuery("UPDATE notifications SET status = 'read' WHERE id = ?", [id]);
+ }
+
+ async getRecentAutomationEvents(limit = 30) {
+ const rows = await this.getAllRows('SELECT * FROM automation_events ORDER BY created_at DESC LIMIT ?', [limit]);
+ return rows.map(row => ({ ...row, data: JSON.parse(row.data || '{}') }));
+ }
+
// Publishing methods
async saveScheduleEntry(entry) {
const id = this.generateId('schedule');
@@ -396,11 +737,16 @@ class Database {
async updateScheduleEntry(entry) {
await this.executeQuery(
`UPDATE publish_schedule SET
- status = ?, youtube_id = ?, youtube_url = ?,
- published_at = ?, error_message = ?
+ title = COALESCE(?, title), publish_time = COALESCE(?, publish_time),
+ status = ?, priority = COALESCE(?, priority), metadata = COALESCE(?, metadata),
+ youtube_id = ?, youtube_url = ?, published_at = ?, error_message = ?
WHERE id = ?`,
[
+ entry.title || null,
+ entry.publishTime || entry.publish_time || null,
entry.status,
+ entry.priority ?? null,
+ entry.metadata ? JSON.stringify(entry.metadata) : null,
entry.youtubeId || null,
entry.youtubeUrl || null,
entry.publishedAt || null,
@@ -419,6 +765,12 @@ class Database {
return rows.map(row => ({
...row,
+ productionId: row.production_id,
+ publishTime: row.publish_time,
+ youtubeId: row.youtube_id,
+ youtubeUrl: row.youtube_url,
+ publishedAt: row.published_at,
+ error: row.error_message,
metadata: JSON.parse(row.metadata || '{}')
}));
}
@@ -436,6 +788,12 @@ class Database {
return rows.map(row => ({
...row,
+ productionId: row.production_id,
+ publishTime: row.publish_time,
+ youtubeId: row.youtube_id,
+ youtubeUrl: row.youtube_url,
+ publishedAt: row.published_at,
+ error: row.error_message,
metadata: JSON.parse(row.metadata || '{}')
}));
}
@@ -654,4 +1012,4 @@ class Database {
}
}
-module.exports = { Database };
\ No newline at end of file
+module.exports = { Database };
diff --git a/eslint.config.js b/eslint.config.js
index fdb5375..c3c2a90 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -25,10 +25,17 @@ module.exports = [
globals: {
__dirname: 'readonly',
Buffer: 'readonly',
+ clearTimeout: 'readonly',
clearInterval: 'readonly',
+ confirm: 'readonly',
console: 'readonly',
+ fetch: 'readonly',
+ FormData: 'readonly',
+ localStorage: 'readonly',
+ location: 'readonly',
module: 'readonly',
process: 'readonly',
+ prompt: 'readonly',
require: 'readonly',
setInterval: 'readonly',
setTimeout: 'readonly',
@@ -38,7 +45,11 @@ module.exports = [
}
},
rules: {
- 'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }]
+ 'no-unused-vars': ['warn', {
+ argsIgnorePattern: '^_',
+ varsIgnorePattern: '^_',
+ caughtErrors: 'none'
+ }]
}
}
-];
\ No newline at end of file
+];
diff --git a/index.js b/index.js
index 0c80dce..cd1b9db 100644
--- a/index.js
+++ b/index.js
@@ -2,6 +2,7 @@ require('dotenv').config();
const express = require('express');
const path = require('path');
+const fs = require('fs').promises;
const { Logger } = require('./utils/logger');
const { Database } = require('./database/db');
const { CredentialManager } = require('./utils/credential-manager');
@@ -13,6 +14,7 @@ const { ProductionManagementAgent } = require('./agents/production-management-ag
const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');
const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');
const { DailyAutomation } = require('./schedules/daily-automation');
+const { OperatorService } = require('./utils/operator-service');
const { version } = require('./package.json');
const chalk = require('chalk');
@@ -24,6 +26,9 @@ class YouTubeAutomationAgent {
this.agents = {};
this.app = express();
this.isInitialized = false;
+ this.activeJobs = new Map();
+ this.operator = null;
+ this.setupRequired = false;
}
async initialize() {
@@ -35,6 +40,8 @@ class YouTubeAutomationAgent {
this.logger.info('Initializing database...');
this.db = new Database();
await this.db.initialize();
+ await this.db.markInterruptedJobs();
+ this.operator = new OperatorService(this.db);
// Load credentials
this.logger.info('Loading credentials...');
@@ -44,7 +51,11 @@ class YouTubeAutomationAgent {
if (!credentialsValid) {
console.log(chalk.yellow('\n⚠️ Some credentials are missing or invalid.'));
console.log(chalk.yellow('Run: npm run credentials:setup'));
- return false;
+ this.setupRequired = true;
+ this.setupAPI();
+ this.isInitialized = true;
+ this.logger.warn('Dashboard started in setup mode; generation and publishing are disabled');
+ return true;
}
// Initialize agents
@@ -59,8 +70,14 @@ class YouTubeAutomationAgent {
// Initialize scheduler
this.logger.info('Setting up automation scheduler...');
- this.scheduler = new DailyAutomation(this.agents, this.db);
+ this.scheduler = new DailyAutomation(this.agents, this.db, {
+ generateContent: input => this.startGenerationJob(input)
+ });
await this.scheduler.initialize();
+
+ if (await this.db.getSetting('automation_paused') === 'true') {
+ await this.scheduler.pauseAutomation();
+ }
this.isInitialized = true;
this.logger.success('YouTube Automation Agent initialized successfully!');
@@ -151,7 +168,7 @@ class YouTubeAutomationAgent {
const value = {
topic: null,
style: null,
- length: typeof body.length === 'string' ? body.length : 'medium'
+ length: typeof body.length === 'string' ? body.length.toLowerCase() : 'medium'
};
// JSON has no `undefined`, so clients send `null` to mean "no value provided".
@@ -195,6 +212,10 @@ class YouTubeAutomationAgent {
value.style = allowedStyles.has(style.toLowerCase()) ? style.toLowerCase() : style || null;
}
+ if (!['short', 'medium', 'long'].includes(value.length)) {
+ return { valid: false, status: 400, error: 'length must be short, medium, or long' };
+ }
+
return { valid: true, value };
}
setupAPI() {
@@ -213,8 +234,9 @@ class YouTubeAutomationAgent {
// Health check
this.app.get('/health', (req, res) => {
res.json({
- status: 'healthy',
+ status: this.setupRequired ? 'setup_required' : 'healthy',
initialized: this.isInitialized,
+ setupRequired: this.setupRequired,
agents: Object.keys(this.agents),
uptime: process.uptime(),
timestamp: new Date().toISOString()
@@ -224,22 +246,26 @@ class YouTubeAutomationAgent {
// Manual content generation
this.app.post('/generate', this.requireAPIKey(), async (req, res) => {
try {
+ if (this.setupRequired) {
+ return res.status(503).json({ success: false, error: 'Finish setup with npm run walkthrough before generating content' });
+ }
const validation = this.validateGenerateRequestBody(req.body);
if (!validation.valid) {
return res.status(validation.status).json({ success: false, error: validation.error });
}
const { topic, style, length } = validation.value;
- const result = await this.generateContent(topic, style, length);
- res.json({ success: true, result });
+ const result = await this.startGenerationJob({ topic, style, length, source: 'manual' });
+ res.status(202).json({ success: true, result });
} catch (error) {
- res.status(500).json({ success: false, error: error.message });
+ res.status(error.status || 500).json({ success: false, error: error.message });
}
});
// Get analytics
this.app.get('/analytics', async (req, res) => {
try {
+ if (!this.agents.analytics) return res.json({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] });
const analytics = await this.agents.analytics.getRecentAnalytics();
res.json(analytics);
} catch (error) {
@@ -260,35 +286,333 @@ class YouTubeAutomationAgent {
// Manual publish
this.app.post('/publish/:contentId', this.requireAPIKey(), async (req, res) => {
try {
+ 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') {
+ 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);
res.json({ success: true, result });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
+
+ this.setupOperatorAPI();
+ }
+
+ setupOperatorAPI() {
+ const protect = this.requireAPIKey();
+
+ this.app.get('/api/dashboard', async (_req, res) => {
+ try {
+ const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics] = await Promise.all([
+ this.db.getStats(),
+ this.db.listGenerationJobs(20),
+ this.db.getPipelineOverview(50),
+ this.db.getUpcomingSchedule(30),
+ this.db.getRecentAutomationEvents(20),
+ this.db.listNotifications(20),
+ this.db.getChannelProfile(),
+ this.db.getAllSettings(),
+ this.db.listContentIdeas(),
+ this.agents.analytics
+ ? this.agents.analytics.getRecentAnalytics(30)
+ : Promise.resolve({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] })
+ ]);
+ res.json({
+ stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics,
+ system: {
+ initialized: this.isInitialized,
+ setupRequired: this.setupRequired,
+ uptime: process.uptime(),
+ activeJobs: this.activeJobs.size,
+ automationPaused: this.scheduler ? !this.scheduler.isEnabled : true,
+ agents: Object.keys(this.agents)
+ }
+ });
+ } catch (error) {
+ res.status(500).json({ error: error.message });
+ }
+ });
+
+ this.app.get('/api/jobs/:jobId', async (req, res) => {
+ const job = await this.db.getGenerationJob(req.params.jobId);
+ if (!job) return res.status(404).json({ error: 'Job not found' });
+ return res.json(job);
+ });
+
+ this.app.post('/api/jobs/:jobId/cancel', protect, async (req, res) => {
+ const job = await this.db.getGenerationJob(req.params.jobId);
+ if (!job) return res.status(404).json({ error: 'Job not found' });
+ if (!['queued', 'running'].includes(job.status)) {
+ return res.status(409).json({ error: 'Only queued or running jobs can be cancelled' });
+ }
+ const updated = await this.db.updateGenerationJob(job.id, { cancelRequested: true, details: { cancelReason: req.body?.reason || 'Cancelled by operator' } });
+ return res.json({ success: true, result: updated });
+ });
+
+ this.app.get('/api/content/:productionId', async (req, res) => {
+ const bundle = await this.db.getProductionBundle(req.params.productionId);
+ if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ return res.json(this.decorateContentBundle(bundle));
+ });
+
+ this.app.patch('/api/content/:productionId', protect, async (req, res) => {
+ try {
+ const bundle = await this.db.getProductionBundle(req.params.productionId);
+ if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ if (bundle.review_status === 'approved' && bundle.schedule?.status === 'published') {
+ return res.status(409).json({ error: 'Published content cannot be edited here' });
+ }
+ const editorData = this.validateEditorData(req.body, bundle.editorData);
+ const result = await this.db.saveContentReview(bundle.id, {
+ status: bundle.review_status || 'needs_review',
+ editorData,
+ qualityChecks: bundle.qualityChecks,
+ reviewNotes: req.body.reviewNotes ?? bundle.review_notes,
+ reviewedAt: bundle.reviewed_at
+ });
+ return res.json({ success: true, result: this.decorateContentBundle(result) });
+ } catch (error) {
+ return res.status(400).json({ success: false, error: error.message });
+ }
+ });
+
+ this.app.post('/api/content/:productionId/approve', protect, async (req, res) => {
+ try {
+ const result = await this.approveContent(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, quality: error.quality });
+ }
+ });
+
+ this.app.post('/api/content/:productionId/reject', protect, async (req, res) => {
+ const bundle = await this.db.getProductionBundle(req.params.productionId);
+ if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ await this.db.saveContentReview(bundle.id, {
+ status: 'rejected',
+ editorData: bundle.editorData,
+ qualityChecks: bundle.qualityChecks,
+ reviewNotes: req.body?.notes || 'Rejected by operator',
+ reviewedAt: new Date().toISOString()
+ });
+ await this.db.updateProductionStatus(bundle.id, 'rejected');
+ return res.json({ success: true });
+ });
+
+ this.app.post('/api/content/:productionId/retry', protect, async (req, res) => {
+ const bundle = await this.db.getProductionBundle(req.params.productionId);
+ if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ const job = await this.startGenerationJob({
+ topic: bundle.strategy.topic || bundle.editorData.title || null,
+ style: bundle.strategy.requestedStyle || bundle.strategy.contentType || null,
+ length: bundle.strategy.requestedLengthKey || 'medium',
+ source: 'retry'
+ });
+ return res.status(202).json({ success: true, result: job });
+ });
+
+ this.app.get('/api/content/:productionId/asset/:kind', async (req, res) => {
+ try {
+ const bundle = await this.db.getProductionBundle(req.params.productionId);
+ if (!bundle) return res.status(404).json({ error: 'Content not found' });
+ const allowed = {
+ video: bundle.assets?.finalVideo?.path,
+ thumbnail: bundle.assets?.thumbnail?.path,
+ captions: bundle.assets?.captions?.path,
+ script: bundle.assets?.script?.originalPath
+ };
+ const filePath = allowed[req.params.kind];
+ if (!filePath) return res.status(404).json({ error: 'Asset not found' });
+ const resolved = path.resolve(filePath);
+ const dataRoot = path.resolve(__dirname, 'data');
+ if (!resolved.startsWith(`${dataRoot}${path.sep}`)) return res.status(403).json({ error: 'Asset path is not allowed' });
+ await fs.access(resolved);
+ return res.sendFile(resolved);
+ } catch (_error) {
+ return res.status(404).json({ error: 'Asset not found' });
+ }
+ });
+
+ this.app.put('/api/profile', protect, async (req, res) => {
+ try {
+ const profile = this.validateProfile(req.body || {});
+ return res.json({ success: true, result: await this.db.saveChannelProfile(profile) });
+ } catch (error) {
+ return res.status(400).json({ success: false, error: error.message });
+ }
+ });
+
+ this.app.post('/api/ideas', protect, async (req, res) => {
+ const topic = String(req.body?.topic || '').trim();
+ if (!topic || topic.length > 200) return res.status(400).json({ error: 'A topic of 200 characters or less is required' });
+ const idea = await this.db.createContentIdea({ ...req.body, topic });
+ return res.status(201).json({ success: true, result: idea });
+ });
+
+ this.app.patch('/api/ideas/:ideaId', protect, async (req, res) => {
+ const idea = await this.db.updateContentIdea(req.params.ideaId, req.body || {});
+ if (!idea) return res.status(404).json({ error: 'Idea not found' });
+ return res.json({ success: true, result: idea });
+ });
+
+ this.app.post('/api/ideas/:ideaId/generate', protect, async (req, res) => {
+ const idea = await this.db.updateContentIdea(req.params.ideaId, { status: 'generating' });
+ if (!idea) return res.status(404).json({ error: 'Idea not found' });
+ const job = await this.startGenerationJob({ topic: idea.topic, style: idea.style, length: req.body?.length || 'medium', source: 'idea' });
+ await this.db.updateContentIdea(idea.id, { status: 'generated' });
+ return res.status(202).json({ success: true, result: job });
+ });
+
+ this.app.post('/api/automation/:action', protect, async (req, res) => {
+ if (!this.scheduler) return res.status(409).json({ error: 'Finish setup before controlling automation' });
+ const { action } = req.params;
+ if (action === 'pause') {
+ await this.scheduler.pauseAutomation();
+ await this.db.setSetting('automation_paused', 'true');
+ } else if (action === 'resume') {
+ await this.scheduler.resumeAutomation();
+ await this.db.setSetting('automation_paused', 'false');
+ } else {
+ return res.status(400).json({ error: 'Action must be pause or resume' });
+ }
+ return res.json({ success: true, paused: !this.scheduler.isEnabled });
+ });
+
+ this.app.put('/api/settings', protect, async (req, res) => {
+ const allowed = ['approval_required', 'notification_enabled', 'channel_timezone', 'max_daily_posts', 'content_buffer_days'];
+ for (const key of allowed) {
+ if (req.body?.[key] !== undefined) await this.db.setSetting(key, String(req.body[key]));
+ }
+ return res.json({ success: true, result: await this.db.getAllSettings() });
+ });
+
+ this.app.post('/api/notifications/:notificationId/read', protect, async (req, res) => {
+ await this.db.markNotificationRead(req.params.notificationId);
+ return res.json({ success: true });
+ });
+ }
+
+ async startGenerationJob(input = {}) {
+ if (this.setupRequired || !this.agents.strategy) {
+ const error = new Error('Finish setup with npm run walkthrough before generating content');
+ error.status = 503;
+ throw error;
+ }
+ const maxConcurrent = Math.max(1, parseInt(process.env.MAX_CONCURRENT_JOBS || '1', 10));
+ if (this.activeJobs.size >= maxConcurrent) {
+ const error = new Error(`Generation is busy (${this.activeJobs.size}/${maxConcurrent} active jobs). Try again when the current job finishes.`);
+ error.status = 429;
+ throw error;
+ }
+
+ const validation = this.validateGenerateRequestBody(input);
+ if (!validation.valid) {
+ const error = new Error(validation.error);
+ error.status = validation.status;
+ throw error;
+ }
+
+ const job = await this.db.createGenerationJob({
+ ...validation.value,
+ source: input.source || 'manual'
+ });
+
+ const work = this.runGenerationJob(job.id, validation.value)
+ .catch(error => this.logger.error(`Generation job ${job.id} failed:`, error))
+ .finally(() => this.activeJobs.delete(job.id));
+ this.activeJobs.set(job.id, work);
+ return job;
+ }
+
+ async runGenerationJob(jobId, input) {
+ try {
+ await this.db.updateGenerationJob(jobId, { status: 'running', stage: 'starting', progress: 2, error: null });
+ const result = await this.generateContent(input.topic, input.style, input.length, { jobId });
+ await this.db.updateGenerationJob(jobId, {
+ status: 'completed',
+ stage: result.reviewStatus === 'approved' ? 'scheduled' : result.reviewStatus,
+ progress: 100,
+ productionId: result.contentId,
+ title: result.title,
+ details: { reviewStatus: result.reviewStatus, qualityScore: result.qualityScore },
+ completedAt: new Date().toISOString()
+ });
+ await this.db.setSetting('last_content_generation', new Date().toISOString());
+ return result;
+ } catch (error) {
+ const cancelled = error.code === 'JOB_CANCELLED';
+ await this.db.updateGenerationJob(jobId, {
+ status: cancelled ? 'cancelled' : 'failed',
+ stage: cancelled ? 'cancelled' : 'failed',
+ error: error.message,
+ completedAt: new Date().toISOString()
+ });
+ await this.operator.notify({
+ type: cancelled ? 'generation_cancelled' : 'generation_failure',
+ level: cancelled ? 'warning' : 'error',
+ title: cancelled ? 'Generation cancelled' : 'Generation failed',
+ message: error.message,
+ data: { jobId }
+ });
+ throw error;
+ }
+ }
+
+ async updateJobStage(jobId, stage, progress, details = {}) {
+ if (!jobId) return;
+ const job = await this.db.getGenerationJob(jobId);
+ if (job?.cancelRequested) {
+ const error = new Error(job.details?.cancelReason || 'Generation cancelled by operator');
+ error.code = 'JOB_CANCELLED';
+ throw error;
+ }
+ await this.db.updateGenerationJob(jobId, { stage, progress, details });
}
- async generateContent(topic = null, style = null, length = 'medium') {
+ async generateContent(topic = null, style = null, length = 'medium', options = {}) {
this.logger.info('Starting content generation pipeline...');
-
+ const { jobId = null } = options;
+ const profile = await this.db.getChannelProfile() || {};
+ const lengthLabels = { short: '2-4 minutes', medium: '8-12 minutes', long: '15-20 minutes' };
+
// Step 1: Strategy
+ await this.updateJobStage(jobId, 'strategy', 10);
const strategy = await this.agents.strategy.generateContentStrategy(topic);
+ const contentStyles = new Set(['tutorial', 'explainer', 'list', 'review', 'story']);
+ const requestedStyle = style || profile.default_style || null;
+ if (requestedStyle && contentStyles.has(requestedStyle.toLowerCase())) {
+ strategy.contentType = requestedStyle.charAt(0).toUpperCase() + requestedStyle.slice(1).toLowerCase();
+ }
+ strategy.requestedStyle = requestedStyle;
+ strategy.requestedLengthKey = length;
+ strategy.requestedLength = lengthLabels[length] || lengthLabels.medium;
+ strategy.targetAudience = profile.target_audience || strategy.targetAudience;
+ strategy.brandVoice = profile.brand_voice || null;
+ strategy.channelGoal = profile.goal || null;
+ strategy.callToAction = profile.call_to_action || null;
this.logger.info(`Strategy generated: ${strategy.topic}`);
-
+
// Step 2: Script Writing
+ await this.updateJobStage(jobId, 'script', 25, { topic: strategy.topic });
const script = await this.agents.scriptWriter.generateScript(strategy);
this.logger.info(`Script generated: ${script.title}`);
-
+
// Step 3: Thumbnail Design
+ await this.updateJobStage(jobId, 'thumbnail', 40, { title: script.title });
const thumbnail = await this.agents.thumbnailDesigner.generateThumbnail(script);
this.logger.info('Thumbnail generated');
-
+
// Step 4: SEO Optimization
+ await this.updateJobStage(jobId, 'seo', 52);
const seoData = await this.agents.seoOptimizer.optimize(script, strategy);
this.logger.info('SEO optimization complete');
-
+
// Step 5: Production Management
+ await this.updateJobStage(jobId, 'production', 62);
const productionData = await this.agents.production.processContent({
strategy,
script,
@@ -299,22 +623,198 @@ class YouTubeAutomationAgent {
// Step 6: Save to database
const contentId = await this.db.saveProductionData(productionData);
+ await this.db.saveProductionSnapshot(productionData);
this.logger.info(`Content saved with ID: ${contentId}`);
- // Step 7: Add to the publish queue (skipped automatically for simulated output)
- const scheduleEntry = await this.agents.publishing.scheduleContent(productionData);
- if (scheduleEntry) {
- this.logger.info(`Content queued for publishing at ${scheduleEntry.publishTime}`);
+ // Step 7: Quality and approval gate
+ await this.updateJobStage(jobId, 'quality_review', 90, { contentId });
+ const quality = await this.operator.runQualityChecks(productionData, profile);
+ const approvalRequired = await this.db.getSetting('approval_required') !== 'false';
+ const reviewStatus = quality.passed
+ ? (approvalRequired ? 'needs_review' : 'approved')
+ : 'needs_attention';
+ await this.db.saveContentReview(contentId, {
+ status: reviewStatus,
+ qualityChecks: quality.checks,
+ editorData: {},
+ reviewNotes: quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`,
+ reviewedAt: approvalRequired ? null : new Date().toISOString()
+ });
+
+ let scheduleEntry = null;
+ if (reviewStatus === 'approved') {
+ scheduleEntry = await this.agents.publishing.scheduleContent(productionData);
+ await this.db.updateProductionStatus(contentId, scheduleEntry ? 'scheduled' : productionData.status);
+ } else {
+ await this.db.updateProductionStatus(contentId, reviewStatus);
+ await this.operator.notify({
+ type: 'review_required',
+ level: quality.passed ? 'info' : 'warning',
+ title: quality.passed ? 'Content ready for review' : 'Content needs attention',
+ message: `${script.title} ${quality.passed ? 'is ready for approval' : 'failed one or more quality checks'}`,
+ data: { contentId, qualityScore: quality.score }
+ });
}
return {
contentId,
title: script.title,
status: productionData.status,
+ reviewStatus,
+ qualityScore: quality.score,
scheduledFor: scheduleEntry ? scheduleEntry.publishTime : null
};
}
+ validateEditorData(input = {}, existing = {}) {
+ const output = { ...existing };
+ if (input.title !== undefined) {
+ const title = String(input.title).trim();
+ if (!title || title.length > 100) throw new Error('Title must be between 1 and 100 characters');
+ output.title = title;
+ }
+ if (input.description !== undefined) {
+ const description = String(input.description).trim();
+ if (description.length > 5000) throw new Error('Description must be 5,000 characters or less');
+ output.description = description;
+ }
+ if (input.tags !== undefined) {
+ const tags = Array.isArray(input.tags)
+ ? input.tags
+ : String(input.tags).split(',');
+ output.tags = tags.map(tag => String(tag).trim()).filter(Boolean).slice(0, 30);
+ }
+ if (input.publishTime !== undefined) {
+ const date = new Date(input.publishTime);
+ if (Number.isNaN(date.getTime())) throw new Error('Publish time must be a valid date');
+ output.publishTime = date.toISOString();
+ }
+ if (input.privacyStatus !== undefined) {
+ if (!['private', 'unlisted', 'public'].includes(input.privacyStatus)) throw new Error('Invalid privacy status');
+ output.privacyStatus = input.privacyStatus;
+ }
+ if (input.factChecked !== undefined) output.factChecked = input.factChecked === true;
+ if (input.rightsConfirmed !== undefined) output.rightsConfirmed = input.rightsConfirmed === true;
+ return output;
+ }
+
+ validateProfile(input) {
+ const textFields = ['channelName', 'goal', 'targetAudience', 'brandVoice', 'defaultStyle', 'callToAction', 'visualStyle', 'timezone'];
+ const result = {};
+ for (const field of textFields) {
+ if (input[field] !== undefined) {
+ const value = String(input[field]).trim();
+ if (value.length > 500) throw new Error(`${field} is too long`);
+ result[field] = value;
+ }
+ }
+ if (input.bannedTopics !== undefined) {
+ const topics = Array.isArray(input.bannedTopics) ? input.bannedTopics : String(input.bannedTopics).split(',');
+ result.bannedTopics = topics.map(topic => String(topic).trim()).filter(Boolean).slice(0, 50);
+ }
+ return result;
+ }
+
+ decorateContentBundle(bundle) {
+ return {
+ ...bundle,
+ 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,
+ captions: bundle.assets?.captions?.path ? `/api/content/${bundle.id}/asset/captions` : null,
+ script: bundle.assets?.script?.originalPath ? `/api/content/${bundle.id}/asset/script` : null
+ }
+ };
+ }
+
+ async approveContent(productionId, input) {
+ const bundle = await this.db.getProductionBundle(productionId);
+ if (!bundle) {
+ const error = new Error('Content not found');
+ error.status = 404;
+ throw error;
+ }
+ if (bundle.schedule?.status === 'published') {
+ const error = new Error('Content is already published');
+ error.status = 409;
+ throw error;
+ }
+
+ const editorData = this.validateEditorData(input, bundle.editorData);
+ if (!editorData.factChecked || !editorData.rightsConfirmed) {
+ const error = new Error('Confirm the factual review and media rights checks before approval');
+ error.status = 409;
+ throw error;
+ }
+ const productionData = {
+ id: bundle.id,
+ status: bundle.status,
+ strategy: bundle.strategy,
+ script: { ...bundle.script, title: editorData.title || bundle.script.title },
+ thumbnail: bundle.thumbnail,
+ seo: {
+ ...bundle.seo,
+ title: editorData.title || bundle.seo.title,
+ description: editorData.description || bundle.seo.description,
+ tags: editorData.tags || bundle.seo.tags
+ },
+ assets: bundle.assets,
+ timeline: bundle.timeline,
+ scheduledPublishTime: editorData.publishTime || input.publishTime || bundle.scheduled_publish_time,
+ priority: bundle.priority,
+ estimatedDuration: bundle.estimated_duration,
+ privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'
+ };
+ const profile = await this.db.getChannelProfile() || {};
+ const quality = await this.operator.runQualityChecks(productionData, profile);
+ if (!quality.passed) {
+ await this.db.saveContentReview(bundle.id, {
+ status: 'needs_attention', editorData, qualityChecks: quality.checks,
+ reviewNotes: `Blocking checks failed: ${quality.blockingFailures.join(', ')}`
+ });
+ const error = new Error('Content still has blocking quality failures');
+ error.status = 409;
+ error.quality = quality;
+ throw error;
+ }
+
+ let scheduleEntry = bundle.schedule;
+ if (!scheduleEntry) {
+ scheduleEntry = await this.agents.publishing.scheduleContent(productionData);
+ } else if (scheduleEntry.status !== 'published') {
+ scheduleEntry.title = productionData.script.title;
+ scheduleEntry.publishTime = productionData.scheduledPublishTime;
+ scheduleEntry.status = 'scheduled';
+ scheduleEntry.metadata = {
+ ...scheduleEntry.metadata,
+ seo: productionData.seo,
+ thumbnail: productionData.assets.thumbnail,
+ video: productionData.assets.finalVideo,
+ captions: productionData.assets.captions,
+ privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'
+ };
+ await this.db.updateScheduleEntry(scheduleEntry);
+ await this.agents.publishing.loadPublishQueue();
+ }
+ if (!scheduleEntry) {
+ const error = new Error('A real MP4 is required before content can be approved for scheduling');
+ error.status = 409;
+ throw error;
+ }
+
+ await this.db.saveContentReview(bundle.id, {
+ status: 'approved', editorData, qualityChecks: quality.checks,
+ reviewNotes: input.reviewNotes || 'Approved by operator', reviewedAt: new Date().toISOString()
+ });
+ await this.db.updateProductionStatus(bundle.id, 'scheduled');
+ await this.operator.notify({
+ type: 'content_approved', level: 'success', title: 'Content approved',
+ message: `${productionData.script.title} is scheduled for ${scheduleEntry.publishTime}`,
+ data: { productionId, publishTime: scheduleEntry.publishTime }
+ });
+ return { productionId, reviewStatus: 'approved', qualityScore: quality.score, schedule: scheduleEntry };
+ }
+
async start() {
const initialized = await this.initialize();
@@ -332,7 +832,11 @@ class YouTubeAutomationAgent {
console.log(chalk.white('📅 Schedule: ') + chalk.cyan(`http://localhost:${PORT}/schedule`));
console.log(chalk.white('📈 Analytics: ') + chalk.cyan(`http://localhost:${PORT}/analytics`));
console.log(chalk.gray('─'.repeat(50)));
- console.log(chalk.yellow('\n🤖 Automation is active. Content will be generated and posted daily.'));
+ if (this.setupRequired) {
+ console.log(chalk.yellow('\n⚙️ Setup is required. The dashboard is available; run npm run walkthrough to enable generation.'));
+ } else {
+ console.log(chalk.yellow('\n🤖 Automation is active. Approved content will be published on schedule.'));
+ }
});
}
}
@@ -346,4 +850,4 @@ if (require.main === module) {
});
}
-module.exports = { YouTubeAutomationAgent };
\ No newline at end of file
+module.exports = { YouTubeAutomationAgent };
diff --git a/package-lock.json b/package-lock.json
index e1847a7..3db4727 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "youtube-automation-agent",
- "version": "2.4.2",
+ "version": "2.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "youtube-automation-agent",
- "version": "2.4.1",
+ "version": "2.5.0",
"dependencies": {
"@google-cloud/local-auth": "^3.0.0",
"@google/genai": "^2.9.0",
diff --git a/package.json b/package.json
index 3207a81..68d0f53 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "youtube-automation-agent",
- "version": "2.4.2",
+ "version": "2.5.0",
"description": "Fully automated YouTube channel management system with specialized AI agents",
"main": "index.js",
"scripts": {
diff --git a/schedules/daily-automation.js b/schedules/daily-automation.js
index f74fa0a..515294b 100644
--- a/schedules/daily-automation.js
+++ b/schedules/daily-automation.js
@@ -2,7 +2,7 @@ const cron = require('node-cron');
const { Logger } = require('../utils/logger');
class DailyAutomation {
- constructor(agents, database) {
+ constructor(agents, database, options = {}) {
this.agents = agents;
this.db = database;
this.logger = new Logger('DailyAutomation');
@@ -10,6 +10,7 @@ class DailyAutomation {
this.isEnabled = true;
this.healthCheckInterval = null;
this.lastHealthCheck = null;
+ this.generateContent = options.generateContent || null;
}
async initialize() {
@@ -100,6 +101,15 @@ class DailyAutomation {
return;
}
+ if (this.generateContent) {
+ const job = await this.generateContent({ source: 'scheduler' });
+ await this.db.setSetting('last_content_generation', new Date().toISOString());
+ timer.end();
+ this.logger.success(`Daily content generation queued: ${job.id}`);
+ await this.logAutomationEvent('daily_content_generation', 'queued', { jobId: job.id });
+ return;
+ }
+
// Generate content strategy
const strategy = await this.agents.strategy.generateContentStrategy();
this.logger.info(`Generated strategy: ${strategy.topic}`);
@@ -208,6 +218,7 @@ class DailyAutomation {
await this.logAutomationEvent('queue_processing', 'error', {
error: error.message
});
+ await this.sendFailureNotification('Publishing Queue', error);
}
}
@@ -246,6 +257,7 @@ class DailyAutomation {
await this.logAutomationEvent('analytics_collection', 'error', {
error: error.message
});
+ await this.sendFailureNotification('Analytics Collection', error);
}
}
@@ -418,7 +430,6 @@ class DailyAutomation {
async cleanupOldFiles() {
// Clean up temporary files older than 7 days
- const fs = require('fs').promises;
const path = require('path');
const tempDir = path.join(__dirname, '..', 'temp');
@@ -474,9 +485,14 @@ class DailyAutomation {
async sendFailureNotification(taskName, error) {
// This would integrate with notification services (email, Slack, etc.)
this.logger.error(`AUTOMATION FAILURE - ${taskName}: ${error.message}`);
-
- // Could send webhook notification, email, etc.
- // For now, just log it prominently
+ if (this.db.createNotification) {
+ await this.db.createNotification({
+ type: 'automation_failure',
+ level: 'error',
+ title: `${taskName} failed`,
+ message: error.message
+ });
+ }
}
startMonitoringLoop() {
@@ -589,4 +605,4 @@ class DailyAutomation {
}
}
-module.exports = { DailyAutomation };
\ No newline at end of file
+module.exports = { DailyAutomation };
diff --git a/setup.js b/setup.js
index 7fed741..85e0057 100644
--- a/setup.js
+++ b/setup.js
@@ -179,7 +179,6 @@ SCREENSHOT_PATH=./debug/screenshots
try {
// Check if package.json exists and dependencies are installed
- const packagePath = path.join(__dirname, 'package.json');
const nodeModulesPath = path.join(__dirname, 'node_modules');
try {
@@ -257,7 +256,7 @@ node index.js`;
// Check database
try {
- const stats = await this.database.getStats();
+ await this.database.getStats();
validation.database = true;
} catch (error) {
validation.database = false;
@@ -352,4 +351,4 @@ if (require.main === module) {
});
}
-module.exports = { YouTubeAutomationSetup };
\ No newline at end of file
+module.exports = { YouTubeAutomationSetup };
diff --git a/test.js b/test.js
index b6a3ae9..7e1923b 100644
--- a/test.js
+++ b/test.js
@@ -18,6 +18,7 @@ class SystemTest {
{ name: 'Database Connection', test: () => this.testDatabase() },
{ name: 'Production Persistence', test: () => this.testProductionPersistence() },
{ name: 'Automation Events Table', test: () => this.testAutomationEventsTable() },
+ { name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },
{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },
{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },
{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },
@@ -148,6 +149,65 @@ class SystemTest {
this.logger.info('Automation events table test completed successfully');
}
+ async testOperatorWorkflowAPI() {
+ const { YouTubeAutomationAgent } = require('./index');
+ const { OperatorService } = require('./utils/operator-service');
+ const db = new Database();
+ await db.initialize();
+ let server;
+ let job;
+
+ try {
+ job = await db.createGenerationJob({ topic: 'Operator workflow test', style: 'explainer', length: 'short' });
+ await db.updateGenerationJob(job.id, { status: 'running', stage: 'script', progress: 25 });
+ const updated = await db.getGenerationJob(job.id);
+ if (updated.stage !== 'script' || updated.progress !== 25) {
+ throw new Error('Generation job progress was not persisted');
+ }
+
+ const operator = new OperatorService(db);
+ const quality = await operator.runQualityChecks({
+ script: { title: 'Test title', fullScript: 'x'.repeat(250) },
+ seo: { title: 'Test title', description: 'x'.repeat(80), tags: ['one', 'two', 'three'] },
+ assets: { finalVideo: { path: 'placeholder.info', simulated: true } }
+ }, { bannedTopics: [] });
+ if (quality.passed || !quality.blockingFailures.includes('video')) {
+ throw new Error('Quality gate did not block a simulated video');
+ }
+
+ const agent = new YouTubeAutomationAgent();
+ agent.db = db;
+ agent.operator = operator;
+ agent.agents = {
+ analytics: {
+ getRecentAnalytics: async () => ({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] })
+ }
+ };
+ agent.scheduler = {
+ isEnabled: true,
+ pauseAutomation: async function() { this.isEnabled = false; },
+ resumeAutomation: async function() { this.isEnabled = true; }
+ };
+ agent.isInitialized = true;
+ agent.setupAPI();
+ server = await new Promise(resolve => {
+ const running = agent.app.listen(0, () => resolve(running));
+ });
+ const { port } = server.address();
+ const response = await fetch(`http://127.0.0.1:${port}/api/dashboard`);
+ const dashboard = await response.json();
+ if (!response.ok || !Array.isArray(dashboard.jobs) || !Array.isArray(dashboard.pipeline)) {
+ throw new Error('Operator dashboard API did not return its data contract');
+ }
+ } finally {
+ if (server) await new Promise(resolve => server.close(resolve));
+ if (job) await db.executeQuery('DELETE FROM generation_jobs WHERE id = ?', [job.id]);
+ await db.close();
+ }
+
+ this.logger.info('Operator workflow API test completed successfully');
+ }
+
async testAPIValidationAndSecurity() {
const { YouTubeAutomationAgent } = require('./index');
const agent = new YouTubeAutomationAgent();
@@ -713,4 +773,4 @@ if (require.main === module) {
});
}
-module.exports = { SystemTest };
\ No newline at end of file
+module.exports = { SystemTest };
diff --git a/utils/operator-service.js b/utils/operator-service.js
new file mode 100644
index 0000000..c7d9b91
--- /dev/null
+++ b/utils/operator-service.js
@@ -0,0 +1,107 @@
+const fs = require('fs').promises;
+const axios = require('axios');
+const { Logger } = require('./logger');
+
+class OperatorService {
+ constructor(db) {
+ this.db = db;
+ this.logger = new Logger('OperatorService');
+ }
+
+ async runQualityChecks(production, profile = {}) {
+ const title = String(production.seo?.title || production.script?.title || '').trim();
+ const description = String(production.seo?.description || '').trim();
+ const tags = Array.isArray(production.seo?.tags) ? production.seo.tags : [];
+ const script = String(production.script?.fullScript || '').trim();
+ const finalVideo = production.assets?.finalVideo;
+ const thumbnail = production.assets?.thumbnail;
+ const bannedTopics = Array.isArray(profile.bannedTopics) ? profile.bannedTopics : [];
+ const combinedText = `${title}\n${description}\n${script}`.toLowerCase();
+
+ const checks = [
+ this.check('title', title.length > 0 && title.length <= 100,
+ title ? `Title is ${title.length}/100 characters` : 'A title is required'),
+ this.check('description', description.length >= 50,
+ description.length >= 50 ? 'Description is detailed enough' : 'Description should be at least 50 characters'),
+ this.check('tags', tags.length >= 3,
+ tags.length >= 3 ? `${tags.length} tags provided` : 'Add at least 3 relevant tags', false),
+ this.check('script', script.length >= 200,
+ script.length >= 200 ? 'Script content is present' : 'Script is missing or unusually short'),
+ this.check('thumbnail', Boolean(thumbnail?.path),
+ thumbnail?.path ? 'Thumbnail asset is present' : 'Thumbnail asset is missing', false),
+ this.check('video', Boolean(finalVideo?.path && !finalVideo?.simulated),
+ finalVideo?.simulated ? 'Only a simulated video was produced' : 'Final MP4 is missing')
+ ];
+
+ const topic = String(production.strategy?.topic || '').trim();
+ if (topic) {
+ const duplicates = await this.db.getRow(
+ `SELECT COUNT(*) AS count FROM content_strategies
+ WHERE lower(trim(topic)) = lower(trim(?))
+ AND created_at >= datetime('now', '-90 days')`,
+ [topic]
+ );
+ const unique = Number(duplicates?.count || 0) <= 1;
+ checks.push(this.check('duplicate_topic', unique,
+ unique
+ ? 'No duplicate topic detected in the last 90 days'
+ : 'This exact topic was already generated recently', false));
+ }
+
+ if (finalVideo?.path && !finalVideo?.simulated) {
+ checks.push(this.check('video_file', await this.fileExists(finalVideo.path),
+ 'Final video file exists on disk'));
+ }
+
+ const matchedBannedTopics = bannedTopics.filter(topic =>
+ topic && combinedText.includes(String(topic).toLowerCase())
+ );
+ checks.push(this.check('brand_policy', matchedBannedTopics.length === 0,
+ matchedBannedTopics.length
+ ? `Content matches blocked terms: ${matchedBannedTopics.join(', ')}`
+ : 'No blocked brand topics detected'));
+
+ const blockingFailures = checks.filter(check => check.blocking && !check.passed);
+ return {
+ passed: blockingFailures.length === 0,
+ score: Math.round((checks.filter(check => check.passed).length / checks.length) * 100),
+ blockingFailures: blockingFailures.map(check => check.id),
+ checks
+ };
+ }
+
+ check(id, passed, message, blocking = true) {
+ return { id, passed: Boolean(passed), blocking, message };
+ }
+
+ async fileExists(filePath) {
+ try {
+ const stats = await fs.stat(filePath);
+ return stats.isFile() && stats.size > 0;
+ } catch (_error) {
+ return false;
+ }
+ }
+
+ async notify(notification) {
+ const enabled = await this.db.getSetting('notification_enabled');
+ if (enabled === 'false') return null;
+
+ const id = await this.db.createNotification(notification);
+ const webhookUrl = process.env.NOTIFICATION_WEBHOOK_URL;
+ if (webhookUrl) {
+ try {
+ await axios.post(webhookUrl, {
+ text: `${notification.title}: ${notification.message}`,
+ content: `${notification.title}: ${notification.message}`,
+ ...notification
+ }, { timeout: 5000 });
+ } catch (error) {
+ this.logger.warn(`Notification webhook failed: ${error.message}`);
+ }
+ }
+ return id;
+ }
+}
+
+module.exports = { OperatorService };