🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
Add closed-loop channel learning
darkzOGx0aea85173449
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c1fcfe5..13a86cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Added an approval-gated Channel Learning Engine that captures real 24-hour and 7-day performance snapshots, derives channel-relative baselines, and feeds only approved recommendations into future autonomous plans+- Added a dashboard learning review with evidence, confidence, approve/reject controls, and operator-selected title/thumbnail variants for approved packaging experiments; simulated analytics are explicitly excluded from learning- Added a persistent Autonomous Channel Operator that turns a channel objective, audience, pillars, cadence, and guardrails into researched editorial plans and sequential end-to-end production runs- Added dashboard strategy controls, operator-run progress and cancellation, scheduled strategy execution, and approval-gated publishing handoff- Added local-only activation milestones for setup, first real MP4, approval, publication, and repeat generationdiff --git a/README.md b/README.mdindex be8e6ae..329e505 100644--- a/README.md+++ b/README.md@@ -47,6 +47,14 @@ Lumen refreshes YouTube trend and configured-competitor signals, checks recent cBy default, finished videos wait for factual review, media-rights confirmation, and approval. Once approved, the existing publishing agent schedules and uploads them. Turning on autonomy does not bypass those gates, and simulated videos still cannot publish.+### Close the performance loop++After publication, Lumen captures comparable 24-hour and 7-day performance snapshots. It evaluates CTR, retention, engagement, watch time, format, length, hook style, and title style against the channel's own history—not a universal view-count target.++Open **Analytics → What the agent learned** to review the evidence and confidence behind each recommendation. Pending or rejected recommendations never influence generation. Once you approve one, the next Autonomous Channel Operator run includes it as an explicit planning constraint. Simulated analytics fallbacks are stored as unverified and are never eligible for baselines or recommendations.++When an approved learning calls for better packaging, Lumen prepares a control plus title and thumbnail variants for new videos. Review Studio shows those options before approval; the selected combination is the only one handed to the publishing queue. Lumen does not silently swap live YouTube metadata.+## From idea to published video| Stage | What Lumen does | What you control |@@ -56,7 +64,7 @@ By default, finished videos wait for factual review, media-rights confirmation,| Production | Generates narration and visuals, then assembles a real MP4 | Provider choice and media fallbacks || Review | Runs quality checks and opens the video in Review Studio | Facts, media rights, edits, approval || Publish | Schedules and uploads approved content | Privacy, timing, final decision |-| Learn | Pulls performance signals into the next strategy cycle | Automation and optimization settings |+| Learn | Captures 24-hour and 7-day evidence, then proposes the next move | Approve or reject each learning before it guides planning |Lumen distinguishes real MP4 output from simulated placeholders. Simulated output cannot enter the approval or publishing path.@@ -221,6 +229,8 @@ The scheduler runs automatically after `npm start`. Content generation at 06:00,When an active channel strategy exists, the 06:00 generation check uses its cadence and launches an autonomous research-and-production run when the content buffer needs work. Without an active strategy, the original topic-selection flow remains in place.+Daily analytics collection backfills each real publication's 24-hour and 7-day evidence windows. Recommendations require at least two real measurements, and format or style comparisons require at least two videos in each compared group.+## API```bash@@ -254,6 +264,10 @@ curl http://localhost:3456/schedule# get analyticscurl http://localhost:3456/analytics+# approve an evidence-backed learning for future autonomous plans+curl -X POST http://localhost:3456/api/learning/recommendations/:recommendationId/approve \+ -H "x-api-key: $API_KEY"+# inspect, edit, and approve content before schedulingcurl http://localhost:3456/api/content/:contentIdcurl -X POST http://localhost:3456/api/content/:contentId/approve \diff --git a/agents/analytics-optimization-agent.js b/agents/analytics-optimization-agent.jsindex d1726a9..7950707 100644--- a/agents/analytics-optimization-agent.js+++ b/agents/analytics-optimization-agent.js@@ -1,5 +1,6 @@const { google } = require('googleapis');const { Logger } = require('../utils/logger');+const { ChannelLearningEngine } = require('../utils/channel-learning-engine');class AnalyticsOptimizationAgent {constructor(db, credentials) {@@ -9,6 +10,7 @@ class AnalyticsOptimizationAgent {this.youtubeAnalytics = null;this.youtube = null;this.performanceData = new Map();+ this.learning = new ChannelLearningEngine(db);}async initialize() {@@ -51,18 +53,21 @@ class AnalyticsOptimizationAgent {}}- async analyzeVideoPerformance(videoId) {+ async analyzeVideoPerformance(videoId, options = {}) {try {this.logger.info(`Analyzing performance for video: ${videoId}`);// Get video detailsconst videoDetails = await this.getVideoDetails(videoId);+ const measurementWindow = options.measurementWindow || 'rolling';+ const period = this.learning.measurementPeriod(videoDetails.publishedAt, measurementWindow);+// Get analytics data- const analytics = await this.getVideoAnalytics(videoId);+ const analytics = await this.getVideoAnalytics(videoId, period);// Analyze thumbnail performance- const thumbnailMetrics = await this.analyzeThumbnailPerformance(videoId);+ const thumbnailMetrics = await this.analyzeThumbnailPerformance(videoId, period);// Analyze title and SEO performanceconst seoMetrics = await this.analyzeSEOPerformance(videoDetails, analytics);@@ -78,6 +83,7 @@ class AnalyticsOptimizationAgent {seoMetrics,insights,performance: this.calculatePerformanceScore(analytics),+ measurementWindow,analyzedAt: new Date().toISOString()};@@ -86,6 +92,12 @@ class AnalyticsOptimizationAgent {// Save to databaseawait this.db.saveAnalyticsReport(performanceReport);+ const context = await this.db.getPublishedContentContext(videoId);+ performanceReport.learningSnapshot = await this.learning.capture(+ performanceReport,+ context,+ measurementWindow+ );this.logger.info(`Analysis complete. Performance score: ${performanceReport.performance.score}/100`);return performanceReport;@@ -121,9 +133,9 @@ class AnalyticsOptimizationAgent {};}- async getVideoAnalytics(videoId) {- const endDate = new Date().toISOString().split('T')[0];- const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];+ async getVideoAnalytics(videoId, period = null) {+ const endDate = period?.endDate || new Date().toISOString().split('T')[0];+ const startDate = period?.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];try {// Get various analytics metrics@@ -142,6 +154,7 @@ class AnalyticsOptimizationAgent {]);return {+ simulated: false,period: { startDate, endDate },views: viewsData,watchTime: watchTimeData,@@ -291,13 +304,13 @@ class AnalyticsOptimizationAgent {};}- async analyzeThumbnailPerformance(videoId) {+ async analyzeThumbnailPerformance(videoId, period = null) {// Analyze thumbnail click-through rate and impressionstry {const response = await this.youtubeAnalytics.reports.query({ids: 'channel==MINE',- startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],- endDate: new Date().toISOString().split('T')[0],+ startDate: period?.startDate || new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],+ endDate: period?.endDate || new Date().toISOString().split('T')[0],metrics: 'impressions,impressionClickThroughRate',filters: `video==${videoId}`});@@ -632,6 +645,7 @@ class AnalyticsOptimizationAgent {// Simulation methods for when API is not availablegetSimulatedAnalytics(_videoId) {return {+ simulated: true,views: { totalViews: Math.floor(Math.random() * 50000), averageCTR: Math.random() * 10 },watchTime: { averageViewPercentage: Math.random() * 100 },engagement: { engagementRate: Math.random() * 10 },@@ -687,6 +701,14 @@ class AnalyticsOptimizationAgent {};}+ getLearningSummary() {+ return this.learning.getSummary();+ }++ getDueMeasurementWindows(video) {+ return this.learning.getDueMeasurementWindows(video);+ }+calculateAverageScore(reports) {if (!reports.length) return 0;const total = reports.reduce((sum, report) => sum + report.performance.score, 0);diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.jsindex 0834c46..f45abc2 100644--- a/agents/content-strategy-agent.js+++ b/agents/content-strategy-agent.js@@ -263,6 +263,9 @@ class ContentStrategyAgent {const recentRows = await this.db.getAllRows("SELECT topic, created_at FROM content_strategies WHERE created_at >= datetime('now', '-90 days') ORDER BY created_at DESC LIMIT 50");+ const approvedLearnings = this.db.listLearningRecommendations+ ? await this.db.listLearningRecommendations({ status: 'approved', limit: 10 })+ : [];const signals = this.trendingTopics.slice(0, 15).map(item => ({topic: item.topic,score: Number(item.score || 0),@@ -272,14 +275,21 @@ class ContentStrategyAgent {const researchSources = [...(signalSources.has('trending') ? ['YouTube most-popular videos'] : []),...(signalSources.has('competitor') ? ['Configured competitor channels'] : []),- ...(recentRows.length ? ['Channel content history'] : [])+ ...(recentRows.length ? ['Channel content history'] : []),+ ...(approvedLearnings.length ? ['Operator-approved channel performance learnings'] : [])];const research = {generatedAt: new Date().toISOString(),sources: researchSources.length ? researchSources : ['No usable live signals returned; evergreen strategy fallback'],signals,recentTopics: recentRows.map(row => row.topic),- competitorChannelsAnalyzed: this.competitorData.length+ competitorChannelsAnalyzed: this.competitorData.length,+ approvedLearnings: approvedLearnings.map(item => ({+ title: item.title,+ rationale: item.rationale,+ confidence: item.confidence,+ proposedChange: item.proposedChange+ }))};let plan = await this.generateAutonomousPlanWithAI(channelStrategy, research, targetCount);@@ -309,8 +319,9 @@ Success metric: ${channelStrategy.success_metric || 'not specified'}Constraints: ${channelStrategy.constraints || 'none'}Research signals: ${JSON.stringify(research.signals)}Recent topics to avoid repeating: ${JSON.stringify(research.recentTopics)}+Operator-approved performance learnings to apply: ${JSON.stringify(research.approvedLearnings)}-Do not invent trend data, statistics, sources, or factual claims. Prefer evergreen topics when the supplied signals are weak.`;+Do not invent trend data, statistics, sources, or factual claims. Apply only the supplied approved learnings; pending or rejected recommendations are not authorized. Prefer evergreen topics when the supplied signals are weak.`;try {const response = await this.aiTextService.generateText(prompt, { maxTokens: 1800, temperature: 0.65 });@@ -336,7 +347,9 @@ Do not invent trend data, statistics, sources, or factual claims. Prefer evergreangle: `${topic} through the lens of ${channelStrategy.value_proposition || channelStrategy.objective}`,rationale: readableSignals.includes(topic)? 'Matches a current YouTube or configured competitor signal and fits the channel strategy.'- : 'Builds an evergreen topic from the channel strategy when live research signals are limited.',+ : research.approvedLearnings.length+ ? `Builds an evergreen topic from the channel strategy while applying approved learning: ${research.approvedLearnings[0].title}.`+ : 'Builds an evergreen topic from the channel strategy when live research signals are limited.',format: index === 0 ? channelStrategy.default_format : ['explainer', 'tutorial', 'list'][index % 3],length: channelStrategy.default_length}));diff --git a/agents/thumbnail-designer-agent.js b/agents/thumbnail-designer-agent.jsindex 271288d..b67019f 100644--- a/agents/thumbnail-designer-agent.js+++ b/agents/thumbnail-designer-agent.js@@ -203,12 +203,13 @@ class ThumbnailDesignerAgent {return prompt;}- async createThumbnail(concept) {+ async createThumbnail(concept, suffix = '') {// Create a base thumbnail using Sharpconst width = 1280;const height = 720;- const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_${Date.now()}.png`);+ const marker = suffix ? `_${suffix}` : '';+ const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail${marker}_${Date.now()}.png`);// Create gradient backgroundconst svg = `@@ -250,8 +251,9 @@ class ThumbnailDesignerAgent {return colors[color] || '#000000';}- async addTextOverlay(imagePath, concept) {- const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_final_${Date.now()}.png`);+ async addTextOverlay(imagePath, concept, suffix = '') {+ const marker = suffix ? `_${suffix}` : '';+ const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_final${marker}_${Date.now()}.png`);// Create text overlay SVGconst textSvg = `@@ -300,8 +302,9 @@ class ThumbnailDesignerAgent {return outputPath;}- async optimizeForYouTube(imagePath) {- const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_optimized_${Date.now()}.jpg`);+ async optimizeForYouTube(imagePath, suffix = '') {+ const marker = suffix ? `_${suffix}` : '';+ const outputPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_optimized${marker}_${Date.now()}.jpg`);// YouTube optimization: JPEG format, proper compressionawait sharp(imagePath)@@ -335,28 +338,36 @@ class ThumbnailDesignerAgent {}async generateABVariants(concept) {- // Generate multiple thumbnail variants for A/B testing+ const concepts = [+ {+ label: 'Color contrast',+ concept: {+ ...concept,+ colors: {+ primary: concept.colors.secondary,+ secondary: concept.colors.primary,+ accent: concept.colors.accent+ }+ }+ },+ {+ label: 'Alternate promise',+ concept: { ...concept, primaryText: this.generateAlternativeText(concept.primaryText) }+ },+ {+ label: 'Centered composition',+ concept: { ...concept, composition: 'centered' }+ }+ ];const variants = [];-- // Variant 1: Different color scheme- const variant1 = { ...concept };- variant1.colors = {- primary: concept.colors.secondary,- secondary: concept.colors.primary,- accent: concept.colors.accent- };- variants.push(await this.createThumbnail(variant1));-- // Variant 2: Different text- const variant2 = { ...concept };- variant2.primaryText = this.generateAlternativeText(concept.primaryText);- variants.push(await this.createThumbnail(variant2));-- // Variant 3: Different composition- const variant3 = { ...concept };- variant3.composition = 'centered';- variants.push(await this.createThumbnail(variant3));-+ for (let index = 0; index < concepts.length; index++) {+ const { label, concept: variantConcept } = concepts[index];+ const suffix = `experiment_${index + 1}`;+ const base = await this.createThumbnail(variantConcept, suffix);+ const overlay = await this.addTextOverlay(base, variantConcept, suffix);+ const optimized = await this.optimizeForYouTube(overlay, suffix);+ variants.push({ label, path: optimized, concept: variantConcept });+ }return variants;}@@ -373,4 +384,4 @@ class ThumbnailDesignerAgent {}}-module.exports = { ThumbnailDesignerAgent };\ No newline at end of file+module.exports = { ThumbnailDesignerAgent };diff --git a/dashboard/app.js b/dashboard/app.jsindex 9fd5e9f..8996db1 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -135,7 +135,7 @@ function renderDashboard() {renderPipeline(state.pipeline);renderCalendar(state.schedule);renderIdeas(state.ideas);- renderAnalytics(state.analytics);+ renderAnalytics(state.analytics, state.learning);renderActivation(state.activation);renderOperator(state.channelStrategy, state.operatorRuns || [], state.system);populateSettings(state.profile, state.settings);@@ -255,16 +255,46 @@ function renderIdeas(ideas) {</article>`).join('');}-function renderAnalytics(analytics) {+function renderAnalytics(analytics, learning = {}) {$('#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+ const approved = (learning.recommendations || []).find(item => item.status === 'approved');+ const pending = (learning.recommendations || []).find(item => item.status === 'pending');+ $('#analytics-action').textContent = approved?.title || pending?.title || 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.');+ renderLearning(learning);+}++function renderLearning(learning = {}) {+ const baseline = learning.baseline || {};+ $('#learning-snapshot-count').textContent = `${learning.snapshotCount || 0} snapshots`;+ $('#learning-approved-count').textContent = `${learning.approvedCount || 0} approved`;+ const metrics = [+ ['CTR', baseline.ctr, '%'],+ ['Retention', baseline.retention, '%'],+ ['Engagement', baseline.engagementRate, '%'],+ ['Performance', baseline.performanceScore, '/100']+ ];+ $('#learning-baseline').innerHTML = learning.measuredVideos ? metrics.map(([name, value, suffix]) => `+ <div><span>${escapeHTML(name)}</span><strong>${Number(value || 0).toFixed(1)}${escapeHTML(suffix)}</strong></div>`).join('') : empty('Two real measurements unlock evidence-backed recommendations.');++ const recommendations = Array.isArray(learning.recommendations) ? learning.recommendations : [];+ $('#learning-recommendations').innerHTML = recommendations.length ? recommendations.map(item => `+ <article class="learning-card">+ <div class="learning-card-heading"><strong>${escapeHTML(item.title)}</strong>${statusChip(item.status)}</div>+ <p>${escapeHTML(item.rationale)}</p>+ <div class="learning-meta"><span>${escapeHTML(label(item.category))} · ${escapeHTML(label(item.confidence))} confidence</span>+ <span class="learning-actions">+ ${item.status !== 'approved' ? `<button class="text-button approve" data-learning-action="approve" data-learning-id="${escapeHTML(item.id)}">Approve</button>` : ''}+ ${item.status !== 'rejected' ? `<button class="text-button" data-learning-action="reject" data-learning-id="${escapeHTML(item.id)}">Reject</button>` : ''}+ </span>+ </div>+ </article>`).join('') : empty('No recommendation yet. Lumen needs at least two real, sufficiently exposed measurements.');}function renderActivation(activation = {}) {@@ -396,6 +426,9 @@ async function openContent(productionId) {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);+ const experiment = data.packagingExperiment;+ const selectedTitleVariant = Number(data.selectedTitleVariant || 0);+ const selectedThumbnailVariant = Number(data.selectedThumbnailVariant || 0);$('#content-detail').innerHTML = `<div class="dialog-heading"><div><p class="eyebrow">CONTENT REVIEW</p><h2>${escapeHTML(title)}</h2><div class="meta-line">${statusChip(item.schedule?.status || item.review_status || item.status)} · Quality ${qualityScore(item.qualityChecks)}%</div></div><button type="button" class="close-button" data-close>×</button></div><div class="content-layout">@@ -408,6 +441,11 @@ async function openContent(productionId) {<label><span>Title</span><input name="title" maxlength="100" value="${escapeHTML(title)}" required></label><label><span>Description</span><textarea name="description" rows="7">${escapeHTML(description)}</textarea></label><label><span>Tags</span><input name="tags" value="${escapeHTML(tags.join(', '))}"></label>+ ${experiment ? `<section class="experiment-panel">+ <div><p class="eyebrow">APPROVED LEARNING EXPERIMENT</p><strong>${escapeHTML(experiment.hypothesis)}</strong><p>Choose the packaging to ship. Nothing changes on YouTube until this content is approved and published.</p></div>+ <label><span>Title variant</span><select name="selectedTitleVariant">${experiment.titleVariants.map((variant, index) => `<option value="${index}" data-title="${escapeHTML(variant.title)}" ${index === selectedTitleVariant ? 'selected' : ''}>${escapeHTML(variant.label)} — ${escapeHTML(variant.title)}</option>`).join('')}</select></label>+ <div class="experiment-thumbnails">${experiment.thumbnailVariants.map((variant, index) => `<label class="experiment-thumb ${index === selectedThumbnailVariant ? 'selected' : ''}"><input type="radio" name="selectedThumbnailVariant" value="${index}" ${index === selectedThumbnailVariant ? 'checked' : ''}><img src="${escapeHTML(item.assetUrls.experimentThumbnails?.[index] || '')}" alt="${escapeHTML(variant.label)} thumbnail variant"><span>${escapeHTML(variant.label)}</span></label>`).join('')}</div>+ </section>` : ''}<div 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>@@ -444,6 +482,8 @@ function contentFormData() {tags: values.tags,publishTime: values.publishTime ? new Date(values.publishTime).toISOString() : undefined,privacyStatus: values.privacyStatus,+ selectedTitleVariant: values.selectedTitleVariant,+ selectedThumbnailVariant: values.selectedThumbnailVariant,factChecked: form.elements.factChecked?.checked || false,rightsConfirmed: form.elements.rightsConfirmed?.checked || false};@@ -485,6 +525,16 @@ document.addEventListener('click', async event => {await mutate(`/api/ideas/${encodeURIComponent(idea.dataset.generateIdea)}/generate`, 'POST', { length: 'medium' }, 'Idea queued for generation.').catch(() => {});}+ const learning = event.target.closest('[data-learning-action]');+ if (learning) {+ const action = learning.dataset.learningAction;+ const id = learning.dataset.learningId;+ const message = action === 'approve'+ ? 'Learning approved for future autonomous plans.'+ : 'Learning rejected and excluded from future plans.';+ await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});+ }+const save = event.target.closest('[data-save-content]');if (save) {await mutate(`/api/content/${encodeURIComponent(save.dataset.saveContent)}`, 'PATCH', contentFormData(), 'Draft saved.').catch(() => {});@@ -514,6 +564,14 @@ document.addEventListener('click', async event => {}});+document.addEventListener('change', event => {+ if (event.target.matches('[name="selectedTitleVariant"]')) {+ const title = event.target.selectedOptions[0]?.dataset.title;+ const input = $('#content-review-form [name="title"]');+ if (title && input) input.value = title;+ }+});+$('#generate-button').addEventListener('click', () => $('#generate-dialog').showModal());$('#add-idea-button').addEventListener('click', () => $('#idea-dialog').showModal());$('#refresh-button').addEventListener('click', () => refreshDashboard());diff --git a/dashboard/index.html b/dashboard/index.htmlindex e417012..53da82f 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -128,6 +128,17 @@<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>+ <div class="learning-grid">+ <article class="panel">+ <div class="panel-heading"><div><p class="eyebrow">CHANNEL BASELINE</p><h2>What real results say</h2></div><span id="learning-snapshot-count" class="status">0 snapshots</span></div>+ <div id="learning-baseline" class="baseline-grid"></div>+ <p class="callout">Only real YouTube analytics enter this evidence layer. Simulated fallback data is excluded.</p>+ </article>+ <article class="panel">+ <div class="panel-heading"><div><p class="eyebrow">WHAT THE AGENT LEARNED</p><h2>Review recommendations</h2></div><span id="learning-approved-count" class="status">0 approved</span></div>+ <div id="learning-recommendations" class="learning-list"></div>+ </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><article class="panel activation-panel"><div class="panel-heading"><div><p class="eyebrow">LOCAL ACTIVATION</p><h2>First-run journey</h2></div></div><p class="callout">Calculated locally from your database and video files. Nothing is transmitted unless anonymous telemetry is explicitly enabled.</p><div id="activation-list" class="timeline"></div></article></section>diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 4a9aa31..83b9f43 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -121,6 +121,20 @@ input:focus, textarea:focus, select:focus { border-color: #636d7c; box-shadow: 0.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; }+.learning-grid { display: grid; grid-template-columns: minmax(300px, .8fr) minmax(0, 1.2fr); gap: 18px; margin-bottom: 18px; }+.baseline-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px; }+.baseline-grid > div { border: 1px solid var(--line); border-radius: 10px; padding: 13px; background: rgba(255,255,255,.018); }+.baseline-grid span, .baseline-grid strong { display: block; }+.baseline-grid span { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .07em; }+.baseline-grid strong { font-size: 22px; margin-top: 5px; }+.baseline-grid .empty { grid-column: 1 / -1; }+.learning-list { display: grid; gap: 10px; }+.learning-card { border: 1px solid var(--line); border-radius: 12px; padding: 14px; background: rgba(255,255,255,.018); }+.learning-card-heading, .learning-meta { display: flex; align-items: center; justify-content: space-between; gap: 14px; }+.learning-card p { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 8px 0 12px; }+.learning-meta { color: var(--muted); font-size: 11px; }+.learning-actions { display: flex; gap: 12px; }+.text-button.approve { color: var(--green); }.settings-form { max-width: 920px; }.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }.form-grid.two { grid-template-columns: 1fr 1fr; }@@ -148,6 +162,14 @@ label small { color: var(--muted); font-weight: 400; }.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; }+.experiment-panel { display: grid; gap: 14px; border: 1px solid rgba(114,165,255,.28); background: rgba(114,165,255,.06); border-radius: 12px; padding: 14px; }+.experiment-panel p { color: var(--muted); font-size: 12px; line-height: 1.45; margin: 6px 0 0; }+.experiment-thumbnails { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }+.experiment-thumb { cursor: pointer; border: 1px solid var(--line); background: #0d1015; border-radius: 9px; padding: 7px; }+.experiment-thumb:has(input:checked) { border-color: var(--blue); box-shadow: 0 0 0 2px rgba(114,165,255,.12); }+.experiment-thumb input { width: auto; position: absolute; opacity: 0; }+.experiment-thumb img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 6px; background: #080a0d; }+.experiment-thumb span { display: block; color: var(--text); font-size: 11px; margin-top: 6px; text-align: center; }.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); }@@ -168,7 +190,7 @@ label small { color: var(--muted); font-weight: 400; }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, .operator-grid { grid-template-columns: 1fr; }+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid { grid-template-columns: 1fr; }.pipeline-item { grid-template-columns: 1fr auto; }.pipeline-col { display: none; }}diff --git a/database/db.js b/database/db.jsindex 7106426..da1cf7a 100644--- a/database/db.js+++ b/database/db.js@@ -146,6 +146,37 @@ class Database {performance_grade TEXT,analyzed_at TEXT DEFAULT CURRENT_TIMESTAMP)`,++ // Evidence-backed channel learning+ `CREATE TABLE IF NOT EXISTS performance_snapshots (+ id TEXT PRIMARY KEY,+ video_id TEXT NOT NULL,+ production_id TEXT,+ measurement_window TEXT NOT NULL,+ published_at TEXT,+ metrics TEXT NOT NULL,+ content_attributes TEXT NOT NULL,+ baseline TEXT,+ deltas TEXT,+ confidence TEXT DEFAULT 'low',+ simulated INTEGER DEFAULT 0,+ measured_at TEXT DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(video_id, measurement_window)+ )`,+ `CREATE TABLE IF NOT EXISTS learning_recommendations (+ id TEXT PRIMARY KEY,+ fingerprint TEXT NOT NULL UNIQUE,+ category TEXT NOT NULL,+ title TEXT NOT NULL,+ rationale TEXT NOT NULL,+ evidence TEXT NOT NULL,+ proposed_change TEXT NOT NULL,+ confidence TEXT DEFAULT 'low',+ status TEXT DEFAULT 'pending',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ reviewed_at TEXT+ )`,// Keywords Performance`CREATE TABLE IF NOT EXISTS keyword_performance (@@ -985,6 +1016,194 @@ class Database {}));}+ async savePerformanceSnapshot(snapshot) {+ const existing = await this.getRow(+ 'SELECT id FROM performance_snapshots WHERE video_id = ? AND measurement_window = ?',+ [snapshot.videoId, snapshot.measurementWindow]+ );+ const id = existing?.id || this.generateId('snapshot');+ await this.executeQuery(+ `INSERT INTO performance_snapshots (+ id, video_id, production_id, measurement_window, published_at, metrics,+ content_attributes, baseline, deltas, confidence, simulated, measured_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(video_id, measurement_window) DO UPDATE SET+ production_id = excluded.production_id,+ published_at = excluded.published_at,+ metrics = excluded.metrics,+ content_attributes = excluded.content_attributes,+ baseline = excluded.baseline,+ deltas = excluded.deltas,+ confidence = excluded.confidence,+ simulated = excluded.simulated,+ measured_at = excluded.measured_at`,+ [+ id,+ snapshot.videoId,+ snapshot.productionId || null,+ snapshot.measurementWindow,+ snapshot.publishedAt || null,+ JSON.stringify(snapshot.metrics || {}),+ JSON.stringify(snapshot.contentAttributes || {}),+ JSON.stringify(snapshot.baseline || {}),+ JSON.stringify(snapshot.deltas || {}),+ snapshot.confidence || 'low',+ snapshot.simulated ? 1 : 0,+ snapshot.measuredAt || new Date().toISOString()+ ]+ );+ return this.getPerformanceSnapshot(id);+ }++ async getPerformanceSnapshot(id) {+ const row = await this.getRow('SELECT * FROM performance_snapshots WHERE id = ?', [id]);+ return this.parsePerformanceSnapshot(row);+ }++ async listPerformanceSnapshots(options = {}) {+ const conditions = [];+ const params = [];+ if (options.videoId) {+ conditions.push('video_id = ?');+ params.push(options.videoId);+ }+ if (options.excludeVideoId) {+ conditions.push('video_id != ?');+ params.push(options.excludeVideoId);+ }+ if (options.measurementWindow) {+ conditions.push('measurement_window = ?');+ params.push(options.measurementWindow);+ }+ if (options.reliableOnly) conditions.push('simulated = 0');+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';+ const rows = await this.getAllRows(+ `SELECT * FROM performance_snapshots ${where} ORDER BY measured_at DESC`,+ params+ );+ return rows.map(row => this.parsePerformanceSnapshot(row));+ }++ parsePerformanceSnapshot(row) {+ if (!row) return null;+ return {+ ...row,+ videoId: row.video_id,+ productionId: row.production_id,+ measurementWindow: row.measurement_window,+ publishedAt: row.published_at,+ measuredAt: row.measured_at,+ simulated: Boolean(row.simulated),+ metrics: JSON.parse(row.metrics || '{}'),+ contentAttributes: JSON.parse(row.content_attributes || '{}'),+ baseline: JSON.parse(row.baseline || '{}'),+ deltas: JSON.parse(row.deltas || '{}')+ };+ }++ async saveLearningRecommendation(recommendation) {+ const existing = await this.getRow(+ 'SELECT id FROM learning_recommendations WHERE fingerprint = ?',+ [recommendation.fingerprint]+ );+ const id = existing?.id || this.generateId('learning');+ await this.executeQuery(+ `INSERT INTO learning_recommendations (+ id, fingerprint, category, title, rationale, evidence, proposed_change, confidence+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(fingerprint) DO UPDATE SET+ category = excluded.category,+ title = excluded.title,+ rationale = excluded.rationale,+ evidence = excluded.evidence,+ proposed_change = excluded.proposed_change,+ confidence = excluded.confidence,+ updated_at = CURRENT_TIMESTAMP`,+ [+ id,+ recommendation.fingerprint,+ recommendation.category,+ recommendation.title,+ recommendation.rationale,+ JSON.stringify(recommendation.evidence || {}),+ JSON.stringify(recommendation.proposedChange || {}),+ recommendation.confidence || 'low'+ ]+ );+ return this.getLearningRecommendation(id);+ }++ async getLearningRecommendation(id) {+ const row = await this.getRow('SELECT * FROM learning_recommendations WHERE id = ?', [id]);+ return this.parseLearningRecommendation(row);+ }++ async listLearningRecommendations(options = {}) {+ const conditions = [];+ const params = [];+ if (options.status) {+ conditions.push('status = ?');+ params.push(options.status);+ }+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';+ const limit = Math.max(1, Math.min(100, Number(options.limit || 25)));+ const rows = await this.getAllRows(+ `SELECT * FROM learning_recommendations ${where}+ ORDER BY CASE status WHEN 'pending' THEN 0 WHEN 'approved' THEN 1 ELSE 2 END,+ updated_at DESC LIMIT ?`,+ [...params, limit]+ );+ return rows.map(row => this.parseLearningRecommendation(row));+ }++ async reviewLearningRecommendation(id, status) {+ if (!['approved', 'rejected'].includes(status)) return null;+ await this.executeQuery(+ `UPDATE learning_recommendations+ SET status = ?, reviewed_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP+ WHERE id = ?`,+ [status, id]+ );+ return this.getLearningRecommendation(id);+ }++ parseLearningRecommendation(row) {+ if (!row) return null;+ return {+ ...row,+ proposedChange: JSON.parse(row.proposed_change || '{}'),+ evidence: JSON.parse(row.evidence || '{}'),+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ reviewedAt: row.reviewed_at+ };+ }++ async getPublishedContentContext(youtubeId) {+ const row = await this.getRow(+ `SELECT sch.production_id, sch.published_at, sch.title, ps.strategy, ps.script, ps.thumbnail, ps.seo,+ cr.editor_data+ FROM publish_schedule sch+ LEFT JOIN production_snapshots ps ON ps.production_id = sch.production_id+ LEFT JOIN content_reviews cr ON cr.production_id = sch.production_id+ WHERE sch.youtube_id = ? ORDER BY sch.published_at DESC LIMIT 1`,+ [youtubeId]+ );+ if (!row) return {};+ const editorData = JSON.parse(row.editor_data || '{}');+ const thumbnail = JSON.parse(row.thumbnail || '{}');+ const selectedThumbnail = editorData.packagingExperiment?.thumbnailVariants?.[editorData.selectedThumbnailVariant];+ return {+ productionId: row.production_id,+ publishedAt: row.published_at,+ title: editorData.title || row.title,+ strategy: JSON.parse(row.strategy || '{}'),+ script: JSON.parse(row.script || '{}'),+ thumbnail: selectedThumbnail?.concept ? { ...thumbnail, concept: selectedThumbnail.concept } : thumbnail,+ seo: JSON.parse(row.seo || '{}')+ };+ }+// Keyword performanceasync updateKeywordPerformance(keyword, views, videoId) {const existing = await this.getRow(diff --git a/index.js b/index.jsindex 2c623f6..347dd73 100644--- a/index.js+++ b/index.js@@ -354,9 +354,10 @@ class YouTubeAutomationAgent {// Get analyticsthis.app.get('/analytics', async (req, res) => {try {- if (!this.agents.analytics) return res.json({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] });+ if (!this.agents.analytics) return res.json({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [], learning: null });const analytics = await this.agents.analytics.getRecentAnalytics();- res.json(analytics);+ const learning = await this.agents.analytics.getLearningSummary();+ res.json({ ...analytics, learning });} catch (error) {res.status(500).json({ error: error.message });}@@ -396,7 +397,7 @@ class YouTubeAutomationAgent {this.app.get('/api/dashboard', async (_req, res) => {try {- const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, activation, channelStrategy, operatorRuns] = await Promise.all([+ const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation, channelStrategy, operatorRuns] = await Promise.all([this.db.getStats(),this.db.listGenerationJobs(20),this.db.getPipelineOverview(50),@@ -409,6 +410,9 @@ class YouTubeAutomationAgent {this.agents.analytics? this.agents.analytics.getRecentAnalytics(30): Promise.resolve({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] }),+ this.agents.analytics?.getLearningSummary+ ? this.agents.analytics.getLearningSummary()+ : Promise.resolve({ measuredVideos: 0, snapshotCount: 0, baseline: {}, recommendations: [], approvedCount: 0, pendingCount: 0 }),this.activation? this.activation.getSummary(): Promise.resolve({ privacy: 'local-only', counts: {}, milestones: {} }),@@ -417,7 +421,7 @@ class YouTubeAutomationAgent {]);if (this.telemetry) void this.telemetry.sync(activation);res.json({- stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, activation,+ stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation,channelStrategy, operatorRuns,system: {initialized: this.isInitialized,@@ -522,11 +526,18 @@ class YouTubeAutomationAgent {captions: bundle.assets?.captions?.path,script: bundle.assets?.script?.originalPath};- const filePath = allowed[req.params.kind];+ const experimentMatch = req.params.kind.match(/^experiment-thumbnail-(\d+)$/);+ const experimentPath = experimentMatch+ ? bundle.editorData?.packagingExperiment?.thumbnailVariants?.[Number(experimentMatch[1])]?.path+ : null;+ const filePath = allowed[req.params.kind] || experimentPath;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' });+ const experimentRoot = path.resolve(__dirname, 'uploads', 'thumbnails');+ const allowedPath = [dataRoot, experimentRoot]+ .some(root => resolved.startsWith(`${root}${path.sep}`));+ if (!allowedPath) return res.status(403).json({ error: 'Asset path is not allowed' });await fs.access(resolved);return res.sendFile(resolved);} catch (_error) {@@ -586,6 +597,24 @@ class YouTubeAutomationAgent {return res.json({ success: true, result: run });});+ this.app.post('/api/learning/recommendations/:recommendationId/:action', protect, async (req, res) => {+ const { recommendationId, action } = req.params;+ if (!['approve', 'reject'].includes(action)) {+ return res.status(400).json({ error: 'Action must be approve or reject' });+ }+ const status = action === 'approve' ? 'approved' : 'rejected';+ const recommendation = await this.db.reviewLearningRecommendation(recommendationId, status);+ if (!recommendation) return res.status(404).json({ error: 'Learning recommendation not found' });+ await this.operator.notify({+ type: 'learning_recommendation_reviewed',+ level: action === 'approve' ? 'success' : 'info',+ title: action === 'approve' ? 'Channel learning approved' : 'Channel learning rejected',+ message: recommendation.title,+ data: { recommendationId, status }+ });+ return res.json({ success: true, result: recommendation });+ });+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' });@@ -793,6 +822,11 @@ class YouTubeAutomationAgent {});this.logger.info('Production processing complete');+ const approvalRequired = await this.db.getSetting('approval_required') !== 'false';+ const packagingExperiment = approvalRequired+ ? await this.preparePackagingExperiment(thumbnail, productionData, seoData, script)+ : null;+// Step 6: Save to databaseconst contentId = await this.db.saveProductionData(productionData);await this.db.saveProductionSnapshot(productionData);@@ -801,14 +835,17 @@ class YouTubeAutomationAgent {// Step 7: Quality and approval gateawait 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: {},+ editorData: packagingExperiment ? {+ packagingExperiment,+ selectedTitleVariant: 0,+ selectedThumbnailVariant: 0+ } : {},reviewNotes: quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`,reviewedAt: approvalRequired ? null : new Date().toISOString()});@@ -867,9 +904,57 @@ class YouTubeAutomationAgent {}if (input.factChecked !== undefined) output.factChecked = input.factChecked === true;if (input.rightsConfirmed !== undefined) output.rightsConfirmed = input.rightsConfirmed === true;+ const experiment = output.packagingExperiment;+ if (input.selectedTitleVariant !== undefined) {+ const selected = Number(input.selectedTitleVariant);+ if (!Number.isInteger(selected) || !experiment?.titleVariants?.[selected]) {+ throw new Error('Selected title variant is invalid');+ }+ output.selectedTitleVariant = selected;+ }+ if (input.selectedThumbnailVariant !== undefined) {+ const selected = Number(input.selectedThumbnailVariant);+ if (!Number.isInteger(selected) || !experiment?.thumbnailVariants?.[selected]) {+ throw new Error('Selected thumbnail variant is invalid');+ }+ output.selectedThumbnailVariant = selected;+ }return output;}+ buildTitleExperimentVariants(title) {+ const control = String(title || '').trim().slice(0, 100);+ const withoutPunctuation = control.replace(/[.!?]+$/, '');+ return [+ { label: 'Control', title: control },+ { label: 'Step-by-step', title: `${withoutPunctuation}: Step-by-Step`.slice(0, 100) },+ { label: 'Curiosity', title: `${withoutPunctuation}: What Most People Miss`.slice(0, 100) }+ ];+ }++ async preparePackagingExperiment(thumbnail, productionData, seoData, script) {+ const approved = await this.db.listLearningRecommendations({ status: 'approved', limit: 25 });+ const recommendation = approved.find(item => item.proposedChange?.experiment === 'title_thumbnail_variant');+ if (!recommendation) return null;+ try {+ const generated = await this.agents.thumbnailDesigner.generateABVariants(thumbnail.concept);+ return {+ sourceRecommendationId: recommendation.id,+ hypothesis: recommendation.title,+ status: 'draft',+ titleVariants: this.buildTitleExperimentVariants(seoData.title || script.title),+ thumbnailVariants: [+ { label: 'Control', path: productionData.assets?.thumbnail?.path, concept: thumbnail.concept },+ ...generated+ ],+ createdAt: new Date().toISOString()+ };+ } catch (error) {+ this.logger.warn(`Packaging experiment preparation failed without blocking production: ${error.message}`);+ return null;+ }+ }+validateProfile(input) {const textFields = ['channelName', 'goal', 'targetAudience', 'brandVoice', 'defaultStyle', 'callToAction', 'visualStyle', 'timezone'];const result = {};@@ -888,11 +973,15 @@ class YouTubeAutomationAgent {}decorateContentBundle(bundle) {+ const experiment = bundle.editorData?.packagingExperiment;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,+ experimentThumbnails: (experiment?.thumbnailVariants || []).map((_variant, index) =>+ `/api/content/${bundle.id}/asset/experiment-thumbnail-${index}`+ ),captions: bundle.assets?.captions?.path ? `/api/content/${bundle.id}/asset/captions` : null,script: bundle.assets?.script?.originalPath ? `/api/content/${bundle.id}/asset/script` : null}@@ -913,6 +1002,10 @@ class YouTubeAutomationAgent {}const editorData = this.validateEditorData(input, bundle.editorData);+ const packagingExperiment = editorData.packagingExperiment;+ const thumbnailVariant = packagingExperiment?.thumbnailVariants?.[editorData.selectedThumbnailVariant];+ const titleVariant = packagingExperiment?.titleVariants?.[editorData.selectedTitleVariant];+ if (titleVariant && input.title === undefined) editorData.title = titleVariant.title;if (!editorData.factChecked || !editorData.rightsConfirmed) {const error = new Error('Confirm the factual review and media rights checks before approval');error.status = 409;@@ -930,7 +1023,9 @@ class YouTubeAutomationAgent {description: editorData.description || bundle.seo.description,tags: editorData.tags || bundle.seo.tags},- assets: bundle.assets,+ assets: thumbnailVariant+ ? { ...bundle.assets, thumbnail: { ...bundle.assets.thumbnail, path: thumbnailVariant.path } }+ : bundle.assets,timeline: bundle.timeline,scheduledPublishTime: editorData.publishTime || input.publishTime || bundle.scheduled_publish_time,priority: bundle.priority,diff --git a/schedules/daily-automation.js b/schedules/daily-automation.jsindex 1cb3a03..d9f41a5 100644--- a/schedules/daily-automation.js+++ b/schedules/daily-automation.js@@ -242,20 +242,22 @@ class DailyAutomation {try {this.logger.info('Starting daily analytics collection...');- // Get recently published videos- const recentVideos = await this.getRecentlyPublishedVideos(7);+ // Keep a 30-day catch-up window so new installs can backfill 24-hour and 7-day evidence.+ const recentVideos = await this.getRecentlyPublishedVideos(30);let processedCount = 0;for (const video of recentVideos) {try {- await this.agents.analytics.analyzeVideoPerformance(video.youtube_id);- processedCount++;-- this.logger.info(`Analyzed video: ${video.title}`);-- // Small delay to avoid API rate limits- await this.sleep(2000);+ const windows = await this.agents.analytics.getDueMeasurementWindows(video);+ for (const measurementWindow of windows) {+ await this.agents.analytics.analyzeVideoPerformance(video.youtube_id, { measurementWindow });+ processedCount++;+ this.logger.info(`Captured ${measurementWindow} learning evidence for: ${video.title}`);++ // Small delay to avoid API rate limits+ await this.sleep(2000);+ }} catch (error) {this.logger.error(`Failed to analyze video ${video.youtube_id}:`, error);}diff --git a/test.js b/test.jsindex 1755ba6..e50e20c 100644--- a/test.js+++ b/test.js@@ -22,6 +22,7 @@ class SystemTest {{ name: 'Anonymous Telemetry Opt-in', test: () => this.testAnonymousTelemetryOptIn() },{ name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },+ { name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },@@ -244,6 +245,7 @@ class SystemTest {await db.initialize();let server;let job;+ let learningRecommendation;try {job = await db.createGenerationJob({ topic: 'Operator workflow test', style: 'explainer', length: 'short' });@@ -254,6 +256,7 @@ class SystemTest {}const operator = new OperatorService(db);+ operator.notify = async () => null;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'] },@@ -301,9 +304,28 @@ class SystemTest {if (unavailableStart.status !== 503) {throw new Error('Autonomous operator did not fail closed when its strategy agent was unavailable');}++ learningRecommendation = await db.saveLearningRecommendation({+ fingerprint: `operator-api-${Date.now()}`,+ category: 'format',+ title: 'Test evidence-backed recommendation',+ rationale: 'Created only for API contract verification.',+ evidence: { sampleSize: 4 },+ proposedChange: { target: 'future_plans', prefer: 'tutorial' },+ confidence: 'medium'+ });+ const approveLearning = await fetch(+ `http://127.0.0.1:${port}/api/learning/recommendations/${learningRecommendation.id}/approve`,+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }+ );+ const approvedLearning = await approveLearning.json();+ if (!approveLearning.ok || approvedLearning.result?.status !== 'approved') {+ throw new Error('Learning recommendation review API did not persist approval');+ }} finally {if (server) await new Promise(resolve => server.close(resolve));if (job) await db.executeQuery('DELETE FROM generation_jobs WHERE id = ?', [job.id]);+ if (learningRecommendation) await db.executeQuery('DELETE FROM learning_recommendations WHERE id = ?', [learningRecommendation.id]);await db.close();}@@ -401,6 +423,118 @@ class SystemTest {this.logger.info('Autonomous channel operator test completed successfully');}+ async testChannelLearningLoop() {+ const fs = require('fs').promises;+ const os = require('os');+ const { ChannelLearningEngine } = require('./utils/channel-learning-engine');+ const { ContentStrategyAgent } = require('./agents/content-strategy-agent');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-learning-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'learning.db');+ await db.initialize();++ try {+ const learning = new ChannelLearningEngine(db);+ const report = (videoId, format, performanceScore, ctr, retention, simulated = false) => ({+ videoId,+ videoDetails: {+ title: `${format} automation guide`,+ publishedAt: new Date(Date.now() - 8 * 86400000).toISOString()+ },+ analytics: {+ simulated,+ views: { totalViews: 500, totalImpressions: 5000, averageCTR: ctr },+ watchTime: { averageViewPercentage: retention, averageViewDuration: 240, totalWatchTime: 2000 },+ engagement: { engagementRate: format === 'tutorial' ? 6 : 2 }+ },+ thumbnailMetrics: { impressions: 5000, clickThroughRate: ctr },+ performance: { score: performanceScore, grade: 'B' }+ });+ const context = format => ({+ strategy: { topic: `${format} topic`, contentType: format, requestedLengthKey: 'medium' },+ script: { hook: 'A concise opening that immediately promises a useful and concrete result.' },+ thumbnail: { concept: { composition: 'centered' } }+ });++ await learning.capture(report('learning-tutorial-1', 'tutorial', 88, 7.5, 62), context('tutorial'), '7d');+ await learning.capture(report('learning-tutorial-2', 'tutorial', 84, 7, 58), context('tutorial'), '7d');+ await learning.capture(report('learning-list-1', 'list', 52, 3.5, 39), context('list'), '7d');+ await learning.capture(report('learning-list-2', 'list', 48, 3, 35), context('list'), '7d');+ await learning.capture(report('learning-simulated', 'review', 99, 12, 90, true), context('review'), '7d');++ const summary = await learning.getSummary();+ const recommendation = summary.recommendations.find(item => item.category === 'format');+ if (summary.measuredVideos !== 4 || !recommendation || !/tutorial/.test(recommendation.title)) {+ throw new Error('Learning engine did not derive a real-evidence format recommendation');+ }+ if (summary.recommendations.some(item => /review/.test(item.title))) {+ throw new Error('Simulated analytics influenced a learning recommendation');+ }++ const approved = await db.reviewLearningRecommendation(recommendation.id, 'approved');+ if (approved.status !== 'approved') throw new Error('Learning recommendation approval was not persisted');++ const strategyAgent = new ContentStrategyAgent(db, {});+ strategyAgent.analyzeTrends = async function() {+ this.trendingTopics = [];+ this.competitorData = [];+ };+ const planned = await strategyAgent.researchAndPlanChannel({+ objective: 'Teach useful automation',+ audience: 'Small teams',+ value_proposition: 'Practical guidance',+ contentPillars: ['Automation'],+ videos_per_run: 1,+ default_format: 'tutorial',+ default_length: 'medium'+ });+ if (+ planned.research.approvedLearnings.length !== 1 ||+ !planned.research.sources.includes('Operator-approved channel performance learnings')+ ) {+ throw new Error('Approved learning was not supplied to autonomous planning');+ }++ const due = await learning.getDueMeasurementWindows({+ youtube_id: 'unmeasured-video',+ published_at: new Date(Date.now() - 8 * 86400000).toISOString()+ });+ if (!due.includes('24h') || !due.includes('7d')) {+ throw new Error('24-hour and 7-day learning windows were not scheduled');+ }++ const { YouTubeAutomationAgent } = require('./index');+ const { ThumbnailDesignerAgent } = require('./agents/thumbnail-designer-agent');+ const workflow = new YouTubeAutomationAgent();+ const titleVariants = workflow.buildTitleExperimentVariants('Automate Your Weekly Reporting');+ const selected = workflow.validateEditorData(+ { selectedTitleVariant: 1, selectedThumbnailVariant: 2 },+ { packagingExperiment: { titleVariants, thumbnailVariants: [{}, {}, {}] } }+ );+ if (titleVariants.length !== 3 || selected.selectedTitleVariant !== 1 || selected.selectedThumbnailVariant !== 2) {+ throw new Error('Packaging experiment selections were not validated');+ }++ const thumbnailDesigner = new ThumbnailDesignerAgent(db, {});+ thumbnailDesigner.createThumbnail = async (_concept, suffix) => `base-${suffix}`;+ thumbnailDesigner.addTextOverlay = async (_path, _concept, suffix) => `overlay-${suffix}`;+ thumbnailDesigner.optimizeForYouTube = async (_path, suffix) => `optimized-${suffix}.jpg`;+ const thumbnailVariants = await thumbnailDesigner.generateABVariants({+ primaryText: 'GUIDE',+ colors: { primary: 'blue', secondary: 'white', accent: 'green' },+ composition: 'split'+ });+ if (thumbnailVariants.length !== 3 || thumbnailVariants.some(item => !item.path.endsWith('.jpg'))) {+ throw new Error('Approved packaging learning did not produce complete thumbnail variants');+ }+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }++ this.logger.info('Closed-loop channel learning test completed successfully');+ }+async testAPIValidationAndSecurity() {const { YouTubeAutomationAgent } = require('./index');const agent = new YouTubeAutomationAgent();diff --git a/utils/channel-learning-engine.js b/utils/channel-learning-engine.jsnew file mode 100644index 0000000..5c20bc8--- /dev/null+++ b/utils/channel-learning-engine.js@@ -0,0 +1,296 @@+const crypto = require('crypto');+const { Logger } = require('./logger');++class ChannelLearningEngine {+ constructor(db) {+ this.db = db;+ this.logger = new Logger('ChannelLearning');+ }++ async capture(performanceReport, context = {}, measurementWindow = 'rolling') {+ const metrics = this.normalizeMetrics(performanceReport);+ const attributes = this.extractAttributes(performanceReport, context);+ const prior = await this.db.listPerformanceSnapshots({+ measurementWindow,+ reliableOnly: true,+ excludeVideoId: performanceReport.videoId+ });+ const baseline = this.calculateBaseline(prior);+ const simulated = Boolean(performanceReport.analytics?.simulated);+ const confidence = simulated ? 'unverified' : this.confidenceFor(metrics);+ const snapshot = await this.db.savePerformanceSnapshot({+ videoId: performanceReport.videoId,+ productionId: context.productionId || null,+ measurementWindow,+ publishedAt: performanceReport.videoDetails?.publishedAt || context.publishedAt || null,+ metrics,+ contentAttributes: attributes,+ baseline,+ deltas: this.calculateDeltas(metrics, baseline),+ confidence,+ simulated+ });++ if (simulated) {+ this.logger.warn(`Excluded simulated analytics for ${performanceReport.videoId} from channel learning`);+ return snapshot;+ }++ await this.refreshRecommendations();+ return snapshot;+ }++ normalizeMetrics(report) {+ const analytics = report.analytics || {};+ const views = analytics.views || {};+ const watchTime = analytics.watchTime || {};+ const engagement = analytics.engagement || {};+ return {+ views: this.number(views.totalViews),+ impressions: this.number(views.totalImpressions || report.thumbnailMetrics?.impressions),+ ctr: this.number(report.thumbnailMetrics?.clickThroughRate ?? views.averageCTR),+ retention: this.number(watchTime.averageViewPercentage),+ averageViewDuration: this.number(watchTime.averageViewDuration),+ watchMinutes: this.number(watchTime.totalWatchTime),+ engagementRate: this.number(engagement.engagementRate),+ performanceScore: this.number(report.performance?.score)+ };+ }++ extractAttributes(report, context) {+ const strategy = context.strategy || {};+ const script = context.script || {};+ const thumbnail = context.thumbnail || {};+ const title = report.videoDetails?.title || context.title || script.title || '';+ const hook = this.text(script.hook || script.introduction || '');+ return {+ topic: strategy.topic || '',+ format: this.slug(strategy.requestedStyle || strategy.contentType || 'unknown'),+ length: this.slug(strategy.requestedLengthKey || strategy.requestedLength || 'unknown'),+ hookLength: hook ? (this.wordCount(hook) <= 40 ? 'concise' : 'extended') : 'unknown',+ titleLength: title ? (this.wordCount(title) <= 9 ? 'concise' : 'long') : 'unknown',+ thumbnailStyle: this.slug(+ thumbnail.concept?.composition || thumbnail.concept?.style || thumbnail.style || 'unknown'+ ),+ source: strategy.planRationale ? 'autonomous_operator' : 'manual'+ };+ }++ calculateBaseline(snapshots) {+ const keys = ['views', 'impressions', 'ctr', 'retention', 'averageViewDuration', 'watchMinutes', 'engagementRate', 'performanceScore'];+ return Object.fromEntries(keys.map(key => [key, this.median(+ snapshots.map(snapshot => this.number(snapshot.metrics?.[key])).filter(value => Number.isFinite(value))+ )]));+ }++ calculateDeltas(metrics, baseline) {+ return Object.fromEntries(Object.entries(metrics).map(([key, value]) => {+ const reference = this.number(baseline[key]);+ return [key, reference > 0 ? Number((((value - reference) / reference) * 100).toFixed(1)) : null];+ }));+ }++ confidenceFor(metrics) {+ if (metrics.impressions >= 1000 && metrics.views >= 100) return 'high';+ if (metrics.impressions >= 100 && metrics.views >= 20) return 'medium';+ return 'low';+ }++ async refreshRecommendations() {+ const all = await this.db.listPerformanceSnapshots({ reliableOnly: true });+ const snapshots = this.preferredSnapshotPerVideo(all);+ if (snapshots.length < 2) return [];++ const candidates = [+ ...this.buildDimensionRecommendations(snapshots),+ ...this.buildChannelRecommendations(snapshots)+ ];+ const saved = [];+ for (const candidate of candidates) {+ saved.push(await this.db.saveLearningRecommendation({+ ...candidate,+ fingerprint: this.fingerprint(candidate)+ }));+ }+ return saved;+ }++ preferredSnapshotPerVideo(snapshots) {+ const rank = { '7d': 3, '24h': 2, rolling: 1 };+ const selected = new Map();+ for (const snapshot of snapshots) {+ const current = selected.get(snapshot.videoId);+ if (!current || (rank[snapshot.measurementWindow] || 0) > (rank[current.measurementWindow] || 0)) {+ selected.set(snapshot.videoId, snapshot);+ }+ }+ return [...selected.values()];+ }++ buildDimensionRecommendations(snapshots) {+ const dimensions = [+ { key: 'format', metric: 'performanceScore', label: 'format', minimumDifference: 10 },+ { key: 'length', metric: 'retention', label: 'video length', minimumDifference: 8 },+ { key: 'hookLength', metric: 'retention', label: 'hook style', minimumDifference: 8 },+ { key: 'titleLength', metric: 'ctr', label: 'title style', minimumDifference: 1.25 }+ ];+ const recommendations = [];++ for (const dimension of dimensions) {+ const groups = new Map();+ for (const snapshot of snapshots) {+ const value = snapshot.contentAttributes?.[dimension.key];+ const metric = this.number(snapshot.metrics?.[dimension.metric]);+ if (!value || value === 'unknown' || !Number.isFinite(metric)) continue;+ if (!groups.has(value)) groups.set(value, []);+ groups.get(value).push(metric);+ }+ const ranked = [...groups.entries()]+ .filter(([, values]) => values.length >= 2)+ .map(([value, values]) => ({ value, count: values.length, average: this.average(values) }))+ .sort((a, b) => b.average - a.average);+ if (ranked.length < 2 || ranked[0].average - ranked.at(-1).average < dimension.minimumDifference) continue;++ const best = ranked[0];+ const weakest = ranked.at(-1);+ const metricLabel = dimension.metric === 'ctr' ? 'CTR' : dimension.metric === 'retention' ? 'retention' : 'performance score';+ recommendations.push({+ category: dimension.key,+ title: `Favor ${this.readable(best.value)} over ${this.readable(weakest.value)} ${dimension.label}`,+ rationale: `${this.readable(best.value)} ${dimension.label} averaged ${this.metric(best.average, dimension.metric)} ${metricLabel} across ${best.count} videos versus ${this.metric(weakest.average, dimension.metric)} across ${weakest.count}.`,+ evidence: { dimension: dimension.key, metric: dimension.metric, best, weakest },+ proposedChange: { target: 'future_plans', dimension: dimension.key, prefer: best.value, deprioritize: weakest.value },+ confidence: best.count >= 4 && weakest.count >= 4 ? 'high' : 'medium'+ });+ }+ return recommendations;+ }++ buildChannelRecommendations(snapshots) {+ const sufficientlyExposed = snapshots.filter(snapshot => this.number(snapshot.metrics?.impressions) >= 100);+ if (sufficientlyExposed.length < 2) return [];+ const averageCTR = this.average(sufficientlyExposed.map(item => this.number(item.metrics.ctr)));+ const averageRetention = this.average(sufficientlyExposed.map(item => this.number(item.metrics.retention)));+ const recommendations = [];++ if (averageCTR < 4) {+ recommendations.push({+ category: 'packaging',+ title: 'Test new title and thumbnail packaging',+ rationale: `Channel CTR averaged ${averageCTR.toFixed(1)}% across ${sufficientlyExposed.length} sufficiently exposed videos.`,+ evidence: { metric: 'ctr', average: averageCTR, sampleSize: sufficientlyExposed.length, minimumImpressions: 100 },+ proposedChange: { target: 'review', experiment: 'title_thumbnail_variant' },+ confidence: sufficientlyExposed.length >= 5 ? 'high' : 'medium'+ });+ }+ if (averageRetention < 35) {+ recommendations.push({+ category: 'retention',+ title: 'Tighten hooks and early pacing',+ rationale: `Average view percentage was ${averageRetention.toFixed(1)}% across ${sufficientlyExposed.length} sufficiently exposed videos.`,+ evidence: { metric: 'retention', average: averageRetention, sampleSize: sufficientlyExposed.length },+ proposedChange: { target: 'future_scripts', prefer: 'concise_hook_and_faster_opening' },+ confidence: sufficientlyExposed.length >= 5 ? 'high' : 'medium'+ });+ }+ return recommendations;+ }++ async getSummary() {+ const snapshots = await this.db.listPerformanceSnapshots({ reliableOnly: true });+ const recommendations = await this.db.listLearningRecommendations({ limit: 50 });+ const preferred = this.preferredSnapshotPerVideo(snapshots);+ return {+ measuredVideos: preferred.length,+ snapshotCount: snapshots.length,+ baseline: this.calculateBaseline(preferred),+ windows: snapshots.reduce((counts, snapshot) => {+ counts[snapshot.measurementWindow] = (counts[snapshot.measurementWindow] || 0) + 1;+ return counts;+ }, {}),+ recommendations,+ approvedCount: recommendations.filter(item => item.status === 'approved').length,+ pendingCount: recommendations.filter(item => item.status === 'pending').length,+ lastMeasuredAt: snapshots[0]?.measuredAt || null,+ evidencePolicy: 'Only real YouTube analytics are eligible; simulated fallbacks are excluded.'+ };+ }++ async getDueMeasurementWindows(video) {+ const published = new Date(video.published_at || video.publishedAt);+ if (Number.isNaN(published.getTime())) return [];+ const ageHours = (Date.now() - published.getTime()) / 3600000;+ const existing = await this.db.listPerformanceSnapshots({+ videoId: video.youtube_id || video.youtubeId,+ reliableOnly: true+ });+ const windows = new Set(existing.map(item => item.measurementWindow));+ return [+ ...(ageHours >= 24 && !windows.has('24h') ? ['24h'] : []),+ ...(ageHours >= 168 && !windows.has('7d') ? ['7d'] : [])+ ];+ }++ measurementPeriod(publishedAt, measurementWindow) {+ if (!['24h', '7d'].includes(measurementWindow) || !publishedAt) return null;+ const start = new Date(publishedAt);+ if (Number.isNaN(start.getTime())) return null;+ const days = measurementWindow === '24h' ? 1 : 7;+ const end = new Date(Math.min(Date.now(), start.getTime() + days * 86400000));+ return { startDate: this.date(start), endDate: this.date(end) };+ }++ fingerprint(candidate) {+ const identity = {+ category: candidate.category,+ title: candidate.title,+ proposedChange: candidate.proposedChange+ };+ return crypto.createHash('sha256').update(JSON.stringify(identity)).digest('hex');+ }++ median(values) {+ if (!values.length) return 0;+ const sorted = [...values].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;+ }++ average(values) {+ return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;+ }++ metric(value, metric) {+ return metric === 'performanceScore' ? value.toFixed(0) : `${value.toFixed(1)}%`;+ }++ number(value) {+ const number = Number(value);+ return Number.isFinite(number) ? number : 0;+ }++ text(value) {+ if (typeof value === 'string') return value;+ if (Array.isArray(value)) return value.map(item => this.text(item)).join(' ');+ if (value && typeof value === 'object') return Object.values(value).map(item => this.text(item)).join(' ');+ return '';+ }++ wordCount(value) {+ return String(value).trim().split(/\s+/).filter(Boolean).length;+ }++ slug(value) {+ return String(value || 'unknown').trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '') || 'unknown';+ }++ readable(value) {+ return String(value).replaceAll('_', ' ');+ }++ date(value) {+ return value.toISOString().slice(0, 10);+ }+}++module.exports = { ChannelLearningEngine };