🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
feat: add outcome and ROI studio
darkzOGxbba9e23e6a7f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f9594ab..9d2c6b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,14 @@# Changelog+## Unreleased++- Added a structured channel-outcome contract with primary KPI, numeric target, measurement window, monthly production budget, and currency while retaining free-text outcome context+- Added independent YouTube subscriber and monetization collection so unavailable revenue never converts otherwise-real analytics into simulated data or false zeroes+- Extended real performance snapshots with net subscribers, watch hours, subscriber and revenue efficiency, known production cost, net revenue, and ROI evidence+- Added an Outcome & ROI Studio dashboard with target progress, evidence coverage, channel economics, and pillar, format, and provider comparisons+- Added approval-gated outcome-allocation recommendations; pending or rejected recommendations cannot change autonomous planning+- Added `GET /api/outcomes`, structured strategy validation, content-pillar propagation, database migrations, and regression coverage for goal alignment and non-monetized channels+## v2.9.0 — 2026-08-23- Added a persistent Audience Engagement Studio: tapered read-only comment sync for recent videos with a strict no-simulated-comments policydiff --git a/README.md b/README.mdindex 8f4284e..f2c9a97 100644--- a/README.md+++ b/README.md@@ -118,6 +118,14 @@ Open **Analytics → What the agent learned** to review the evidence and confideWhen 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.+### Align the channel with outcomes and ROI++The Autonomous Operator strategy can define a measurable primary outcome—views, watch hours, net subscribers, engagement rate, or estimated revenue—plus a numeric target, evidence window, monthly production budget, and currency. The existing free-text outcome context remains available for goals that need human nuance.++At each real analytics window, Lumen stores subscriber gains and losses, watch hours, monetization evidence when the channel exposes it, and known production costs from durable scene records. **Analytics → Outcome & ROI Studio** shows target progress, evidence coverage, net subscribers, estimated revenue, known cost, ROI, and comparisons by content pillar, format, and production provider.++Missing evidence is explicit. A channel without monetization access shows revenue as unavailable rather than zero, and ROI stays unavailable until both revenue and complete cost evidence exist. When at least two comparable videos exist in each group, the learning engine can propose reallocating future content toward the pillar or format that best advances the configured outcome. That proposal remains pending until you approve it; Lumen never changes the strategy or budget silently.+### Find the exact scene that lost viewersAt each real analytics window, AgentTube also requests YouTube's audience-retention curve and maps its 100 elapsed-time points onto the stored scene durations. Open **Analytics → Scene-aware retention** to see the curve divided by scene, compare absolute and relative retention, and inspect drop-off, rewatch, strong-hold, or steady signals for each beat.@@ -141,7 +149,7 @@ When three or more commenters ask for the same thing, the analysis mines an **au| 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 | Captures 24-hour and 7-day evidence, then proposes the next move | Approve or reject each learning before it guides planning |+| Learn | Captures 24-hour and 7-day evidence, measures the configured outcome and economics, then proposes the next move | Choose the KPI and 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.@@ -374,7 +382,7 @@ curl -X POST http://localhost:3456/api/readiness/run \curl -X PUT http://localhost:3456/api/operator/strategy \-H "Content-Type: application/json" \-H "x-api-key: $API_KEY" \- -d '{"objective":"Own practical AI automation for small teams","audience":"Small business operators","contentPillars":["AI workflows","Automation playbooks"],"cadencePerWeek":2,"videosPerRun":2,"defaultFormat":"tutorial","defaultLength":"medium","status":"draft"}'+ -d '{"objective":"Own practical AI automation for small teams","audience":"Small business operators","contentPillars":["AI workflows","Automation playbooks"],"cadencePerWeek":2,"videosPerRun":2,"defaultFormat":"tutorial","defaultLength":"medium","primaryKpi":"subscribers","targetValue":100,"targetWindowDays":28,"monthlyBudget":250,"outcomeCurrency":"USD","status":"draft"}'# activate the saved strategy and start a background operator runcurl -X POST http://localhost:3456/api/operator/start \@@ -392,6 +400,9 @@ curl http://localhost:3456/schedule# get analyticscurl http://localhost:3456/analytics+# get the goal-aligned Outcome & ROI Studio summary+curl http://localhost:3456/api/outcomes+# approve an evidence-backed learning for future autonomous planscurl -X POST http://localhost:3456/api/learning/recommendations/:recommendationId/approve \-H "x-api-key: $API_KEY"diff --git a/agents/analytics-optimization-agent.js b/agents/analytics-optimization-agent.jsindex 2e6eb56..031398b 100644--- a/agents/analytics-optimization-agent.js+++ b/agents/analytics-optimization-agent.js@@ -64,7 +64,10 @@ class AnalyticsOptimizationAgent {const period = this.learning.measurementPeriod(videoDetails.publishedAt, measurementWindow);// Get analytics data- const analytics = await this.getVideoAnalytics(videoId, period);+ const channelStrategy = this.db.getChannelStrategy ? await this.db.getChannelStrategy() : null;+ const analytics = await this.getVideoAnalytics(videoId, period, {+ currency: channelStrategy?.outcome_currency || 'USD'+ });const context = await this.db.getPublishedContentContext(videoId);// Fetch the granular retention curve separately so its absence never@@ -156,7 +159,7 @@ class AnalyticsOptimizationAgent {};}- async getVideoAnalytics(videoId, period = null) {+ async getVideoAnalytics(videoId, period = null, options = {}) {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];@@ -167,13 +170,15 @@ class AnalyticsOptimizationAgent {watchTimeData,demographicsData,trafficSourcesData,- deviceData+ deviceData,+ outcomeData] = await Promise.all([this.getViewsAnalytics(videoId, startDate, endDate),this.getWatchTimeAnalytics(videoId, startDate, endDate),this.getDemographicsAnalytics(videoId, startDate, endDate),this.getTrafficSourcesAnalytics(videoId, startDate, endDate),- this.getDeviceAnalytics(videoId, startDate, endDate)+ this.getDeviceAnalytics(videoId, startDate, endDate),+ this.getOutcomeAnalytics(videoId, startDate, endDate, options.currency || 'USD')]);return {@@ -184,6 +189,7 @@ class AnalyticsOptimizationAgent {demographics: demographicsData,trafficSources: trafficSourcesData,devices: deviceData,+ outcomes: outcomeData,engagement: await this.calculateEngagementMetrics(videoId)};} catch (error) {@@ -307,6 +313,40 @@ class AnalyticsOptimizationAgent {};}+ async getOutcomeAnalytics(videoId, startDate, endDate, currency = 'USD') {+ const query = (metrics, includeCurrency = false) => this.youtubeAnalytics.reports.query({+ ids: 'channel==MINE',+ startDate,+ endDate,+ metrics,+ filters: `video==${videoId}`,+ ...(includeCurrency ? { currency } : {})+ });+ const [subscriberResult, revenueResult] = await Promise.allSettled([+ query('subscribersGained,subscribersLost'),+ query('estimatedRevenue,monetizedPlaybacks,playbackBasedCpm', true)+ ]);+ const subscribers = subscriberResult.status === 'fulfilled'+ ? subscriberResult.value.data.rows?.[0] || [0, 0]+ : null;+ const revenue = revenueResult.status === 'fulfilled'+ ? revenueResult.value.data.rows?.[0] || [0, 0, 0]+ : null;+ if (!subscribers) this.logger.warn(`Subscriber outcomes unavailable for ${videoId}: ${subscriberResult.reason?.message || 'unknown error'}`);+ if (!revenue) this.logger.info(`Revenue outcomes unavailable for ${videoId}; monetization data will remain unavailable`);+ return {+ subscribersAvailable: Boolean(subscribers),+ subscribersGained: subscribers ? Number(subscribers[0] || 0) : null,+ subscribersLost: subscribers ? Number(subscribers[1] || 0) : null,+ netSubscribers: subscribers ? Number(subscribers[0] || 0) - Number(subscribers[1] || 0) : null,+ revenueAvailable: Boolean(revenue),+ currency: revenue ? currency : null,+ estimatedRevenue: revenue ? Number(revenue[0] || 0) : null,+ monetizedPlaybacks: revenue ? Number(revenue[1] || 0) : null,+ playbackBasedCpm: revenue ? Number(revenue[2] || 0) : null+ };+ }+async calculateEngagementMetrics(videoId) {const videoDetails = await this.getVideoDetails(videoId);const stats = videoDetails.statistics;@@ -672,7 +712,12 @@ class AnalyticsOptimizationAgent {views: { totalViews: Math.floor(Math.random() * 50000), averageCTR: Math.random() * 10 },watchTime: { averageViewPercentage: Math.random() * 100 },engagement: { engagementRate: Math.random() * 10 },- trafficSources: { sources: [{ source: 'SEARCH', percentage: '30' }] }+ trafficSources: { sources: [{ source: 'SEARCH', percentage: '30' }] },+ outcomes: {+ subscribersAvailable: false, subscribersGained: null, subscribersLost: null,+ netSubscribers: null, revenueAvailable: false, estimatedRevenue: null,+ monetizedPlaybacks: null, playbackBasedCpm: null+ }};}diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.jsindex 10d7c75..3d29a58 100644--- a/agents/content-strategy-agent.js+++ b/agents/content-strategy-agent.js@@ -335,7 +335,7 @@ class ContentStrategyAgent {const prompt = `You are the strategy lead for an autonomous YouTube channel.Turn the channel strategy and the supplied research signals into a focused content plan.Return only a valid JSON array with exactly ${targetCount} items using this shape:-[{"topic":"specific video topic","angle":"distinct audience-relevant angle","rationale":"why this advances the channel objective using the supplied evidence","format":"explainer|tutorial|list|review|story","length":"short|medium|long","sourceUrls":["exact URL from the supplied source catalog"]}]+[{"topic":"specific video topic","pillar":"one exact content pillar from the supplied strategy","angle":"distinct audience-relevant angle","rationale":"why this advances the channel objective using the supplied evidence","format":"explainer|tutorial|list|review|story","length":"short|medium|long","sourceUrls":["exact URL from the supplied source catalog"]}]Channel objective: ${channelStrategy.objective}Audience: ${channelStrategy.audience}@@ -344,6 +344,9 @@ Content pillars: ${(channelStrategy.contentPillars || []).join(', ')}Preferred format: ${channelStrategy.default_format}Preferred length: ${channelStrategy.default_length}Success metric: ${channelStrategy.success_metric || 'not specified'}+Primary KPI: ${channelStrategy.primary_kpi || 'views'}+Target: ${channelStrategy.target_value || 'not set'} per ${channelStrategy.target_window_days || 28} days+Monthly production budget: ${channelStrategy.monthly_budget ?? 'not set'} ${channelStrategy.outcome_currency || 'USD'}Constraints: ${channelStrategy.constraints || 'none'}Research signals: ${JSON.stringify(research.signals)}Allowed source catalog: ${JSON.stringify(research.sourceCatalog)}@@ -373,6 +376,7 @@ Do not invent trend data, statistics, sources, URLs, or factual claims. Use onlyreturn candidates.slice(0, targetCount).map((topic, index) => ({topic,+ pillar: pillars.find(pillar => topic.toLowerCase().includes(String(pillar).toLowerCase())) || pillars[index % Math.max(1, pillars.length)] || '',angle: `${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.'@@ -389,10 +393,12 @@ Do not invent trend data, statistics, sources, URLs, or factual claims. Use onlyconst formats = new Set(['explainer', 'tutorial', 'list', 'review', 'story']);const lengths = new Set(['short', 'medium', 'long']);const allowedSourceUrls = new Set((research.sourceCatalog || []).map(source => source.url));+ const pillars = channelStrategy.contentPillars || [];const seen = new Set();return plan.map(item => ({topic: String(item.topic || '').trim().slice(0, 200),+ pillar: pillars.find(pillar => String(pillar).toLowerCase() === String(item.pillar || '').trim().toLowerCase()) || '',angle: String(item.angle || '').trim().slice(0, 500),rationale: String(item.rationale || '').trim().slice(0, 1000),format: formats.has(String(item.format || '').toLowerCase())diff --git a/dashboard/app.js b/dashboard/app.jsindex e460a45..3e46776 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -315,10 +315,71 @@ function renderAnalytics(analytics, learning = {}) {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.');+ renderOutcome(learning.outcome || {});renderLearning(learning);renderRetention(learning.retention || {});}+function formatOutcomeValue(value, kind = 'number', currency = 'USD') {+ if (value === null || value === undefined) return 'Unavailable';+ const number = Number(value);+ if (!Number.isFinite(number)) return 'Unavailable';+ if (kind === 'currency') {+ try {+ return new Intl.NumberFormat(undefined, { style: 'currency', currency, maximumFractionDigits: 2 }).format(number);+ } catch (_error) {+ return `${currency} ${number.toFixed(2)}`;+ }+ }+ if (kind === 'percent') return `${number.toFixed(1)}%`;+ if (kind === 'hours') return `${number.toFixed(1)}h`;+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(number);+}++function renderOutcome(outcome = {}) {+ const status = $('#outcome-status');+ if (!outcome.configured || !outcome.goal) {+ status.textContent = 'Not configured';+ status.className = 'status';+ $('#outcome-summary').innerHTML = empty('Choose a measurable primary outcome in the Autonomous Operator strategy.');+ $('#outcome-economics').innerHTML = '';+ $('#outcome-breakdowns').innerHTML = '';+ $('#outcome-policy').textContent = outcome.evidencePolicy || 'Configure a primary outcome to activate goal-aligned learning.';+ return;+ }+ const { goal, economics = {}, coverage = {}, breakdowns = {} } = outcome;+ status.textContent = outcome.available ? 'Measuring' : 'Awaiting evidence';+ status.className = `status ${outcome.available ? 'active' : ''}`;+ const target = goal.targetValue === null+ ? `No numeric target · ${goal.windowDays}-day evidence window`+ : `${formatOutcomeValue(goal.targetValue, goal.unit, goal.currency)} target · ${goal.windowDays} days`;+ const progress = outcome.progressPercent === null ? null : Math.min(100, Number(outcome.progressPercent));+ $('#outcome-summary').innerHTML = `+ <div class="outcome-primary">+ <span>${escapeHTML(goal.label)}</span>+ <strong>${escapeHTML(outcome.formattedObserved || 'Unavailable')}</strong>+ <small>${escapeHTML(target)} · ${Number(outcome.measuredVideoCount || 0)} measured videos</small>+ ${progress === null ? '' : `<div class="outcome-progress" role="progressbar" aria-label="Outcome target progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${progress}"><span style="width:${progress}%"></span></div><small>${Number(outcome.progressPercent).toFixed(1)}% of target from stored measurement windows</small>`}+ </div>`;+ const economicsRows = [+ ['Net subscribers', economics.netSubscribers, 'number', coverage.subscribers],+ ['Watch hours', economics.watchHours, 'hours', null],+ ['Estimated revenue', economics.estimatedRevenue, 'currency', coverage.revenue],+ ['Known production cost', economics.knownProductionCost, 'currency', coverage.cost],+ ['Estimated ROI', economics.roi, 'percent', null],+ ['Budget used', economics.budgetUsedPercent, 'percent', null]+ ];+ $('#outcome-economics').innerHTML = economicsRows.map(([name, value, kind, metricCoverage]) => `+ <div><span>${escapeHTML(name)}</span><strong>${escapeHTML(formatOutcomeValue(value, kind, economics.currency || goal.currency))}</strong>${metricCoverage ? `<small>${Number(metricCoverage.measured || 0)}/${Number(metricCoverage.total || 0)} videos measured</small>` : ''}</div>`).join('');+ const dimensions = [+ ['pillar', 'Content pillars'], ['format', 'Formats'], ['provider', 'Production providers']+ ].filter(([key]) => Array.isArray(breakdowns[key]) && breakdowns[key].length);+ $('#outcome-breakdowns').innerHTML = dimensions.length ? dimensions.map(([key, heading]) => `+ <section><h3>${escapeHTML(heading)}</h3>${breakdowns[key].slice(0, 5).map(item => `+ <div class="outcome-breakdown-row"><span>${escapeHTML(label(item.name))}<small>${Number(item.count || 0)} video${Number(item.count || 0) === 1 ? '' : 's'}</small></span><strong>${escapeHTML(formatOutcomeValue(item.average, goal.unit, goal.currency))} avg</strong></div>`).join('')}</section>`).join('') : empty('Breakdowns appear once measured videos carry comparable pillar, format, or provider evidence.');+ $('#outcome-policy').textContent = outcome.evidencePolicy;+}+function renderLearning(learning = {}) {const baseline = learning.baseline || {};$('#learning-snapshot-count').textContent = `${learning.snapshotCount || 0} snapshots`;@@ -586,6 +647,11 @@ function renderOperator(strategy, runs, system) {defaultFormat: strategy.default_format,defaultLength: strategy.default_length,successMetric: strategy.success_metric,+ primaryKpi: strategy.primary_kpi,+ targetValue: strategy.target_value,+ targetWindowDays: strategy.target_window_days,+ monthlyBudget: strategy.monthly_budget,+ outcomeCurrency: strategy.outcome_currency,constraints: strategy.constraints} : {};for (const [name, value] of Object.entries(mapping)) {@@ -1435,6 +1501,9 @@ function strategyFormData(status = ui.state?.channelStrategy?.status || 'draft')contentPillars: values.contentPillars.split(',').map(value => value.trim()).filter(Boolean),cadencePerWeek: Number(values.cadencePerWeek),videosPerRun: Number(values.videosPerRun),+ targetValue: values.targetValue === '' ? null : Number(values.targetValue),+ targetWindowDays: Number(values.targetWindowDays),+ monthlyBudget: values.monthlyBudget === '' ? null : Number(values.monthlyBudget),status};}diff --git a/dashboard/index.html b/dashboard/index.htmlindex 4bb0710..391a908 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -99,7 +99,11 @@<label><span>Videos per planning run</span><input name="videosPerRun" type="number" min="1" max="5" value="1"></label><label><span>Default format</span><select name="defaultFormat"><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>Default length</span><select name="defaultLength"><option value="short">Short · 2–4 min</option><option value="medium">Medium · 8–12 min</option><option value="long">Long · 15–20 min</option></select></label>- <label class="full-row"><span>Success metric</span><input name="successMetric" maxlength="300" placeholder="Qualified subscribers and returning viewers"></label>+ <label><span>Primary outcome</span><select name="primaryKpi"><option value="views">Views</option><option value="watch_hours">Watch hours</option><option value="subscribers">Net subscribers</option><option value="engagement">Engagement rate</option><option value="revenue">Estimated revenue</option></select></label>+ <label><span>Target value</span><input name="targetValue" type="number" min="0.01" step="0.01" placeholder="100"></label>+ <label><span>Target window</span><select name="targetWindowDays"><option value="7">7 days</option><option value="28" selected>28 days</option><option value="90">90 days</option><option value="365">365 days</option></select></label>+ <label><span>Monthly production budget</span><span class="currency-input"><select name="outcomeCurrency" aria-label="Outcome currency"><option value="USD">USD</option><option value="CAD">CAD</option><option value="EUR">EUR</option><option value="GBP">GBP</option><option value="AUD">AUD</option></select><input name="monthlyBudget" type="number" min="0" step="0.01" placeholder="Optional"></span></label>+ <label class="full-row"><span>Outcome context</span><input name="successMetric" maxlength="300" placeholder="Grow qualified subscribers who return for practical automation tutorials"><small>Used by planning alongside the measurable primary outcome.</small></label><label class="full-row"><span>Boundaries and constraints</span><textarea name="constraints" rows="3" maxlength="2000" placeholder="No hype, no unverified statistics, explain costs and tradeoffs."></textarea></label></div><p class="callout">The operator uses YouTube trend signals, configured competitors, and channel history. Publishing still obeys your quality, factual-review, rights, and approval gates.</p>@@ -138,6 +142,13 @@<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 outcome-studio">+ <div class="panel-heading"><div><p class="eyebrow">OUTCOME & ROI STUDIO</p><h2>Is the channel achieving its mandate?</h2></div><span id="outcome-status" class="status">Not configured</span></div>+ <div id="outcome-summary" class="outcome-summary"></div>+ <div id="outcome-economics" class="outcome-economics"></div>+ <div id="outcome-breakdowns" class="outcome-breakdowns"></div>+ <p id="outcome-policy" class="callout">Configure a primary outcome in the Autonomous Operator to align channel learning with a measurable goal.</p>+ </article><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>diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 1fd9f44..246ec44 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -363,6 +363,8 @@ label:has(input:disabled) > span { color: var(--muted); }.form-grid.two { grid-template-columns: 1fr 1fr; }.full-row { grid-column: 1 / -1; }.form-actions { margin-top: 4px; }+.currency-input { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 8px; }+.currency-input select, .currency-input input { min-width: 0; }.settings-row { display: flex; flex-wrap: wrap; gap: 24px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); margin: 22px 0; padding: 16px 0; }@@ -428,6 +430,25 @@ label:has(input:disabled) > span { color: var(--muted); }.analytics-stats { grid-template-columns: 1fr 1fr 2fr; }.stat.wide strong.recommendation { font-size: 18px; line-height: 1.4; letter-spacing: -.02em; font-family: var(--font-sans); -webkit-text-fill-color: var(--text); background: none; font-weight: 650; }+.outcome-studio { display: grid; gap: 16px; margin-bottom: 16px; overflow: hidden; }+.outcome-summary { display: grid; grid-template-columns: minmax(0, 1fr); }+.outcome-primary { display: grid; gap: 6px; padding: 18px; border: 1px solid rgba(61, 220, 151, .22); border-radius: var(--radius); background: linear-gradient(145deg, rgba(61, 220, 151, .08), var(--surface-inset)); }+.outcome-primary > span, .outcome-economics span { color: var(--muted); font-size: 9px; text-transform: uppercase; letter-spacing: .12em; font-family: var(--font-mono); font-weight: 600; }+.outcome-primary > strong { font-size: clamp(28px, 4vw, 44px); letter-spacing: -.04em; line-height: 1; }+.outcome-primary small, .outcome-economics small, .outcome-breakdown-row small { color: var(--muted); font-size: 10px; }+.outcome-progress { height: 7px; margin-top: 8px; overflow: hidden; border-radius: 999px; background: rgba(151, 167, 195, .12); }+.outcome-progress span { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, var(--blue), var(--green)); box-shadow: 0 0 16px rgba(61, 220, 151, .35); }+.outcome-economics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }+.outcome-economics > div { display: grid; gap: 5px; min-width: 0; padding: 13px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-inset); }+.outcome-economics strong { overflow-wrap: anywhere; font-size: 17px; font-family: var(--font-mono); }+.outcome-breakdowns { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }+.outcome-breakdowns > section { min-width: 0; border-top: 1px solid var(--line); padding-top: 12px; }+.outcome-breakdowns h3 { margin: 0 0 8px; color: var(--text-2); font-size: 11px; text-transform: uppercase; letter-spacing: .09em; }+.outcome-breakdown-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 7px 0; border-top: 1px solid rgba(151, 167, 195, .07); font-size: 11px; }+.outcome-breakdown-row:first-of-type { border-top: 0; }+.outcome-breakdown-row span, .outcome-breakdown-row small { display: block; min-width: 0; }+.outcome-breakdown-row strong { text-align: right; font-family: var(--font-mono); font-size: 10px; }+.learning-grid { display: grid; grid-template-columns: minmax(300px, .8fr) minmax(0, 1.2fr); gap: 16px; margin-bottom: 16px; }.baseline-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px; }.baseline-grid > div { border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 13px; background: var(--surface-inset); transition: border-color .15s ease; }@@ -663,7 +684,7 @@ label:has(input:disabled) > span { color: var(--muted); }main { width: 100%; max-width: 100vw; 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, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list { grid-template-columns: 1fr; }+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list, .outcome-breakdowns { grid-template-columns: 1fr; }.overview-grid, .card-list, .job-card { min-width: 0; max-width: 100%; }.pipeline-item { grid-template-columns: 1fr auto; }.pipeline-col { display: none; }@@ -672,7 +693,7 @@ label:has(input:disabled) > span { color: var(--muted); }@media (max-width: 560px) {.topbar { align-items: flex-start; flex-direction: column; justify-content: center; padding: 22px 0 18px; }.top-actions .icon-button { display: none; }- .stats-grid, .form-grid, .form-grid.two, .quality-grid { grid-template-columns: 1fr; }+ .stats-grid, .form-grid, .form-grid.two, .quality-grid, .outcome-economics { grid-template-columns: 1fr; }.full-row { grid-column: auto; }.stat { min-height: 108px; }.section-intro, .split-heading, .panel-heading, .form-actions { align-items: flex-start; flex-wrap: wrap; }diff --git a/database/db.js b/database/db.jsindex bf701e2..80a1e81 100644--- a/database/db.js+++ b/database/db.js@@ -481,6 +481,11 @@ class Database {default_format TEXT DEFAULT 'explainer',default_length TEXT DEFAULT 'medium',success_metric TEXT,+ primary_kpi TEXT DEFAULT 'views',+ target_value REAL,+ target_window_days INTEGER DEFAULT 28,+ monthly_budget REAL,+ outcome_currency TEXT DEFAULT 'USD',constraints TEXT,status TEXT DEFAULT 'draft',created_at TEXT DEFAULT CURRENT_TIMESTAMP,@@ -543,13 +548,20 @@ class Database {narration_generated_at: 'TEXT',narration_cost: "TEXT NOT NULL DEFAULT '{}'"});+ await this.ensureColumns('channel_strategies', {+ primary_kpi: "TEXT DEFAULT 'views'",+ target_value: 'REAL',+ target_window_days: 'INTEGER DEFAULT 28',+ monthly_budget: 'REAL',+ outcome_currency: "TEXT DEFAULT 'USD'"+ });// Insert default settingsawait this.insertDefaultSettings();}async ensureColumns(tableName, columns) {- const allowedTables = new Set(['production_scenes']);+ const allowedTables = new Set(['production_scenes', 'channel_strategies']);if (!allowedTables.has(tableName)) throw new Error(`Unsupported migration table: ${tableName}`);const existing = new Set((await this.getAllRows(`PRAGMA table_info(${tableName})`)).map(column => column.name));for (const [columnName, definition] of Object.entries(columns)) {@@ -1400,15 +1412,19 @@ class Database {await this.executeQuery(`INSERT INTO channel_strategies (id, objective, audience, value_proposition, content_pillars, cadence_per_week,- videos_per_run, default_format, default_length, success_metric, constraints,+ videos_per_run, default_format, default_length, success_metric, primary_kpi,+ target_value, target_window_days, monthly_budget, outcome_currency, constraints,status, created_at, updated_at- ) VALUES ('default', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')), datetime('now'))+ ) VALUES ('default', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')), datetime('now'))ON CONFLICT(id) DO UPDATE SETobjective = excluded.objective, audience = excluded.audience,value_proposition = excluded.value_proposition, content_pillars = excluded.content_pillars,cadence_per_week = excluded.cadence_per_week, videos_per_run = excluded.videos_per_run,default_format = excluded.default_format, default_length = excluded.default_length,- success_metric = excluded.success_metric, constraints = excluded.constraints,+ success_metric = excluded.success_metric, primary_kpi = excluded.primary_kpi,+ target_value = excluded.target_value, target_window_days = excluded.target_window_days,+ monthly_budget = excluded.monthly_budget, outcome_currency = excluded.outcome_currency,+ constraints = excluded.constraints,status = excluded.status, updated_at = datetime('now')`,[strategy.objective ?? current.objective ?? '',@@ -1420,6 +1436,11 @@ class Database {strategy.defaultFormat ?? current.default_format ?? 'explainer',strategy.defaultLength ?? current.default_length ?? 'medium',strategy.successMetric ?? current.success_metric ?? '',+ strategy.primaryKpi ?? current.primary_kpi ?? 'views',+ strategy.targetValue ?? current.target_value ?? null,+ strategy.targetWindowDays ?? current.target_window_days ?? 28,+ strategy.monthlyBudget ?? current.monthly_budget ?? null,+ strategy.outcomeCurrency ?? current.outcome_currency ?? 'USD',strategy.constraints ?? current.constraints ?? '',strategy.status ?? current.status ?? 'draft',current.created_at || null@@ -2220,11 +2241,48 @@ class Database {script: JSON.parse(row.script || '{}'),thumbnail: selectedThumbnail?.concept ? { ...thumbnail, concept: selectedThumbnail.concept } : thumbnail,seo: JSON.parse(row.seo || '{}'),+ productionCost: this.summarizeProductionCost(sourceScenes),retentionScenes: this.buildRetentionSceneContext(sourceScenes, shortClip),retentionDuration: isShort ? shortClip?.duration || null : sourceScenes.reduce((sum, scene) => sum + Number(scene.duration || 0), 0)};}+ summarizeProductionCost(scenes = []) {+ const entries = scenes.flatMap(scene => [scene.actualCost, scene.narrationCost]).filter(entry => entry && (+ entry.amount !== undefined || entry.billed !== undefined || entry.invoiceRequired || entry.provider || entry.generatedSeconds+ ));+ const currencies = new Set();+ const providers = new Set();+ let amount = 0;+ let knownEntries = 0;+ let unknownEntries = 0;+ let freeEntries = 0;+ for (const entry of entries) {+ if (entry.provider) providers.add(String(entry.provider));+ if (entry.billed === false) {+ freeEntries++;+ continue;+ }+ const numericAmount = Number(entry.amount);+ if (Number.isFinite(numericAmount) && numericAmount >= 0) {+ amount += numericAmount;+ knownEntries++;+ if (entry.currency) currencies.add(String(entry.currency).toUpperCase());+ } else if (entry.invoiceRequired || entry.billed !== false) {+ unknownEntries++;+ }+ }+ return {+ amount: currencies.size > 1 ? null : knownEntries ? Number(amount.toFixed(4)) : freeEntries && unknownEntries === 0 ? 0 : null,+ currency: currencies.size === 1 ? [...currencies][0] : null,+ complete: unknownEntries === 0 && currencies.size <= 1,+ knownEntries,+ unknownEntries,+ freeEntries,+ providers: [...providers]+ };+ }+buildRetentionSceneContext(scenes = [], shortClip = null) {let cursor = 0;const timeline = scenes.map(scene => {diff --git a/index.js b/index.jsindex 8cee69c..927ee48 100644--- a/index.js+++ b/index.js@@ -275,7 +275,7 @@ class YouTubeAutomationAgent {if (typeof body.strategyContext !== 'object' || Array.isArray(body.strategyContext)) {return { valid: false, status: 400, error: 'strategyContext must be an object' };}- const limits = { angle: 500, rationale: 1000, audience: 500, objective: 1000, valueProposition: 1000, constraints: 2000 };+ const limits = { angle: 500, rationale: 1000, audience: 500, objective: 1000, valueProposition: 1000, constraints: 2000, pillar: 100 };value.strategyContext = {};for (const [key, max] of Object.entries(limits)) {if (body.strategyContext[key] === undefined || body.strategyContext[key] === null) continue;@@ -320,11 +320,26 @@ class YouTubeAutomationAgent {const defaultFormat = text('defaultFormat', current.default_format || 'explainer', 20).toLowerCase();const defaultLength = text('defaultLength', current.default_length || 'medium', 20).toLowerCase();const status = text('status', current.status || 'draft', 20).toLowerCase();+ const primaryKpi = text('primaryKpi', current.primary_kpi || 'views', 30).toLowerCase();+ const outcomeCurrency = text('outcomeCurrency', current.outcome_currency || 'USD', 3).toUpperCase();if (!['explainer', 'tutorial', 'list', 'review', 'story'].includes(defaultFormat)) {throw new Error('defaultFormat is not supported');}if (!['short', 'medium', 'long'].includes(defaultLength)) throw new Error('defaultLength is not supported');if (!['draft', 'active', 'paused'].includes(status)) throw new Error('status must be draft, active, or paused');+ if (!['views', 'watch_hours', 'subscribers', 'engagement', 'revenue'].includes(primaryKpi)) {+ throw new Error('primaryKpi is not supported');+ }+ if (!/^[A-Z]{3}$/.test(outcomeCurrency)) throw new Error('outcomeCurrency must be a three-letter currency code');+ const optionalNumber = (key, fallback, min, max) => {+ const raw = body[key] ?? fallback;+ if (raw === undefined || raw === null || raw === '') return null;+ const value = Number(raw);+ if (!Number.isFinite(value) || value < min || value > max) {+ throw new Error(`${key} must be a number from ${min} to ${max}`);+ }+ return value;+ };return {objective,@@ -336,6 +351,11 @@ class YouTubeAutomationAgent {defaultFormat,defaultLength,successMetric: text('successMetric', current.success_metric, 300),+ primaryKpi,+ targetValue: optionalNumber('targetValue', current.target_value, 0.01, 1000000000),+ targetWindowDays: integer('targetWindowDays', current.target_window_days || 28, 7, 365),+ monthlyBudget: optionalNumber('monthlyBudget', current.monthly_budget, 0, 10000000),+ outcomeCurrency,constraints: text('constraints', current.constraints, 2000),status};@@ -396,6 +416,17 @@ class YouTubeAutomationAgent {}});+ this.app.get('/api/outcomes', async (_req, res) => {+ try {+ const learning = this.agents.analytics?.getLearningSummary+ ? await this.agents.analytics.getLearningSummary()+ : { outcome: null };+ return res.json({ success: true, result: learning.outcome || null });+ } catch (error) {+ return res.status(500).json({ success: false, error: error.message });+ }+ });+// Get upcoming schedulethis.app.get('/schedule', async (req, res) => {try {@@ -1301,6 +1332,7 @@ class YouTubeAutomationAgent {generated.channelGoal = strategyContext.objective || profile.goal || null;generated.channelValueProposition = strategyContext.valueProposition || null;generated.channelConstraints = strategyContext.constraints || null;+ generated.contentPillar = strategyContext.pillar || null;generated.callToAction = profile.call_to_action || null;generated.researchSources = Array.isArray(strategyContext.researchSources)? strategyContext.researchSourcesdiff --git a/test.js b/test.jsindex b657e13..636ebb2 100644--- a/test.js+++ b/test.js@@ -27,6 +27,7 @@ class SystemTest {{ name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },+ { name: 'Outcome and ROI Studio', test: () => this.testOutcomeROIStudio() },{ name: 'Scene-Aware Retention Studio', test: () => this.testSceneAwareRetentionStudio() },{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },{ name: 'Durable Multi-Provider Video Generation', test: () => this.testVideoProviderLayer() },@@ -596,6 +597,89 @@ class SystemTest {this.logger.info('Closed-loop channel learning test completed successfully');}+ async testOutcomeROIStudio() {+ const fs = require('fs').promises;+ const os = require('os');+ const { ChannelLearningEngine } = require('./utils/channel-learning-engine');+ const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');+ const { YouTubeAutomationAgent } = require('./index');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-outcomes-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'outcomes.db');+ await db.initialize();++ try {+ const validated = new YouTubeAutomationAgent().validateChannelStrategy({+ objective: 'Grow a durable automation audience', audience: 'Small teams',+ contentPillars: ['Automation', 'Tool reviews'], primaryKpi: 'subscribers',+ targetValue: 40, targetWindowDays: 28, monthlyBudget: 100,+ outcomeCurrency: 'USD', status: 'active'+ });+ const strategy = await db.saveChannelStrategy(validated);+ if (strategy.primary_kpi !== 'subscribers' || strategy.target_value !== 40 || strategy.target_window_days !== 28) {+ throw new Error('Structured outcome strategy was not validated and persisted');+ }++ const learning = new ChannelLearningEngine(db);+ const report = (videoId, format, subscribers, revenue) => ({+ videoId,+ videoDetails: { title: `${format} outcome fixture`, publishedAt: new Date(Date.now() - 8 * 86400000).toISOString() },+ analytics: {+ simulated: false,+ views: { totalViews: 1000, totalImpressions: 10000, averageCTR: 5 },+ watchTime: { averageViewPercentage: 45, averageViewDuration: 240, totalWatchTime: 4000 },+ engagement: { engagementRate: 4 },+ outcomes: {+ subscribersAvailable: true, subscribersGained: subscribers + 1, subscribersLost: 1,+ netSubscribers: subscribers, revenueAvailable: true, estimatedRevenue: revenue,+ monetizedPlaybacks: 500, playbackBasedCpm: 8, currency: 'USD'+ }+ },+ thumbnailMetrics: { impressions: 10000, clickThroughRate: 5 },+ performance: { score: 70, grade: 'B' }+ });+ const context = (format, pillar) => ({+ strategy: { topic: `${format} topic`, contentType: format, requestedLengthKey: 'medium', contentPillar: pillar },+ script: { hook: 'A concise, outcome-aligned opening.' },+ thumbnail: { concept: { composition: 'centered' } },+ productionCost: { amount: 2, currency: 'USD', complete: true, providers: ['fixture-video'] }+ });+ await learning.capture(report('outcome-tutorial-1', 'tutorial', 12, 5), context('tutorial', 'Automation'), '7d');+ await learning.capture(report('outcome-tutorial-2', 'tutorial', 10, 5), context('tutorial', 'Automation'), '7d');+ await learning.capture(report('outcome-list-1', 'list', 2, 5), context('list', 'Tool reviews'), '7d');+ await learning.capture(report('outcome-list-2', 'list', 1, 5), context('list', 'Tool reviews'), '7d');++ const summary = await learning.getSummary();+ const recommendation = summary.recommendations.find(item => item.category === 'outcome_alignment');+ if (+ summary.outcome.goal.id !== 'subscribers' || summary.outcome.observed !== 25 ||+ summary.outcome.progressPercent !== 62.5 || summary.outcome.economics.roi !== 150 ||+ !recommendation || recommendation.status !== 'pending' || recommendation.proposedChange.autoApply !== false+ ) {+ throw new Error('Outcome evidence did not produce the expected goal scorecard and approval-gated recommendation');+ }++ const analytics = new AnalyticsOptimizationAgent(db, { getYouTubeAuth: () => ({}) });+ analytics.youtubeAnalytics = {+ reports: {+ query: async ({ metrics }) => {+ if (metrics.includes('estimatedRevenue')) throw new Error('not monetized');+ return { data: { rows: [[7, 2]] } };+ }+ }+ };+ const outcomes = await analytics.getOutcomeAnalytics('outcome-video', '2026-08-01', '2026-08-07');+ if (!outcomes.subscribersAvailable || outcomes.netSubscribers !== 5 || outcomes.revenueAvailable || outcomes.estimatedRevenue !== null) {+ throw new Error('Unavailable monetization evidence was converted into a false zero');+ }+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }++ this.logger.info('Outcome and ROI Studio test completed successfully');+ }+async testSceneAwareRetentionStudio() {const fs = require('fs').promises;const os = require('os');diff --git a/utils/autonomous-channel-operator.js b/utils/autonomous-channel-operator.jsindex a2e8236..36f7f6e 100644--- a/utils/autonomous-channel-operator.js+++ b/utils/autonomous-channel-operator.js@@ -134,6 +134,7 @@ class AutonomousChannelOperator {strategyContext: {angle: item.angle,rationale: item.rationale,+ pillar: item.pillar,audience: strategy.audience,objective: strategy.objective,valueProposition: strategy.value_proposition,diff --git a/utils/channel-learning-engine.js b/utils/channel-learning-engine.jsindex 1c3d085..99929ca 100644--- a/utils/channel-learning-engine.js+++ b/utils/channel-learning-engine.js@@ -10,7 +10,7 @@ class ChannelLearningEngine {}async capture(performanceReport, context = {}, measurementWindow = 'rolling') {- const metrics = this.normalizeMetrics(performanceReport);+ const metrics = this.normalizeMetrics(performanceReport, context);const attributes = this.extractAttributes(performanceReport, context);const prior = (await this.db.listPerformanceSnapshots({measurementWindow,@@ -42,20 +42,57 @@ class ChannelLearningEngine {return snapshot;}- normalizeMetrics(report) {+ normalizeMetrics(report, context = {}) {const analytics = report.analytics || {};const views = analytics.views || {};const watchTime = analytics.watchTime || {};const engagement = analytics.engagement || {};+ const outcomes = analytics.outcomes || {};+ const impressions = this.number(views.totalImpressions || report.thumbnailMetrics?.impressions);+ const totalViews = this.number(views.totalViews);+ const watchMinutes = this.number(watchTime.totalWatchTime);+ const netSubscribers = outcomes.subscribersAvailable ? this.optionalNumber(outcomes.netSubscribers) : null;+ const estimatedRevenue = outcomes.revenueAvailable ? this.optionalNumber(outcomes.estimatedRevenue) : null;+ const cost = context.productionCost || {};+ const productionCost = this.optionalNumber(cost.amount);+ const revenueCurrency = outcomes.currency || null;+ const costCurrency = cost.currency || null;+ const currencyCompatible = productionCost === 0 || (+ revenueCurrency && costCurrency && String(revenueCurrency).toUpperCase() === String(costCurrency).toUpperCase()+ );return {- views: this.number(views.totalViews),- impressions: this.number(views.totalImpressions || report.thumbnailMetrics?.impressions),+ views: totalViews,+ impressions,ctr: this.number(report.thumbnailMetrics?.clickThroughRate ?? views.averageCTR),retention: this.number(watchTime.averageViewPercentage),averageViewDuration: this.number(watchTime.averageViewDuration),- watchMinutes: this.number(watchTime.totalWatchTime),+ watchMinutes,+ watchHours: Number((watchMinutes / 60).toFixed(3)),engagementRate: this.number(engagement.engagementRate),- performanceScore: this.number(report.performance?.score)+ performanceScore: this.number(report.performance?.score),+ subscribersGained: outcomes.subscribersAvailable ? this.optionalNumber(outcomes.subscribersGained) : null,+ subscribersLost: outcomes.subscribersAvailable ? this.optionalNumber(outcomes.subscribersLost) : null,+ netSubscribers,+ estimatedRevenue,+ revenueCurrency,+ monetizedPlaybacks: outcomes.revenueAvailable ? this.optionalNumber(outcomes.monetizedPlaybacks) : null,+ playbackBasedCpm: outcomes.revenueAvailable ? this.optionalNumber(outcomes.playbackBasedCpm) : null,+ subscribersPerThousandImpressions: netSubscribers !== null && impressions > 0+ ? Number(((netSubscribers / impressions) * 1000).toFixed(3))+ : null,+ watchHoursPerThousandViews: totalViews > 0 ? Number((((watchMinutes / 60) / totalViews) * 1000).toFixed(3)) : null,+ revenuePerThousandViews: estimatedRevenue !== null && totalViews > 0+ ? Number(((estimatedRevenue / totalViews) * 1000).toFixed(3))+ : null,+ productionCost,+ costCurrency,+ costComplete: cost.complete === true,+ netRevenue: estimatedRevenue !== null && productionCost !== null && cost.complete === true && currencyCompatible+ ? Number((estimatedRevenue - productionCost).toFixed(3))+ : null,+ roi: estimatedRevenue !== null && productionCost !== null && productionCost > 0 && cost.complete === true && currencyCompatible+ ? Number((((estimatedRevenue - productionCost) / productionCost) * 100).toFixed(1))+ : null};}@@ -67,6 +104,7 @@ class ChannelLearningEngine {const hook = this.text(script.hook || script.introduction || '');return {topic: strategy.topic || '',+ pillar: strategy.contentPillar || strategy.pillar || 'unknown',surface: context.contentFormat === 'short' ? 'shorts' : 'long_form',format: context.contentFormat === 'short'? 'shorts'@@ -77,21 +115,29 @@ class ChannelLearningEngine {thumbnailStyle: this.slug(thumbnail.concept?.composition || thumbnail.concept?.style || thumbnail.style || 'unknown'),+ provider: context.productionCost?.providers?.length === 1 ? this.slug(context.productionCost.providers[0]) : 'mixed_or_unknown',source: strategy.planRationale ? 'autonomous_operator' : 'manual'};}calculateBaseline(snapshots) {- const keys = ['views', 'impressions', 'ctr', 'retention', 'averageViewDuration', 'watchMinutes', 'engagementRate', 'performanceScore'];+ const keys = [+ 'views', 'impressions', 'ctr', 'retention', 'averageViewDuration', 'watchMinutes', 'watchHours',+ 'engagementRate', 'performanceScore', 'netSubscribers', 'subscribersPerThousandImpressions',+ 'estimatedRevenue', 'revenuePerThousandViews', 'productionCost', 'netRevenue', 'roi'+ ];return Object.fromEntries(keys.map(key => [key, this.median(- snapshots.map(snapshot => this.number(snapshot.metrics?.[key])).filter(value => Number.isFinite(value))+ snapshots.map(snapshot => this.optionalNumber(snapshot.metrics?.[key])).filter(value => value !== null))]));}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];+ const numericValue = this.optionalNumber(value);+ const reference = this.optionalNumber(baseline[key]);+ return [key, numericValue !== null && reference !== null && reference !== 0+ ? Number((((numericValue - reference) / Math.abs(reference)) * 100).toFixed(1))+ : null];}));}@@ -102,13 +148,17 @@ class ChannelLearningEngine {}async refreshRecommendations() {- const all = await this.db.listPerformanceSnapshots({ reliableOnly: true });+ const [all, strategy] = await Promise.all([+ this.db.listPerformanceSnapshots({ reliableOnly: true }),+ this.db.getChannelStrategy ? this.db.getChannelStrategy() : Promise.resolve(null)+ ]);const snapshots = this.preferredSnapshotPerVideo(all);if (snapshots.length < 2) return [];const candidates = [...this.buildDimensionRecommendations(snapshots),- ...this.buildChannelRecommendations(snapshots)+ ...this.buildChannelRecommendations(snapshots),+ ...this.buildOutcomeRecommendations(snapshots, strategy)];const saved = [];for (const candidate of candidates) {@@ -201,11 +251,54 @@ class ChannelLearningEngine {return recommendations;}+ buildOutcomeRecommendations(snapshots, strategy = {}) {+ const goal = this.outcomeGoal(strategy);+ if (!goal || snapshots.length < 4) return [];+ const eligible = snapshots.filter(snapshot => this.outcomeMetricValue(snapshot, goal) !== null);+ if (eligible.length < 4) return [];+ const candidates = [];+ for (const dimension of ['pillar', 'format']) {+ const groups = new Map();+ for (const snapshot of eligible) {+ const value = snapshot.contentAttributes?.[dimension];+ const metric = this.outcomeMetricValue(snapshot, goal);+ if (!value || value === 'unknown' || value === 'mixed_or_unknown' || metric === null) 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) continue;+ const best = ranked[0];+ const weakest = ranked.at(-1);+ const meaningfulDifference = best.average - weakest.average;+ const relativeDifference = Math.abs(weakest.average) > 0+ ? meaningfulDifference / Math.abs(weakest.average)+ : best.average > 0 ? 1 : 0;+ if (meaningfulDifference <= 0 || relativeDifference < 0.2) continue;+ candidates.push({+ category: 'outcome_alignment',+ title: `Allocate more ${dimension} capacity to ${this.readable(best.value)}`,+ rationale: `${this.readable(best.value)} averaged ${this.formatOutcome(best.average, goal)} across ${best.count} videos versus ${this.formatOutcome(weakest.average, goal)} for ${this.readable(weakest.value)}, aligned to the configured ${goal.label.toLowerCase()} goal.`,+ evidence: { primaryKpi: goal.id, metric: goal.metric, dimension, best, weakest, minimumSamplesPerGroup: 2 },+ proposedChange: {+ target: 'future_plans', dimension, prefer: best.value, deprioritize: weakest.value,+ primaryKpi: goal.id, autoApply: false+ },+ confidence: best.count >= 4 && weakest.count >= 4 ? 'high' : 'medium'+ });+ }+ return candidates;+ }+async getSummary() {- const [snapshots, recommendations, retentionSnapshots] = await Promise.all([+ const [snapshots, recommendations, retentionSnapshots, strategy] = await Promise.all([this.db.listPerformanceSnapshots({ reliableOnly: true }),this.db.listLearningRecommendations({ limit: 50 }),- this.db.listRetentionSnapshots ? this.db.listRetentionSnapshots({ limit: 12 }) : Promise.resolve([])+ this.db.listRetentionSnapshots ? this.db.listRetentionSnapshots({ limit: 12 }) : Promise.resolve([]),+ this.db.getChannelStrategy ? this.db.getChannelStrategy() : Promise.resolve(null)]);const preferred = this.preferredSnapshotPerVideo(snapshots);return {@@ -221,6 +314,7 @@ class ChannelLearningEngine {pendingCount: recommendations.filter(item => item.status === 'pending').length,lastMeasuredAt: snapshots[0]?.measuredAt || null,evidencePolicy: 'Only real YouTube analytics are eligible; simulated fallbacks are excluded.',+ outcome: this.buildOutcomeSummary(preferred, strategy),retention: {snapshotCount: retentionSnapshots.length,longFormCount: retentionSnapshots.filter(item => item.surface === 'long_form').length,@@ -230,6 +324,114 @@ class ChannelLearningEngine {};}+ outcomeGoal(strategy = {}) {+ if (!strategy) return null;+ const definitions = {+ views: { id: 'views', metric: 'views', label: 'Views', unit: 'count', aggregation: 'sum' },+ watch_hours: { id: 'watch_hours', metric: 'watchHours', label: 'Watch hours', unit: 'hours', aggregation: 'sum' },+ subscribers: { id: 'subscribers', metric: 'netSubscribers', label: 'Net subscribers', unit: 'count', aggregation: 'sum' },+ engagement: { id: 'engagement', metric: 'engagementRate', label: 'Engagement rate', unit: 'percent', aggregation: 'average' },+ revenue: { id: 'revenue', metric: 'estimatedRevenue', label: 'Estimated revenue', unit: 'currency', aggregation: 'sum' }+ };+ const definition = definitions[strategy.primary_kpi] || definitions.views;+ return {+ ...definition,+ targetValue: this.optionalNumber(strategy.target_value),+ windowDays: Math.max(7, Math.min(365, Number(strategy.target_window_days || 28))),+ currency: String(strategy.outcome_currency || 'USD').toUpperCase(),+ monthlyBudget: this.optionalNumber(strategy.monthly_budget),+ description: strategy.success_metric || ''+ };+ }++ buildOutcomeSummary(snapshots = [], strategy = null) {+ const goal = this.outcomeGoal(strategy);+ if (!goal) {+ return { configured: false, available: false, goal: null, evidencePolicy: 'Configure a channel strategy to activate outcome tracking.' };+ }+ const cutoff = Date.now() - goal.windowDays * 86400000;+ const recent = snapshots.filter(snapshot => {+ const measured = new Date(snapshot.measuredAt || snapshot.measured_at || 0).getTime();+ return Number.isFinite(measured) && measured >= cutoff;+ });+ const values = recent+ .map(snapshot => this.outcomeMetricValue(snapshot, goal))+ .filter(value => value !== null);+ const observed = values.length+ ? goal.aggregation === 'average' ? this.average(values) : values.reduce((sum, value) => sum + value, 0)+ : null;+ const progressPercent = observed !== null && goal.targetValue !== null && goal.targetValue > 0+ ? Number(Math.max(0, Math.min(999, (observed / goal.targetValue) * 100)).toFixed(1))+ : null;+ const sumAvailable = key => {+ const available = recent.map(snapshot => this.optionalNumber(snapshot.metrics?.[key])).filter(value => value !== null);+ return { value: available.length ? available.reduce((sum, value) => sum + value, 0) : null, count: available.length };+ };+ const subscribers = sumAvailable('netSubscribers');+ const watchHours = sumAvailable('watchHours');+ const revenueValues = recent+ .filter(snapshot => String(snapshot.metrics?.revenueCurrency || 'USD').toUpperCase() === goal.currency)+ .map(snapshot => this.optionalNumber(snapshot.metrics?.estimatedRevenue)).filter(value => value !== null);+ const revenue = { value: revenueValues.length ? revenueValues.reduce((sum, value) => sum + value, 0) : null, count: revenueValues.length };+ const costValues = recent+ .filter(snapshot => this.optionalNumber(snapshot.metrics?.productionCost) === 0 || String(snapshot.metrics?.costCurrency || '').toUpperCase() === goal.currency)+ .map(snapshot => this.optionalNumber(snapshot.metrics?.productionCost)).filter(value => value !== null);+ const cost = { value: costValues.length ? costValues.reduce((sum, value) => sum + value, 0) : null, count: costValues.length };+ const costsComplete = recent.length > 0 && cost.count === recent.length && recent.every(snapshot => snapshot.metrics?.costComplete === true);+ const roi = revenue.count === recent.length && costsComplete && cost.value > 0+ ? Number((((revenue.value - cost.value) / cost.value) * 100).toFixed(1))+ : null;+ const breakdowns = {};+ for (const dimension of ['pillar', 'format', 'provider']) {+ const groups = new Map();+ for (const snapshot of recent) {+ const name = snapshot.contentAttributes?.[dimension];+ const value = this.outcomeMetricValue(snapshot, goal);+ if (!name || name === 'unknown' || name === 'mixed_or_unknown' || value === null) continue;+ if (!groups.has(name)) groups.set(name, []);+ groups.get(name).push(value);+ }+ breakdowns[dimension] = [...groups.entries()]+ .map(([name, groupValues]) => ({+ name,+ count: groupValues.length,+ average: Number(this.average(groupValues).toFixed(3)),+ total: Number(groupValues.reduce((sum, value) => sum + value, 0).toFixed(3))+ }))+ .sort((a, b) => b.average - a.average);+ }+ return {+ configured: true,+ available: observed !== null,+ goal,+ observed: observed === null ? null : Number(observed.toFixed(3)),+ formattedObserved: observed === null ? 'Unavailable' : this.formatOutcome(observed, goal),+ progressPercent,+ snapshotCount: recent.length,+ measuredVideoCount: values.length,+ economics: {+ currency: goal.currency,+ netSubscribers: subscribers.value,+ watchHours: watchHours.value === null ? null : Number(watchHours.value.toFixed(3)),+ estimatedRevenue: revenue.value === null ? null : Number(revenue.value.toFixed(3)),+ knownProductionCost: cost.value === null ? null : Number(cost.value.toFixed(3)),+ costsComplete,+ roi,+ monthlyBudget: goal.monthlyBudget,+ budgetUsedPercent: goal.monthlyBudget > 0 && cost.value !== null+ ? Number(((cost.value / goal.monthlyBudget) * 100).toFixed(1))+ : null+ },+ coverage: {+ subscribers: { measured: subscribers.count, total: recent.length },+ revenue: { measured: revenue.count, total: recent.length },+ cost: { measured: cost.count, total: recent.length }+ },+ breakdowns,+ evidencePolicy: 'Only real YouTube measurements are included. Missing subscriber, revenue, or cost evidence remains unavailable and is never converted to zero.'+ };+ }+captureRetention(retentionReport, context = {}, measurementWindow = 'rolling', exposure = {}) {return this.sceneRetention.capture(retentionReport, context, measurementWindow, exposure);}@@ -268,7 +470,7 @@ class ChannelLearningEngine {}median(values) {- if (!values.length) return 0;+ if (!values.length) return null;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;@@ -287,6 +489,32 @@ class ChannelLearningEngine {return Number.isFinite(number) ? number : 0;}+ optionalNumber(value) {+ if (value === null || value === undefined || value === '') return null;+ const number = Number(value);+ return Number.isFinite(number) ? number : null;+ }++ outcomeMetricValue(snapshot, goal) {+ if (goal.id === 'revenue' && String(snapshot.metrics?.revenueCurrency || 'USD').toUpperCase() !== goal.currency) {+ return null;+ }+ return this.optionalNumber(snapshot.metrics?.[goal.metric]);+ }++ formatOutcome(value, goal) {+ if (goal.unit === 'currency') {+ try {+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: goal.currency, maximumFractionDigits: 2 }).format(value);+ } catch (_error) {+ return `${goal.currency} ${Number(value).toFixed(2)}`;+ }+ }+ if (goal.unit === 'percent') return `${Number(value).toFixed(1)}%`;+ if (goal.unit === 'hours') return `${Number(value).toFixed(1)} hours`;+ return new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 }).format(value);+ }+text(value) {if (typeof value === 'string') return value;if (Array.isArray(value)) return value.map(item => this.text(item)).join(' ');