🎬 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
Release v2.8 research provenance desk
darkzOGxc79097b0a605
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b8cc2b..960e1f5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,15 @@## Unreleased+## v2.8.0 — 2026-08-21++- Added a persistent Research & Provenance Desk with source metadata, claim-to-source links, reviewer status, notes, and evidence summaries+- Preserved exact YouTube trend and competitor source URLs through autonomous planning and into script generation+- Added AI-declared factual claims that may reference only sources supplied by the research stage+- Made unresolved claims blocking; supported claims require verified evidence and claim waivers require reviewer notes+- Added Review Studio controls for adding and reviewing sources and claims, including official, article, video, dataset, asset-license, and other evidence types+- Added realistic altered or synthetic media disclosure and passed the reviewed value into YouTube upload metadata+## v2.7.0 — 2026-08-21- Added persistent per-stage generation checkpoints with artifact validation, bounded retry-safe backoff, and resume-from-first-incomplete behaviordiff --git a/README.md b/README.mdindex 37d3c38..8b32108 100644--- a/README.md+++ b/README.md@@ -8,15 +8,15 @@ Research topics → write scripts → generate narration and visuals → assembl[](LICENSE)[](package.json)-## What's new in version 2.7.0+## What's new in version 2.8.0-Version 2.7 makes long-running production recoverable instead of disposable:+Version 2.8 adds an evidence-first Research & Provenance Desk to every production:-- **Resumable generation:** strategy, script, thumbnail, SEO, production, and quality-review stages persist as checkpoints and resume from the first unfinished stage.-- **Selective retry controls:** choose exactly which stage to regenerate while reusing earlier verified artifacts and tracking saved stages in the dashboard.-- **Operator-run recovery:** interrupted autonomous runs continue from their saved research, editorial plan, ideas, and generation jobs.-- **Duplicate-upload protection:** YouTube video IDs are persisted immediately; known uploads are reconciled, while uncertain outcomes stop for manual verification instead of uploading twice.-- **Bounded transient retries:** retry-safe provider and network failures receive one backoff retry without weakening approval, rights, readiness, or publishing gates.+- **Source-aware research:** YouTube trend and competitor signals retain their exact video URLs, titles, publishers, and publication dates through autonomous planning.+- **Claim ledger:** AI scripts declare externally verifiable claims and connect them only to sources supplied by the research stage.+- **Evidence review:** Review Studio lets an operator add and verify sources, mark claims supported, unsupported, or explicitly waived, and record reviewer notes.+- **Fail-closed approval:** unresolved claims block approval; a supported claim must link to at least one reviewer-verified source, and a waiver requires a note.+- **Disclosure handoff:** realistic altered or synthetic media can be declared in Review Studio and is passed to YouTube's upload metadata.See the complete release history in [CHANGELOG.md](CHANGELOG.md).@@ -56,6 +56,14 @@ Every generation stage writes a local SQLite checkpoint. If a provider times outAutonomous Operator runs preserve their research and editorial plan, so **Resume run** continues unfinished plan items instead of researching and generating completed videos again. Publishing remains fail-closed: if an upload may have reached YouTube but no video ID was returned, Lumen requires channel reconciliation before another upload attempt.+### Review research and provenance++Every production has an **Evidence desk** inside Review Studio. Autonomous research carries exact YouTube source metadata into the production, while AI-generated scripts list the factual claims that need review. Add any official articles, datasets, asset licenses, or other evidence that the script needs, verify each source, and connect it to the claims it supports.++A claim can be approved only when it links to a verified source. Unsupported claims remain blocking, and an intentional waiver requires a reviewer note. Productions with no externally verifiable factual claims are marked as not requiring provenance review. The separate factual-review and media-rights attestations remain required before scheduling.++Use the altered or synthetic media control only when the video contains realistic content that requires YouTube disclosure. The selected value is preserved in the publishing queue and included in the YouTube upload request.+### What you need- Node.js 18+diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.jsindex f45abc2..e529606 100644--- a/agents/content-strategy-agent.js+++ b/agents/content-strategy-agent.js@@ -60,11 +60,14 @@ class ContentStrategyAgent {});return response.data.items.map(video => ({+ videoId: video.id,title: video.snippet.title,tags: video.snippet.tags || [],viewCount: parseInt(video.statistics?.viewCount, 10) || 0,category: video.snippet.categoryId,- publishedAt: video.snippet.publishedAt+ publishedAt: video.snippet.publishedAt,+ publisher: video.snippet.channelTitle || 'YouTube',+ url: `https://www.youtube.com/watch?v=${video.id}`}));} catch (error) {this.logger.error('Failed to fetch YouTube trends:', error);@@ -138,16 +141,23 @@ class ContentStrategyAgent {// Extract topics from titleconst keywords = this.extractKeywords(title);keywords.forEach(keyword => {- if (!topics[keyword]) topics[keyword] = { count: 0, views: 0 };+ if (!topics[keyword]) topics[keyword] = { count: 0, views: 0, evidence: [] };topics[keyword].count++;topics[keyword].views += views;+ topics[keyword].evidence.push({+ url: `https://www.youtube.com/watch?v=${video.id}`,+ title: video.snippet.title,+ publisher: video.snippet.channelTitle || 'Configured competitor channel',+ publishedAt: video.snippet.publishedAt,+ sourceType: 'video'+ });});});const topTopics = Object.entries(topics).sort((a, b) => b[1].views - a[1].views).slice(0, 10)- .map(([topic, data]) => ({ topic, avgViews: data.views / data.count }));+ .map(([topic, data]) => ({ topic, avgViews: data.views / data.count, evidence: data.evidence.slice(0, 5) }));return {topTopics,@@ -175,24 +185,32 @@ class ContentStrategyAgent {const keywords = this.extractKeywords(trend.title);keywords.forEach(keyword => {if (!mergedTopics.has(keyword)) {- mergedTopics.set(keyword, { score: 0, sources: [] });+ mergedTopics.set(keyword, { score: 0, sources: [], evidence: [] });}const topic = mergedTopics.get(keyword);topic.score += trend.viewCount / 1000000; // Normalize by millionstopic.sources.push('trending');+ topic.evidence.push({+ url: trend.url,+ title: trend.title,+ publisher: trend.publisher,+ publishedAt: trend.publishedAt,+ sourceType: 'video'+ });});});// Add competitor topicscompetitors.forEach(competitor => {if (competitor.topPerformingTopics) {- competitor.topPerformingTopics.forEach(({ topic, avgViews }) => {+ competitor.topPerformingTopics.forEach(({ topic, avgViews, evidence = [] }) => {if (!mergedTopics.has(topic)) {- mergedTopics.set(topic, { score: 0, sources: [] });+ mergedTopics.set(topic, { score: 0, sources: [], evidence: [] });}const topicData = mergedTopics.get(topic);topicData.score += avgViews / 100000; // NormalizetopicData.sources.push('competitor');+ topicData.evidence.push(...evidence);});}});@@ -200,6 +218,10 @@ class ContentStrategyAgent {// Convert to array and sort by scorereturn Array.from(mergedTopics.entries()).map(([topic, data]) => ({ topic, ...data }))+ .map(item => ({+ ...item,+ evidence: [...new Map(item.evidence.filter(source => source.url).map(source => [source.url, source])).values()].slice(0, 5)+ })).sort((a, b) => b.score - a.score).slice(0, 50);}@@ -269,8 +291,12 @@ class ContentStrategyAgent {const signals = this.trendingTopics.slice(0, 15).map(item => ({topic: item.topic,score: Number(item.score || 0),- sources: [...new Set(item.sources || [])]+ sources: [...new Set(item.sources || [])],+ evidence: item.evidence || []}));+ const sourceCatalog = [...new Map(+ signals.flatMap(signal => signal.evidence || []).map(source => [source.url, source])+ ).values()].slice(0, 30);const signalSources = new Set(signals.flatMap(signal => signal.sources));const researchSources = [...(signalSources.has('trending') ? ['YouTube most-popular videos'] : []),@@ -282,6 +308,7 @@ class ContentStrategyAgent {generatedAt: new Date().toISOString(),sources: researchSources.length ? researchSources : ['No usable live signals returned; evergreen strategy fallback'],signals,+ sourceCatalog,recentTopics: recentRows.map(row => row.topic),competitorChannelsAnalyzed: this.competitorData.length,approvedLearnings: approvedLearnings.map(item => ({@@ -293,10 +320,10 @@ class ContentStrategyAgent {};let plan = await this.generateAutonomousPlanWithAI(channelStrategy, research, targetCount);- plan = this.normalizeAutonomousPlan(plan, channelStrategy, targetCount);+ plan = this.normalizeAutonomousPlan(plan, channelStrategy, targetCount, research);if (plan.length < targetCount) {const fallback = this.buildFallbackAutonomousPlan(channelStrategy, research, targetCount);- plan = this.normalizeAutonomousPlan([...plan, ...fallback], channelStrategy, targetCount);+ plan = this.normalizeAutonomousPlan([...plan, ...fallback], channelStrategy, targetCount, research);}return { research, plan };@@ -307,7 +334,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"}]+[{"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"]}]Channel objective: ${channelStrategy.objective}Audience: ${channelStrategy.audience}@@ -318,10 +345,11 @@ Preferred length: ${channelStrategy.default_length}Success metric: ${channelStrategy.success_metric || 'not specified'}Constraints: ${channelStrategy.constraints || 'none'}Research signals: ${JSON.stringify(research.signals)}+Allowed source catalog: ${JSON.stringify(research.sourceCatalog)}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. Apply only the supplied approved learnings; pending or rejected recommendations are not authorized. Prefer evergreen topics when the supplied signals are weak.`;+Do not invent trend data, statistics, sources, URLs, or factual claims. Use only exact URLs from the supplied source catalog. 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 });@@ -351,13 +379,15 @@ Do not invent trend data, statistics, sources, or factual claims. Apply only the? `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+ length: channelStrategy.default_length,+ sourceUrls: research.signals.find(signal => signal.topic === topic)?.evidence?.map(source => source.url) || []}));}- normalizeAutonomousPlan(plan, channelStrategy, targetCount) {+ normalizeAutonomousPlan(plan, channelStrategy, targetCount, research = {}) {const 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 seen = new Set();return plan.map(item => ({@@ -369,7 +399,10 @@ Do not invent trend data, statistics, sources, or factual claims. Apply only the: channelStrategy.default_format,length: lengths.has(String(item.length || '').toLowerCase())? String(item.length).toLowerCase()- : channelStrategy.default_length+ : channelStrategy.default_length,+ sourceUrls: [...new Set((Array.isArray(item.sourceUrls) ? item.sourceUrls : [])+ .map(url => String(url))+ .filter(url => allowedSourceUrls.has(url)))]})).filter(item => {const key = item.topic.toLowerCase();diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.jsindex 3c822ef..f82ae28 100644--- a/agents/publishing-scheduling-agent.js+++ b/agents/publishing-scheduling-agent.js@@ -72,7 +72,8 @@ class PublishingSchedulingAgent {thumbnail: productionData.assets.thumbnail,video: productionData.assets.finalVideo,captions: productionData.assets.captions,- privacyStatus: productionData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'+ privacyStatus: productionData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',+ containsSyntheticMedia: productionData.containsSyntheticMedia === true},createdAt: new Date().toISOString()};@@ -103,6 +104,15 @@ class PublishingSchedulingAgent {throw error;}}+ if (this.db.getProductionBundle) {+ const bundle = await this.db.getProductionBundle(contentId);+ if (bundle && !['verified', 'not_required'].includes(bundle.provenance?.status || 'not_required')) {+ const error = new Error('Publishing is blocked until every factual claim is supported or explicitly waived');+ error.status = 409;+ error.code = 'PROVENANCE_BLOCKED';+ throw error;+ }+ }this.logger.info(`Publishing content: ${contentId}`);let scheduleEntry = this.publishQueue.find(entry =>@@ -188,7 +198,8 @@ class PublishingSchedulingAgent {status: {privacyStatus: metadata.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',publishAt: scheduleEntry.publishTime,- selfDeclaredMadeForKids: false+ selfDeclaredMadeForKids: false,+ containsSyntheticMedia: metadata.containsSyntheticMedia === true}};diff --git a/agents/script-writer-agent.js b/agents/script-writer-agent.jsindex bd8c424..8e80165 100644--- a/agents/script-writer-agent.js+++ b/agents/script-writer-agent.js@@ -78,6 +78,7 @@ class ScriptWriterAgent {tone: template.tone,pacing: template.pacing,keywords: strategy.keywords,+ claims: [],metadata: {strategy: strategy,generatedAt: new Date().toISOString(),@@ -113,7 +114,10 @@ Return only valid JSON with this exact shape:"sections": [{ "title": "section title", "content": ["spoken script bullet"], "duration": 60 }],- "cta": "clear call to action"+ "cta": "clear call to action",+ "claims": [+ { "text": "specific factual claim a reviewer must verify", "riskLevel": "standard|high", "sourceUrls": ["exact supplied source URL"] }+ ]}Topic: ${strategy.topic}@@ -130,7 +134,8 @@ Editorial rationale: ${strategy.planRationale || 'fit the selected topic and audChannel constraints: ${strategy.channelConstraints || 'none beyond the factual-safety rules below'}Preferred call to action: ${strategy.callToAction || 'invite the viewer to subscribe'}Keywords: ${(strategy.keywords || []).join(', ')}-Avoid fabricated statistics, unsupported claims, and fake urgency.`;+Research sources: ${JSON.stringify(strategy.researchSources || [])}+Avoid fabricated statistics, unsupported claims, and fake urgency. List every externally verifiable factual claim in claims. Use only exact URLs from Research sources; use an empty sourceUrls array when the supplied sources do not support a claim.`;try {const response = await this.aiTextService.generateText(prompt, {@@ -159,6 +164,7 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;tone: template.tone,pacing: template.pacing,keywords: strategy.keywords || [],+ claims: this.normalizeAIClaims(parsed.claims, strategy.researchSources || []),metadata: {strategy,generatedAt: new Date().toISOString(),@@ -225,6 +231,18 @@ Avoid fabricated statistics, unsupported claims, and fake urgency.`;.filter(section => section.title && section.content.length > 0);}+ normalizeAIClaims(claims, sources) {+ if (!Array.isArray(claims)) return [];+ const allowedUrls = new Set((sources || []).map(source => source.url));+ return claims.slice(0, 25).map(item => ({+ text: String(item?.text || item?.claim || '').trim().slice(0, 1000),+ riskLevel: item?.riskLevel === 'high' ? 'high' : 'standard',+ sourceUrls: [...new Set((Array.isArray(item?.sourceUrls) ? item.sourceUrls : [])+ .map(url => String(url))+ .filter(url => allowedUrls.has(url)))]+ })).filter(item => item.text);+ }+normalizeAICTA(cta, strategy) {if (cta && typeof cta === 'object') {return {diff --git a/dashboard/app.js b/dashboard/app.jsindex 90abcb7..623a261 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -462,6 +462,67 @@ function switchView(view) {location.hash = view;}+function selectOptions(options, selected) {+ return options.map(([value, label]) =>+ `<option value="${escapeHTML(value)}" ${value === selected ? 'selected' : ''}>${escapeHTML(label)}</option>`+ ).join('');+}++function renderSourceEditor(source = {}, disabled = false) {+ return `<article class="provenance-item" data-provenance-source data-id="${escapeHTML(source.id || '')}" data-published-at="${escapeHTML(source.publishedAt || '')}" data-accessed-at="${escapeHTML(source.accessedAt || '')}">+ <div class="provenance-item-heading"><strong>Research source</strong><button type="button" class="text-button danger-text" data-remove-provenance ${disabled ? 'disabled' : ''}>Remove</button></div>+ <label><span>URL</span><input data-field="url" type="url" value="${escapeHTML(source.url || '')}" placeholder="https://..." required ${disabled ? 'disabled' : ''}></label>+ <div class="form-grid two">+ <label><span>Title</span><input data-field="title" value="${escapeHTML(source.title || '')}" maxlength="300" ${disabled ? 'disabled' : ''}></label>+ <label><span>Publisher</span><input data-field="publisher" value="${escapeHTML(source.publisher || '')}" maxlength="200" ${disabled ? 'disabled' : ''}></label>+ <label><span>Type</span><select data-field="sourceType" ${disabled ? 'disabled' : ''}>${selectOptions([+ ['official', 'Official source'], ['article', 'Article'], ['video', 'Video'], ['dataset', 'Dataset'], ['asset', 'Asset or license'], ['other', 'Other']+ ], source.sourceType || 'other')}</select></label>+ <label><span>Review status</span><select data-field="status" ${disabled ? 'disabled' : ''}>${selectOptions([+ ['pending', 'Pending review'], ['verified', 'Verified'], ['rejected', 'Rejected']+ ], source.status || 'pending')}</select></label>+ </div>+ <label><span>Evidence notes</span><textarea data-field="notes" rows="2" maxlength="1000" ${disabled ? 'disabled' : ''}>${escapeHTML(source.notes || '')}</textarea></label>+ ${source.url ? `<a class="source-link" href="${escapeHTML(source.url)}" target="_blank" rel="noopener">Open source ↗</a>` : ''}+ </article>`;+}++function renderClaimEditor(claim = {}, sources = [], disabled = false) {+ const linked = new Set(claim.sourceIds || []);+ return `<article class="provenance-item ${claim.riskLevel === 'high' ? 'high-risk' : ''}" data-provenance-claim data-id="${escapeHTML(claim.id || '')}">+ <div class="provenance-item-heading"><strong>Factual claim</strong><button type="button" class="text-button danger-text" data-remove-provenance ${disabled ? 'disabled' : ''}>Remove</button></div>+ <label><span>Claim</span><textarea data-field="text" rows="3" maxlength="1000" required ${disabled ? 'disabled' : ''}>${escapeHTML(claim.text || '')}</textarea></label>+ <div class="form-grid two">+ <label><span>Risk</span><select data-field="riskLevel" ${disabled ? 'disabled' : ''}>${selectOptions([+ ['standard', 'Standard'], ['high', 'High risk']+ ], claim.riskLevel || 'standard')}</select></label>+ <label><span>Resolution</span><select data-field="status" ${disabled ? 'disabled' : ''}>${selectOptions([+ ['pending', 'Pending'], ['supported', 'Supported'], ['unsupported', 'Unsupported'], ['waived', 'Waived with note']+ ], claim.status || 'pending')}</select></label>+ </div>+ <fieldset class="source-checklist" ${disabled ? 'disabled' : ''}><legend>Supporting sources</legend>+ ${sources.length ? sources.map(source => `<label><input type="checkbox" data-claim-source="${escapeHTML(source.id)}" ${linked.has(source.id) ? 'checked' : ''}> ${escapeHTML(source.title || source.url)}</label>`).join('') : '<small>Add a source before marking this claim supported.</small>'}+ </fieldset>+ <label><span>Reviewer notes</span><textarea data-field="notes" rows="2" maxlength="1000" placeholder="Required when waived" ${disabled ? 'disabled' : ''}>${escapeHTML(claim.notes || '')}</textarea></label>+ </article>`;+}++function renderProvenanceEditor(provenance = {}, canReview = true) {+ const sources = provenance.sources || [];+ const claims = provenance.claims || [];+ const summary = provenance.summary || {};+ const statusLabel = provenance.status === 'verified' ? 'Evidence verified' : provenance.status === 'not_required' ? 'No claims declared' : `${summary.unresolvedClaims || 0} unresolved`;+ return `<section class="provenance-panel">+ <div class="panel-heading"><div><p class="eyebrow">RESEARCH & PROVENANCE</p><h3>Evidence desk</h3><p>Verify sources, connect every factual claim, and record disclosure before approval.</p></div><span class="status ${provenance.status === 'verified' || provenance.status === 'not_required' ? 'success' : 'warning'}">${escapeHTML(statusLabel)}</span></div>+ <div class="provenance-toolbar"><strong>Sources</strong>${canReview ? '<button type="button" class="text-button" data-add-provenance-source>Add source +</button>' : ''}</div>+ <div id="provenance-sources" class="provenance-list">${sources.map(source => renderSourceEditor(source, !canReview)).join('') || '<p class="empty-inline">No research sources attached.</p>'}</div>+ <div class="provenance-toolbar"><strong>Claims</strong>${canReview ? '<button type="button" class="text-button" data-add-provenance-claim>Add claim +</button>' : ''}</div>+ <div id="provenance-claims" class="provenance-list">${claims.map(claim => renderClaimEditor(claim, sources, !canReview)).join('') || '<p class="empty-inline">No externally verifiable claims declared.</p>'}</div>+ <label class="toggle disclosure-toggle"><input id="contains-synthetic-media" type="checkbox" ${provenance.containsSyntheticMedia ? 'checked' : ''} ${canReview ? '' : 'disabled'}><span></span> Contains realistic altered or synthetic media requiring YouTube disclosure</label>+ ${canReview ? '<button type="button" class="button secondary" data-save-provenance>Save evidence review</button>' : ''}+ </section>`;+}+async function openContent(productionId) {$('#loading').classList.add('active');try {@@ -492,6 +553,7 @@ async function openContent(productionId) {<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>` : ''}+ ${renderProvenanceEditor(item.provenance, canReview)}<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>@@ -503,6 +565,7 @@ async function openContent(productionId) {${canReview ? `<div class="form-actions"><button type="button" class="button primary" data-approve-content="${escapeHTML(item.id)}">Approve & schedule</button><button type="button" class="button secondary" data-save-content="${escapeHTML(item.id)}">Save draft</button><button type="button" class="button danger" data-reject-content="${escapeHTML(item.id)}">Reject</button><button type="button" class="button ghost" data-retry-content="${escapeHTML(item.id)}">Regenerate</button></div>` : `<a class="button secondary" href="${escapeHTML(item.schedule?.youtube_url || '#')}" target="_blank" rel="noopener">Open on YouTube</a>`}</form></div>`;+ $('#content-review-form').dataset.productionId = item.id;$('#content-dialog').showModal();} catch (error) {showToast(error.message, 'error');@@ -535,6 +598,66 @@ function contentFormData() {};}+function provenanceFormData() {+ const sources = $$('[data-provenance-source]').map(item => ({+ id: item.dataset.id,+ url: item.querySelector('[data-field="url"]').value,+ title: item.querySelector('[data-field="title"]').value,+ publisher: item.querySelector('[data-field="publisher"]').value,+ sourceType: item.querySelector('[data-field="sourceType"]').value,+ status: item.querySelector('[data-field="status"]').value,+ notes: item.querySelector('[data-field="notes"]').value,+ publishedAt: item.dataset.publishedAt || null,+ accessedAt: item.dataset.accessedAt || null+ }));+ const claims = $$('[data-provenance-claim]').map(item => ({+ id: item.dataset.id,+ text: item.querySelector('[data-field="text"]').value,+ riskLevel: item.querySelector('[data-field="riskLevel"]').value,+ status: item.querySelector('[data-field="status"]').value,+ notes: item.querySelector('[data-field="notes"]').value,+ sourceIds: [...item.querySelectorAll('[data-claim-source]:checked')].map(input => input.dataset.claimSource)+ }));+ return {+ sources,+ claims,+ containsSyntheticMedia: $('#contains-synthetic-media')?.checked || false+ };+}++function clientId(prefix) {+ const uuid = globalThis.crypto?.randomUUID?.() || `${Date.now()}_${Math.random().toString(16).slice(2)}`;+ return `${prefix}_${uuid}`;+}++function currentSourceOptions() {+ return $$('[data-provenance-source]').map(item => ({+ id: item.dataset.id,+ title: item.querySelector('[data-field="title"]').value || item.querySelector('[data-field="url"]').value || 'New source'+ }));+}++async function persistProvenance(productionId, successMessage = null) {+ $('#loading').classList.add('active');+ try {+ const result = await api(`/api/content/${encodeURIComponent(productionId)}/provenance`, {+ method: 'PUT',+ body: JSON.stringify(provenanceFormData())+ });+ if (successMessage) {+ showToast(successMessage);+ $('#content-dialog').close();+ await openContent(productionId);+ }+ return result;+ } catch (error) {+ showToast(error.message, 'error');+ throw error;+ } finally {+ $('#loading').classList.remove('active');+ }+}+async function mutate(url, method, body, successMessage) {$('#loading').classList.add('active');try {@@ -591,14 +714,47 @@ document.addEventListener('click', async event => {await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});}+ const addSource = event.target.closest('[data-add-provenance-source]');+ if (addSource) {+ const list = $('#provenance-sources');+ list.querySelector('.empty-inline')?.remove();+ list.insertAdjacentHTML('beforeend', renderSourceEditor({ id: clientId('source') }));+ return;+ }++ const addClaim = event.target.closest('[data-add-provenance-claim]');+ if (addClaim) {+ const list = $('#provenance-claims');+ list.querySelector('.empty-inline')?.remove();+ list.insertAdjacentHTML('beforeend', renderClaimEditor({ id: clientId('claim') }, currentSourceOptions()));+ return;+ }++ const removeProvenance = event.target.closest('[data-remove-provenance]');+ if (removeProvenance) {+ removeProvenance.closest('.provenance-item')?.remove();+ return;+ }++ const saveProvenance = event.target.closest('[data-save-provenance]');+ if (saveProvenance) {+ const productionId = $('#content-review-form')?.dataset.productionId;+ if (productionId) await persistProvenance(productionId, 'Evidence review saved.').catch(() => {});+ return;+ }+const save = event.target.closest('[data-save-content]');if (save) {- await mutate(`/api/content/${encodeURIComponent(save.dataset.saveContent)}`, 'PATCH', contentFormData(), 'Draft saved.').catch(() => {});+ try {+ await persistProvenance(save.dataset.saveContent);+ await mutate(`/api/content/${encodeURIComponent(save.dataset.saveContent)}`, 'PATCH', contentFormData(), 'Draft and evidence review saved.');+ } catch (_error) { /* toast already shown */ }}const approve = event.target.closest('[data-approve-content]');if (approve) {try {+ await persistProvenance(approve.dataset.approveContent);await mutate(`/api/content/${encodeURIComponent(approve.dataset.approveContent)}/approve`, 'POST', contentFormData(), 'Content approved and scheduled.');$('#content-dialog').close();} catch (_error) { /* toast already shown */ }diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 4a78fc1..48d61b3 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -87,6 +87,7 @@ h2 { letter-spacing: -.025em; margin-bottom: 0; }.status.needs_review, .status.queued { color: var(--amber); background: rgba(245,185,68,.12); }.status.needs_attention, .status.failed, .status.interrupted, .status.reconciliation_required, .status.rejected { color: #ff8994; background: var(--red-soft); }.status.approved, .status.scheduled, .status.published, .status.completed, .status.passed { color: var(--green); background: rgba(72,213,151,.12); }+.status.success { color: var(--green); background: rgba(72,213,151,.12); }.status.warning, .status.skipped, .status.unverified { color: var(--amber); background: rgba(245,185,68,.12); }.progress { height: 5px; border-radius: 99px; background: #262c35; margin-top: 9px; overflow: hidden; }.progress i { display: block; height: 100%; background: var(--red); border-radius: inherit; }@@ -154,7 +155,7 @@ label small { color: var(--muted); font-weight: 400; }.dialog form { display: grid; gap: 18px; }.dialog-heading { display: flex; align-items: start; justify-content: space-between; }.dialog-heading h2 { font-size: 27px; }-.content-dialog { width: min(980px, calc(100vw - 30px)); }+.content-dialog { width: min(1080px, calc(100vw - 30px)); max-height: calc(100vh - 30px); overflow: auto; }.callout { background: rgba(114,165,255,.08); border: 1px solid rgba(114,165,255,.18); padding: 12px; border-radius: 10px; color: #b9d0fb; font-size: 12px; margin: 0; }.activation-panel { margin-top: 18px; }.activation-panel .callout { margin-bottom: 14px; }@@ -193,6 +194,24 @@ label small { color: var(--muted); font-weight: 400; }.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; }+.provenance-panel { display: grid; gap: 14px; border: 1px solid rgba(72,213,151,.25); background: rgba(72,213,151,.045); border-radius: 12px; padding: 14px; }+.provenance-panel .panel-heading { align-items: flex-start; margin: 0; }+.provenance-panel h3 { font-size: 17px; margin: 2px 0 0; }+.provenance-panel .panel-heading p:not(.eyebrow) { color: var(--muted); font-size: 12px; line-height: 1.45; margin: 6px 0 0; }+.provenance-toolbar, .provenance-item-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }+.provenance-toolbar { border-top: 1px solid var(--line); padding-top: 12px; }+.provenance-list { display: grid; gap: 10px; }+.provenance-item { display: grid; gap: 11px; border: 1px solid var(--line); background: rgba(7,10,14,.44); border-radius: 10px; padding: 12px; }+.provenance-item.high-risk { border-color: rgba(245,185,68,.38); }+.provenance-item-heading strong { font-size: 12px; }+.danger-text { color: #ff8994; }+.source-checklist { display: grid; gap: 7px; border: 1px solid var(--line); border-radius: 9px; padding: 10px 12px; }+.source-checklist legend { color: var(--text); font-size: 11px; font-weight: 700; padding: 0 5px; }+.source-checklist label { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 11px; }+.source-checklist input { width: auto; }+.source-link { color: var(--blue); font-size: 11px; }+.empty-inline { color: var(--muted); font-size: 12px; margin: 0; padding: 10px 0; }+.disclosure-toggle { align-items: flex-start; font-size: 11px; line-height: 1.4; }.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); }diff --git a/database/db.js b/database/db.jsindex fde671f..8bba051 100644--- a/database/db.js+++ b/database/db.js@@ -267,6 +267,18 @@ class Database {updated_at TEXT DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (production_id) REFERENCES productions(id))`,+ `CREATE TABLE IF NOT EXISTS content_provenance (+ production_id TEXT PRIMARY KEY,+ sources TEXT NOT NULL DEFAULT '[]',+ claims TEXT NOT NULL DEFAULT '[]',+ contains_synthetic_media INTEGER DEFAULT 0,+ status TEXT DEFAULT 'not_required',+ summary TEXT NOT NULL DEFAULT '{}',+ reviewed_at TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (production_id) REFERENCES productions(id)+ )`,`CREATE TABLE IF NOT EXISTS channel_profiles (id TEXT PRIMARY KEY,channel_name TEXT,@@ -585,6 +597,7 @@ class Database {'SELECT * FROM publish_schedule WHERE production_id = ? ORDER BY created_at DESC LIMIT 1',[productionId]);+ const provenance = await this.getContentProvenance(productionId);return {...row,assets: JSON.parse(row.assets || '{}'),@@ -595,7 +608,11 @@ class Database {seo: JSON.parse(row.seo || '{}'),editorData: JSON.parse(row.editor_data || '{}'),qualityChecks: JSON.parse(row.quality_checks || '[]'),- schedule: schedule ? { ...schedule, metadata: JSON.parse(schedule.metadata || '{}') } : null+ schedule: schedule ? { ...schedule, metadata: JSON.parse(schedule.metadata || '{}') } : null,+ provenance: provenance || {+ sources: [], claims: [], containsSyntheticMedia: false, status: 'not_required',+ summary: { sourceCount: 0, verifiedSources: 0, claimCount: 0, resolvedClaims: 0, highRiskClaims: 0, unresolvedClaims: 0 }+ }};}@@ -779,6 +796,41 @@ class Database {return this.getProductionBundle(productionId);}+ async saveContentProvenance(productionId, provenance = {}) {+ await this.executeQuery(+ `INSERT INTO content_provenance (+ production_id, sources, claims, contains_synthetic_media, status, summary, reviewed_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))+ ON CONFLICT(production_id) DO UPDATE SET+ sources = excluded.sources, claims = excluded.claims,+ contains_synthetic_media = excluded.contains_synthetic_media,+ status = excluded.status, summary = excluded.summary,+ reviewed_at = excluded.reviewed_at, updated_at = datetime('now')`,+ [+ productionId,+ JSON.stringify(provenance.sources || []),+ JSON.stringify(provenance.claims || []),+ Number(provenance.containsSyntheticMedia === true),+ provenance.status || 'not_required',+ JSON.stringify(provenance.summary || {}),+ provenance.reviewedAt || null+ ]+ );+ return this.getContentProvenance(productionId);+ }++ async getContentProvenance(productionId) {+ const row = await this.getRow('SELECT * FROM content_provenance WHERE production_id = ?', [productionId]);+ return row ? {+ ...row,+ sources: JSON.parse(row.sources || '[]'),+ claims: JSON.parse(row.claims || '[]'),+ containsSyntheticMedia: Boolean(row.contains_synthetic_media),+ summary: JSON.parse(row.summary || '{}'),+ reviewedAt: row.reviewed_at+ } : null;+ }+async getChannelProfile() {const row = await this.getRow("SELECT * FROM channel_profiles WHERE id = 'default'");return row ? { ...row, bannedTopics: JSON.parse(row.banned_topics || '[]') } : null;diff --git a/index.js b/index.jsindex 86f7c51..45b61c5 100644--- a/index.js+++ b/index.js@@ -20,6 +20,7 @@ const { ActivationMetrics } = require('./utils/activation-metrics');const { AnonymousTelemetry } = require('./utils/anonymous-telemetry');const { ProductionReadinessService } = require('./utils/production-readiness-service');const { GenerationRecoveryService, GENERATION_STAGES } = require('./utils/generation-recovery-service');+const { ProvenanceService } = require('./utils/provenance-service');const { version } = require('./package.json');const chalk = require('chalk');@@ -38,6 +39,7 @@ class YouTubeAutomationAgent {this.telemetry = null;this.readiness = null;this.recovery = null;+ this.provenance = null;this.setupRequired = false;}@@ -56,6 +58,7 @@ class YouTubeAutomationAgent {updateJobStage: (...args) => this.updateJobStage(...args)});this.operator = new OperatorService(this.db);+ this.provenance = new ProvenanceService(this.db);this.autonomous = new AutonomousChannelOperator(this.db, {researchAndPlan: strategy => {if (!this.agents.strategy) throw new Error('The strategy agent is not configured');@@ -637,6 +640,35 @@ class YouTubeAutomationAgent {return res.json({ success: true, result: run });});+ this.app.put('/api/content/:productionId/provenance', protect, async (req, res) => {+ try {+ const bundle = await this.db.getProductionBundle(req.params.productionId);+ if (!bundle) return res.status(404).json({ error: 'Content not found' });+ if (bundle.review_status === 'approved' || bundle.schedule) {+ return res.status(409).json({ error: 'Provenance is locked after content is approved or scheduled' });+ }+ if (!this.provenance) this.provenance = new ProvenanceService(this.db);+ await this.provenance.review(bundle.id, req.body || {});+ const updated = await this.db.getProductionBundle(bundle.id);+ const profile = await this.db.getChannelProfile() || {};+ const quality = await this.operator.runQualityChecks({+ ...updated,+ scheduledPublishTime: updated.scheduled_publish_time+ }, profile);+ const reviewStatus = quality.passed ? 'needs_review' : 'needs_attention';+ const result = await this.db.saveContentReview(bundle.id, {+ status: reviewStatus,+ editorData: updated.editorData,+ qualityChecks: quality.checks,+ reviewNotes: quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`,+ reviewedAt: null+ });+ return res.json({ success: true, result: this.decorateContentBundle(result) });+ } catch (error) {+ return res.status(error.status || 400).json({ success: false, error: error.message });+ }+ });+this.app.post('/api/operator/runs/:runId/resume', protect, async (req, res) => {try {if (this.setupRequired || !this.agents.strategy) {@@ -920,6 +952,9 @@ class YouTubeAutomationAgent {generated.channelValueProposition = strategyContext.valueProposition || null;generated.channelConstraints = strategyContext.constraints || null;generated.callToAction = profile.call_to_action || null;+ generated.researchSources = Array.isArray(strategyContext.researchSources)+ ? strategyContext.researchSources+ : [];return generated;});this.logger.info(`Strategy generated: ${strategy.topic}`);@@ -963,6 +998,8 @@ class YouTubeAutomationAgent {// Re-persist reused production artifacts in case a restart happened between checkpointing and persistence.const contentId = await this.db.saveProductionData(productionData);await this.db.saveProductionSnapshot(productionData);+ if (!this.provenance) this.provenance = new ProvenanceService(this.db);+ productionData.provenance = await this.provenance.initialize(contentId, productionData);this.logger.info(`Content saved with ID: ${contentId}`);// Step 6: Quality and approval gate@@ -1182,7 +1219,9 @@ class YouTubeAutomationAgent {scheduledPublishTime: editorData.publishTime || input.publishTime || bundle.scheduled_publish_time,priority: bundle.priority,estimatedDuration: bundle.estimated_duration,- privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'+ privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',+ provenance: bundle.provenance,+ containsSyntheticMedia: bundle.provenance?.containsSyntheticMedia === true};const profile = await this.db.getChannelProfile() || {};const quality = await this.operator.runQualityChecks(productionData, profile);@@ -1210,7 +1249,8 @@ class YouTubeAutomationAgent {thumbnail: productionData.assets.thumbnail,video: productionData.assets.finalVideo,captions: productionData.assets.captions,- privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private'+ privacyStatus: editorData.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',+ containsSyntheticMedia: productionData.containsSyntheticMedia};await this.db.updateScheduleEntry(scheduleEntry);await this.agents.publishing.loadPublishQueue();diff --git a/package-lock.json b/package-lock.jsonindex 3d00018..fffe9ed 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "youtube-automation-agent",- "version": "2.7.0",+ "version": "2.8.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "youtube-automation-agent",- "version": "2.7.0",+ "version": "2.8.0","dependencies": {"@google-cloud/local-auth": "^3.0.0","@google/genai": "^2.9.0",diff --git a/package.json b/package.jsonindex aa214c7..e60caa4 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "youtube-automation-agent",- "version": "2.7.0",+ "version": "2.8.0","description": "Lumen is an open-source AI agent that runs a YouTube channel end to end","main": "index.js","scripts": {diff --git a/test.js b/test.jsindex ca01f22..9f6cf4b 100644--- a/test.js+++ b/test.js@@ -26,6 +26,7 @@ class SystemTest {{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },+ { name: 'Research and Provenance Desk', test: () => this.testProvenanceDesk() },{ name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },@@ -365,11 +366,20 @@ class SystemTest {const strategyAgent = new ContentStrategyAgent(db, {});strategyAgent.analyzeTrends = async function() {- this.trendingTopics = [{ topic: 'practical AI workflows', score: 8, sources: ['trending'] }];+ this.trendingTopics = [{+ topic: 'practical AI workflows', score: 8, sources: ['trending'],+ evidence: [{+ url: 'https://www.youtube.com/watch?v=research123',+ title: 'Practical AI workflows', publisher: 'Evidence channel', sourceType: 'video'+ }]+ }];this.competitorData = [];};const planned = await strategyAgent.researchAndPlanChannel(strategy);- if (planned.plan.length !== 2 || !planned.research.sources.includes('YouTube most-popular videos')) {+ if (+ planned.plan.length !== 2 || !planned.research.sources.includes('YouTube most-popular videos') ||+ planned.research.sourceCatalog.length !== 1 || planned.plan[0].sourceUrls.length !== 1+ ) {throw new Error('Strategy did not produce an evidence-labeled autonomous plan');}@@ -399,7 +409,8 @@ class SystemTest {if (completed.status !== 'waiting_review' ||completed.generatedJobs.length !== 2 ||- receivedInputs.some(input => input.source !== 'autonomous_operator' || !input.strategyContext?.angle)+ receivedInputs.some(input => input.source !== 'autonomous_operator' || !input.strategyContext?.angle) ||+ receivedInputs[0].strategyContext.researchSources.length !== 1) {throw new Error('Autonomous operator did not execute the planned workflow');}@@ -653,6 +664,138 @@ class SystemTest {this.logger.info('Production readiness gate test completed successfully');}+ async testProvenanceDesk() {+ const fs = require('fs').promises;+ const os = require('os');+ const { ProvenanceService } = require('./utils/provenance-service');+ const { OperatorService } = require('./utils/operator-service');+ const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-provenance-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'provenance.db');+ await db.initialize();+ const productionId = 'prod-provenance-test';+ const videoPath = path.join(directory, 'video.mp4');+ await fs.writeFile(videoPath, Buffer.from('test-video'));++ try {+ await db.saveProductionData({+ id: productionId,+ status: 'needs_review',+ assets: { finalVideo: { path: videoPath, simulated: false } },+ timeline: {}, scheduledPublishTime: new Date(Date.now() + 86400000).toISOString(),+ priority: 50, estimatedDuration: '1:00'+ });+ const production = {+ id: productionId,+ strategy: {+ topic: 'Evidence-aware automation',+ researchSources: [{+ url: 'https://example.com/research/fact',+ title: 'Official research evidence',+ publisher: 'Example Institute',+ sourceType: 'official'+ }]+ },+ script: {+ title: 'Evidence-aware automation',+ fullScript: 'A sufficiently detailed script with a factual statement that must be reviewed before this production can be approved.'.repeat(3),+ claims: [{+ text: 'The documented workflow reduces repeated manual steps.',+ riskLevel: 'standard',+ sourceUrls: ['https://example.com/research/fact']+ }]+ },+ seo: {+ title: 'Evidence-aware automation',+ description: 'A detailed description of an evidence-aware automation workflow for careful channel operators.',+ tags: ['automation', 'evidence', 'workflow']+ },+ assets: { finalVideo: { path: videoPath, simulated: false } }+ };+ await db.saveProductionSnapshot(production);++ const provenanceService = new ProvenanceService(db);+ const initialized = await provenanceService.initialize(productionId, production);+ if (+ initialized.status !== 'blocked' || initialized.sources.length !== 1 ||+ initialized.claims.length !== 1 || initialized.claims[0].sourceIds.length !== 1+ ) {+ throw new Error('Generated research sources and claims were not initialized as unresolved provenance');+ }++ const publishGuard = new PublishingSchedulingAgent(db, {});+ publishGuard.publishQueue = [{ productionId, status: 'scheduled', metadata: {} }];+ let blockedPublishRejected = false;+ try {+ await publishGuard.publishContent(productionId);+ } catch (error) {+ blockedPublishRejected = error.code === 'PROVENANCE_BLOCKED';+ }+ if (!blockedPublishRejected) throw new Error('Publishing did not independently enforce the provenance gate');++ let unverifiedSupportRejected = false;+ try {+ await provenanceService.review(productionId, {+ sources: initialized.sources,+ claims: [{ ...initialized.claims[0], status: 'supported' }]+ });+ } catch (error) {+ unverifiedSupportRejected = /verified source/.test(error.message);+ }+ if (!unverifiedSupportRejected) throw new Error('A claim was supported without reviewer-verified evidence');++ const reviewed = await provenanceService.review(productionId, {+ sources: initialized.sources.map(source => ({ ...source, status: 'verified' })),+ claims: [{ ...initialized.claims[0], status: 'supported' }],+ containsSyntheticMedia: true+ });+ if (reviewed.status !== 'verified' || !reviewed.containsSyntheticMedia || reviewed.summary.unresolvedClaims !== 0) {+ throw new Error('A complete evidence review was not persisted as verified');+ }++ const bundle = await db.getProductionBundle(productionId);+ const quality = await new OperatorService(db).runQualityChecks({ ...production, provenance: bundle.provenance }, {});+ if (!quality.passed || !quality.checks.find(check => check.id === 'provenance' && check.passed)) {+ throw new Error('Verified provenance did not satisfy the production quality gate');+ }++ let uploadRequest;+ const publishing = new PublishingSchedulingAgent(db, {});+ publishing.youtube = {+ videos: { insert: async request => { uploadRequest = request; return { data: { id: 'provenance-video' } }; } }+ };+ await publishing.uploadToYouTube({+ publishTime: new Date(Date.now() + 86400000).toISOString(),+ metadata: {+ seo: production.seo,+ video: { path: videoPath },+ privacyStatus: 'private',+ containsSyntheticMedia: true+ }+ });+ if (uploadRequest?.requestBody?.status?.containsSyntheticMedia !== true) {+ throw new Error('Synthetic-media disclosure was not handed to the YouTube upload request');+ }++ let emptyWaiverRejected = false;+ try {+ new ProvenanceService(db).build({+ sources: reviewed.sources,+ claims: [{ ...reviewed.claims[0], status: 'waived', notes: '' }]+ });+ } catch (error) {+ emptyWaiverRejected = /reviewer note/.test(error.message);+ }+ if (!emptyWaiverRejected) throw new Error('A claim waiver without a reviewer note was accepted');+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }++ this.logger.info('Research and provenance desk test completed successfully');+ }+async testResumableGenerationCheckpoints() {const fs = require('fs').promises;const os = require('os');diff --git a/utils/autonomous-channel-operator.js b/utils/autonomous-channel-operator.jsindex 759e0ec..a2e8236 100644--- a/utils/autonomous-channel-operator.js+++ b/utils/autonomous-channel-operator.js@@ -125,6 +125,7 @@ class AutonomousChannelOperator {if (job && ['failed', 'interrupted'].includes(job.status)) {job = await this.resumeGenerationJob(job.id);} else if (!job || !['queued', 'running', 'completed'].includes(job.status)) {+ const selectedSourceUrls = new Set(item.sourceUrls || []);job = await this.startGenerationJob({topic: item.topic,style: item.format,@@ -136,7 +137,8 @@ class AutonomousChannelOperator {audience: strategy.audience,objective: strategy.objective,valueProposition: strategy.value_proposition,- constraints: strategy.constraints+ constraints: strategy.constraints,+ researchSources: (research.sourceCatalog || []).filter(source => selectedSourceUrls.has(source.url))}});}diff --git a/utils/operator-service.js b/utils/operator-service.jsindex c7d9b91..28b4175 100644--- a/utils/operator-service.js+++ b/utils/operator-service.js@@ -61,6 +61,16 @@ class OperatorService {? `Content matches blocked terms: ${matchedBannedTopics.join(', ')}`: 'No blocked brand topics detected'));+ const provenance = production.provenance || {};+ const provenancePassed = ['verified', 'not_required'].includes(provenance.status || 'not_required');+ const unresolved = Number(provenance.summary?.unresolvedClaims || 0);+ checks.push(this.check('provenance', provenancePassed,+ provenance.status === 'verified'+ ? `${provenance.summary?.resolvedClaims || 0} factual claims resolved against reviewed evidence`+ : provenance.status === 'not_required'+ ? 'No externally verifiable factual claims were declared'+ : `${unresolved} factual claim${unresolved === 1 ? '' : 's'} still require evidence review`));+const blockingFailures = checks.filter(check => check.blocking && !check.passed);return {passed: blockingFailures.length === 0,diff --git a/utils/provenance-service.js b/utils/provenance-service.jsnew file mode 100644index 0000000..95e7250--- /dev/null+++ b/utils/provenance-service.js@@ -0,0 +1,154 @@+const crypto = require('crypto');++const SOURCE_TYPES = new Set(['article', 'video', 'dataset', 'official', 'asset', 'other']);+const SOURCE_STATUSES = new Set(['pending', 'verified', 'rejected']);+const CLAIM_RISKS = new Set(['standard', 'high']);+const CLAIM_STATUSES = new Set(['pending', 'supported', 'unsupported', 'waived']);++class ProvenanceService {+ constructor(db) {+ this.db = db;+ }++ async initialize(productionId, production = {}) {+ const existing = await this.db.getContentProvenance(productionId);+ if (existing) return existing;++ const sources = this.normalizeSources(production.strategy?.researchSources || []);+ const sourceIdByUrl = new Map(sources.map(source => [source.url, source.id]));+ const claims = this.normalizeClaims(production.script?.claims || [], sources, sourceIdByUrl);+ const provenance = this.build({ sources, claims, containsSyntheticMedia: false });+ await this.db.saveContentProvenance(productionId, provenance);+ return this.db.getContentProvenance(productionId);+ }++ async review(productionId, input = {}) {+ const existing = await this.db.getContentProvenance(productionId) || {};+ const provenance = this.build({+ sources: input.sources ?? existing.sources ?? [],+ claims: input.claims ?? existing.claims ?? [],+ containsSyntheticMedia: input.containsSyntheticMedia ?? existing.containsSyntheticMedia ?? false+ });+ await this.db.saveContentProvenance(productionId, provenance);+ return this.db.getContentProvenance(productionId);+ }++ build(input = {}) {+ const sources = this.normalizeSources(input.sources || []);+ const sourceIds = new Set(sources.map(source => source.id));+ const claims = this.normalizeClaims(input.claims || [], sources);++ for (const claim of claims) {+ claim.sourceIds = claim.sourceIds.filter(id => sourceIds.has(id));+ if (claim.status === 'supported') {+ const hasVerifiedSource = claim.sourceIds.some(id =>+ sources.some(source => source.id === id && source.status === 'verified')+ );+ if (!hasVerifiedSource) throw this.invalid('A supported claim must link to at least one verified source');+ }+ if (claim.status === 'waived' && !claim.notes) {+ throw this.invalid('A waived claim requires a reviewer note');+ }+ }++ const unresolvedClaims = claims.filter(claim => !['supported', 'waived'].includes(claim.status));+ const status = claims.length === 0+ ? 'not_required'+ : unresolvedClaims.length === 0 ? 'verified' : 'blocked';++ return {+ sources,+ claims,+ containsSyntheticMedia: input.containsSyntheticMedia === true,+ status,+ reviewedAt: status === 'verified' ? new Date().toISOString() : null,+ summary: {+ sourceCount: sources.length,+ verifiedSources: sources.filter(source => source.status === 'verified').length,+ claimCount: claims.length,+ resolvedClaims: claims.length - unresolvedClaims.length,+ highRiskClaims: claims.filter(claim => claim.riskLevel === 'high').length,+ unresolvedClaims: unresolvedClaims.length+ }+ };+ }++ normalizeSources(items = []) {+ if (!Array.isArray(items)) throw this.invalid('Sources must be an array');+ const seenUrls = new Set();+ return items.slice(0, 50).map((item, index) => {+ const url = this.validUrl(item?.url);+ if (!url) throw this.invalid(`Source ${index + 1} requires a valid http or https URL`);+ if (seenUrls.has(url)) throw this.invalid(`Duplicate source URL: ${url}`);+ seenUrls.add(url);+ return {+ id: this.id(item?.id, 'source'),+ url,+ title: this.text(item?.title, 300) || url,+ publisher: this.text(item?.publisher, 200),+ publishedAt: this.date(item?.publishedAt),+ accessedAt: this.date(item?.accessedAt) || new Date().toISOString(),+ sourceType: SOURCE_TYPES.has(item?.sourceType) ? item.sourceType : 'other',+ status: SOURCE_STATUSES.has(item?.status) ? item.status : 'pending',+ notes: this.text(item?.notes, 1000)+ };+ });+ }++ normalizeClaims(items = [], sources = [], sourceIdByUrl = new Map()) {+ if (!Array.isArray(items)) throw this.invalid('Claims must be an array');+ const validSourceIds = new Set(sources.map(source => source.id));+ return items.slice(0, 100).map((item, index) => {+ const text = this.text(item?.text || item?.claim, 1000);+ if (!text) throw this.invalid(`Claim ${index + 1} requires text`);+ const mappedUrls = Array.isArray(item?.sourceUrls)+ ? item.sourceUrls.map(url => sourceIdByUrl.get(this.validUrl(url))).filter(Boolean)+ : [];+ const sourceIds = [...new Set([+ ...(Array.isArray(item?.sourceIds) ? item.sourceIds : []),+ ...mappedUrls+ ].map(value => String(value)).filter(id => validSourceIds.has(id)))];+ return {+ id: this.id(item?.id, 'claim'),+ text,+ riskLevel: CLAIM_RISKS.has(item?.riskLevel) ? item.riskLevel : 'standard',+ sourceIds,+ status: CLAIM_STATUSES.has(item?.status) ? item.status : 'pending',+ notes: this.text(item?.notes, 1000)+ };+ });+ }++ id(value, prefix) {+ const normalized = String(value || '').trim();+ if (/^[a-zA-Z0-9_-]{1,100}$/.test(normalized)) return normalized;+ return `${prefix}_${crypto.randomUUID()}`;+ }++ validUrl(value) {+ try {+ const url = new URL(String(value || '').trim());+ return ['http:', 'https:'].includes(url.protocol) ? url.toString() : '';+ } catch (_error) {+ return '';+ }+ }++ text(value, limit) {+ return String(value || '').trim().slice(0, limit);+ }++ date(value) {+ if (!value) return null;+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? null : date.toISOString();+ }++ invalid(message) {+ const error = new Error(message);+ error.status = 400;+ return error;+ }+}++module.exports = { ProvenanceService };