🎬 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.6 production readiness
darkzOGx4ccdf731c918
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13a86cd..6ada4d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@## Unreleased+## v2.6.0 — 2026-08-20++- Added a user-triggered Production Readiness Gate with live text, narration, YouTube-access, local audio/video MP4, and queued-metadata probes; paid image verification is explicit opt-in+- Added persistent readiness evidence and a dashboard remediation panel; recorded blocking failures now stop autonomous runs and publishing until a later check clears them+- Added YouTube metadata normalization and fail-fast upload validation to prevent malformed AI-generated tags from reaching the upload API- Added an approval-gated Channel Learning Engine that captures real 24-hour and 7-day performance snapshots, derives channel-relative baselines, and feeds only approved recommendations into future autonomous plans- Added a dashboard learning review with evidence, confidence, approve/reject controls, and operator-selected title/thumbnail variants for approved packaging experiments; simulated analytics are explicitly excluded from learning- Added a persistent Autonomous Channel Operator that turns a channel objective, audience, pillars, cadence, and guardrails into researched editorial plans and sequential end-to-end production runsdiff --git a/README.md b/README.mdindex 329e505..44fb2fd 100644--- a/README.md+++ b/README.md@@ -8,6 +8,17 @@ Research topics → write scripts → generate narration and visuals → assembl[](LICENSE)[](package.json)+## What's new in version 2.6.0++Version 2.6 turns the agent into a safer, self-improving channel operator:++- **Autonomous Channel Operator:** define the audience, objective, content pillars, cadence, and guardrails once; the agent researches, plans, and runs the production workflow.+- **Closed-loop channel learning:** real 24-hour and 7-day analytics become evidence-backed recommendations that influence future plans only after you approve them.+- **Production Readiness Gate:** verify text, narration, FFmpeg, YouTube access, and upload metadata before autonomous production or publishing begins.+- **Safer packaging experiments:** review and select title and thumbnail variants without silently changing live YouTube metadata.++See the complete release history in [CHANGELOG.md](CHANGELOG.md).+- **Self-hosted:** your credentials, media, and channel data stay under your control.- **Approval-first:** nothing is scheduled until quality, rights, and human-review gates pass by default.- **Strategy-driven:** give the Autonomous Channel Operator an objective, audience, pillars, cadence, and guardrails; it turns them into researched content plans and production runs.@@ -30,6 +41,14 @@ Open `http://localhost:3456`. The walkthrough explains each provider choice, tesAlready know what you are doing? `npm run setup` offers a shorter classic flow, and `.env.example` documents every setting.+### Verify production readiness++Before activating autonomous production, open **Production readiness** in the dashboard and choose **Run verified check**. The gate makes small live text and narration requests, verifies access to the connected YouTube channel, creates and decodes a temporary MP4 containing audio and video, and validates every queued upload's metadata. It never creates or uploads a YouTube video, and temporary probe assets are deleted after the run.++AI image generation can incur a larger provider charge, so its live probe is a separate opt-in checkbox. Without that checkbox, image configuration is reported as verified, skipped, or using the built-in gradient fallback without making a paid image request.++Results persist locally in SQLite with exact remediation steps. A recorded blocking failure stops autonomous generation and publishing until a later run passes; manual work remains available when readiness has never been checked or the last result is older than 24 hours.+### What you need- Node.js 18+@@ -246,6 +265,15 @@ curl -X POST http://localhost:3456/generate \# inspect the returned background jobcurl http://localhost:3456/api/jobs/:jobId+# inspect the latest production-readiness evidence+curl http://localhost:3456/api/readiness++# run harmless live probes; add {"includePaidMedia":true} only to test paid image generation+curl -X POST http://localhost:3456/api/readiness/run \+ -H "Content-Type: application/json" \+ -H "x-api-key: $API_KEY" \+ -d '{"includePaidMedia":false}'+# save a channel strategycurl -X PUT http://localhost:3456/api/operator/strategy \-H "Content-Type: application/json" \diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.jsindex 857300d..2b027ce 100644--- a/agents/publishing-scheduling-agent.js+++ b/agents/publishing-scheduling-agent.js@@ -3,6 +3,7 @@ const fs = require('fs').promises;const fsSync = require('fs');const path = require('path');const { Logger } = require('../utils/logger');+const { assertValidYouTubeMetadata } = require('../utils/youtube-metadata-validator');class PublishingSchedulingAgent {constructor(db, credentials) {@@ -82,6 +83,18 @@ class PublishingSchedulingAgent {async publishContent(contentId) {try {+ if (this.db.getLatestReadinessRun) {+ const readiness = await this.db.getLatestReadinessRun();+ if (readiness?.status === 'failed') {+ const failures = readiness.checks+ .filter(check => check.blocking && check.status === 'failed')+ .map(check => check.id);+ const error = new Error(`Publishing is blocked by the production readiness gate. Fix ${failures.join(', ')} and run the check again.`);+ error.status = 409;+ error.code = 'READINESS_BLOCKED';+ throw error;+ }+ }this.logger.info(`Publishing content: ${contentId}`);const scheduleEntry = this.publishQueue.find(entry =>@@ -116,16 +129,21 @@ class PublishingSchedulingAgent {async uploadToYouTube(scheduleEntry) {const { metadata } = scheduleEntry;+ const validation = assertValidYouTubeMetadata(metadata.seo);+ if (validation.warnings.length) {+ this.logger.warn(`YouTube metadata warnings: ${validation.warnings.join(' ')}`);+ }+ const safeMetadata = validation.value;// Prepare video metadataconst videoMetadata = {snippet: {- title: metadata.seo.title,- description: metadata.seo.description,- tags: metadata.seo.tags,- categoryId: metadata.seo.metadata.category.toString(),- defaultLanguage: metadata.seo.metadata.language,- defaultAudioLanguage: metadata.seo.metadata.language+ title: safeMetadata.title,+ description: safeMetadata.description,+ tags: safeMetadata.tags,+ categoryId: safeMetadata.categoryId,+ defaultLanguage: safeMetadata.defaultLanguage,+ defaultAudioLanguage: safeMetadata.defaultAudioLanguage},status: {privacyStatus: metadata.privacyStatus || process.env.DEFAULT_PRIVACY_STATUS || 'private',@@ -236,6 +254,10 @@ class PublishingSchedulingAgent {await this.publishContent(entry.productionId);this.logger.info(`Auto-published: ${entry.title}`);} catch (error) {+ if (error.code === 'READINESS_BLOCKED') {+ this.logger.warn(error.message);+ continue;+ }this.logger.error(`Failed to auto-publish ${entry.title}:`, error);// Mark as failed but don't stop processing other itemsentry.status = 'failed';diff --git a/dashboard/app.js b/dashboard/app.jsindex 8996db1..2aab3fb 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -137,10 +137,41 @@ function renderDashboard() {renderIdeas(state.ideas);renderAnalytics(state.analytics, state.learning);renderActivation(state.activation);- renderOperator(state.channelStrategy, state.operatorRuns || [], state.system);+ renderReadiness(state.readiness);+ renderOperator(state.channelStrategy, state.operatorRuns || [], { ...state.system, readiness: state.readiness });populateSettings(state.profile, state.settings);}+function renderReadiness(readiness = {}) {+ const status = readiness.status || 'unverified';+ const statusNode = $('#readiness-status');+ statusNode.className = `status ${escapeHTML(status)}`;+ statusNode.textContent = readiness.stale && status !== 'unverified' ? `${label(status)} · stale` : label(status);++ const titles = {+ passed: 'The production path is verified.',+ warning: 'Core checks passed with warnings.',+ failed: 'Automation is blocked until this is fixed.',+ unverified: 'Prove the pipeline, without uploading.'+ };+ $('#readiness-title').textContent = titles[status] || titles.unverified;+ const counts = readiness.summary || {};+ $('#readiness-summary').textContent = status === 'unverified'+ ? 'The check makes small live text and narration requests, verifies channel access, builds a local audio/video MP4, and validates queued metadata. It never creates or uploads a YouTube video.'+ : `${counts.passed || 0} passed, ${counts.warnings || 0} warning${counts.warnings === 1 ? '' : 's'}, and ${counts.failed || 0} failed.`;+ $('#readiness-meta').textContent = readiness.completed_at+ ? `Last run ${formatDate(readiness.completed_at)}${readiness.stale ? ' · older than 24 hours' : ''}`+ : 'No readiness run recorded.';++ const checks = Array.isArray(readiness.checks) ? readiness.checks : [];+ $('#readiness-checks').innerHTML = checks.length ? checks.map(check => `+ <article class="readiness-check ${escapeHTML(check.status)}">+ <div class="readiness-check-heading"><span class="readiness-icon" aria-hidden="true">${check.status === 'passed' ? '✓' : check.status === 'failed' ? '×' : '!'}</span><div><strong>${escapeHTML(check.label)}</strong><div class="meta-line">${escapeHTML(label(check.status))}${check.blocking ? ' · blocking' : ' · optional'} · ${(check.durationMs || 0) / 1000}s</div></div></div>+ <p>${escapeHTML(check.message)}</p>+ ${check.remediation ? `<small><strong>Next:</strong> ${escapeHTML(check.remediation)}</small>` : ''}+ </article>`).join('') : empty('Run the verified check to inspect every production dependency.');+}+function renderReviews(reviews) {const container = $('#review-list');if (!reviews.length) {@@ -345,7 +376,8 @@ function renderOperator(strategy, runs, system) {$('#operator-strategy-status').textContent = label(strategyStatus);const run = runs[0];const active = run && ['queued', 'running', 'cancelling'].includes(run.status);- $('#activate-operator-button').disabled = Boolean(system.setupRequired || active);+ $('#activate-operator-button').disabled = Boolean(system.setupRequired || active || system.readiness?.status === 'failed');+ $('#activate-operator-button').title = system.readiness?.status === 'failed' ? 'Resolve the production readiness failures first' : '';$('#activate-operator-button').textContent = strategy?.status === 'active' ? 'Run strategy now' : 'Activate & run now';$('#pause-operator-button').classList.toggle('hidden', strategy?.status !== 'active');$('#cancel-operator-run').classList.toggle('hidden', !active);@@ -409,6 +441,7 @@ function switchView(view) {pipeline: ['CONTENT OPERATIONS', 'From idea to published.'],calendar: ['EDITORIAL PLANNING', 'Plan before you generate.'],analytics: ['PERFORMANCE', 'Turn results into the next move.'],+ readiness: ['PRODUCTION READINESS', 'Verify before autonomy runs.'],settings: ['CHANNEL GUARDRAILS', 'Make every agent sound like you.']};$('#view-eyebrow').textContent = titles[view][0];@@ -577,6 +610,20 @@ $('#add-idea-button').addEventListener('click', () => $('#idea-dialog').showModa$('#refresh-button').addEventListener('click', () => refreshDashboard());$('#pipeline-filter').addEventListener('change', () => renderPipeline(ui.state?.pipeline || []));+$('#run-readiness-button').addEventListener('click', async event => {+ const button = event.currentTarget;+ button.disabled = true;+ button.textContent = 'Running live checks…';+ try {+ await mutate('/api/readiness/run', 'POST', { includePaidMedia: $('#paid-image-probe').checked }, 'Production readiness check completed.');+ switchView('readiness');+ } catch (_error) { /* toast already shown */ }+ finally {+ button.disabled = false;+ button.textContent = 'Run verified check';+ }+});+$('#automation-toggle').addEventListener('click', async () => {const action = ui.state?.system.automationPaused ? 'resume' : 'pause';await mutate(`/api/automation/${action}`, 'POST', {}, `Automation ${action}d.`).catch(() => {});@@ -654,6 +701,6 @@ $('#api-key-button').addEventListener('click', () => {});const initialView = location.hash.slice(1);-if (['overview', 'operator', 'pipeline', 'calendar', 'analytics', 'settings'].includes(initialView)) switchView(initialView);+if (['overview', 'operator', 'pipeline', 'calendar', 'analytics', 'readiness', 'settings'].includes(initialView)) switchView(initialView);refreshDashboard();setInterval(() => refreshDashboard(true), 8000);diff --git a/dashboard/index.html b/dashboard/index.htmlindex 53da82f..d4343e6 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -20,6 +20,7 @@<button class="nav-item" data-view="pipeline"><span>≋</span> Pipeline <b id="review-badge" class="badge hidden">0</b></button><button class="nav-item" data-view="calendar"><span>□</span> Calendar & ideas</button><button class="nav-item" data-view="analytics"><span>⌁</span> Analytics</button>+ <button class="nav-item" data-view="readiness"><span>✓</span> Production readiness</button><button class="nav-item" data-view="settings"><span>⚙</span> Channel setup</button></nav><div class="sidebar-footer">@@ -143,6 +144,28 @@<article class="panel activation-panel"><div class="panel-heading"><div><p class="eyebrow">LOCAL ACTIVATION</p><h2>First-run journey</h2></div></div><p class="callout">Calculated locally from your database and video files. Nothing is transmitted unless anonymous telemetry is explicitly enabled.</p><div id="activation-list" class="timeline"></div></article></section>+ <section id="readiness-view" class="view">+ <div class="section-intro readiness-intro">+ <div><h2>Production readiness</h2><p>Verify the real path from providers to a publishable YouTube upload before autonomy spends time or credits.</p></div>+ <span id="readiness-status" class="status unverified">Unverified</span>+ </div>+ <article class="panel readiness-hero">+ <div>+ <p class="eyebrow">VERIFIED DRY RUN</p>+ <h2 id="readiness-title">Prove the pipeline, without uploading.</h2>+ <p id="readiness-summary">The check makes small live text and narration requests, verifies channel access, builds a local audio/video MP4, and validates queued metadata. It never creates or uploads a YouTube video.</p>+ <div id="readiness-meta" class="meta-line">No readiness run recorded.</div>+ </div>+ <div class="readiness-actions">+ <label class="toggle paid-probe"><input id="paid-image-probe" type="checkbox"><span></span> Include paid image probe</label>+ <button id="run-readiness-button" class="button primary">Run verified check</button>+ <small>Live provider probes can consume a small amount of quota or credits.</small>+ </div>+ </article>+ <div id="readiness-checks" class="readiness-grid"></div>+ <p class="callout readiness-policy">A recorded blocking failure stops autonomous generation and publishing until a later run passes. An unverified or stale result remains visible but does not interrupt manual work.</p>+ </section>+<section id="settings-view" class="view"><div class="section-intro"><div><h2>Channel setup</h2><p>These guardrails guide every agent in the pipeline.</p></div></div><form id="profile-form" class="panel settings-form">diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 83b9f43..d69b23a 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -83,7 +83,8 @@ h2 { letter-spacing: -.025em; margin-bottom: 0; }.status { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; background: rgba(114,165,255,.12); color: var(--blue); }.status.needs_review, .status.queued { color: var(--amber); background: rgba(245,185,68,.12); }.status.needs_attention, .status.failed, .status.rejected { color: #ff8994; background: var(--red-soft); }-.status.approved, .status.scheduled, .status.published, .status.completed { color: var(--green); background: rgba(72,213,151,.12); }+.status.approved, .status.scheduled, .status.published, .status.completed, .status.passed { 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; }.activity { display: grid; grid-template-columns: 8px 1fr auto; gap: 10px; align-items: start; }@@ -154,6 +155,25 @@ label small { color: var(--muted); font-weight: 400; }.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; }+.readiness-hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, .42fr); gap: 28px; align-items: center; margin-bottom: 18px; }+.readiness-hero h2 { font-size: 25px; margin: 5px 0 8px; }+.readiness-hero p:not(.eyebrow) { color: var(--muted); line-height: 1.55; max-width: 760px; }+.readiness-actions { display: grid; gap: 11px; padding: 16px; border: 1px solid var(--line); background: rgba(255,255,255,.018); border-radius: 12px; }+.readiness-actions small { color: var(--muted); line-height: 1.45; }+.readiness-actions .paid-probe { font-size: 11px; }+.readiness-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }+.readiness-check { border: 1px solid var(--line); background: var(--panel); border-radius: 13px; padding: 17px; min-height: 180px; }+.readiness-check.passed { border-color: rgba(72,213,151,.26); }+.readiness-check.failed { border-color: rgba(255,87,98,.34); }+.readiness-check.warning, .readiness-check.skipped { border-color: rgba(245,185,68,.28); }+.readiness-check-heading { display: flex; gap: 11px; align-items: center; }+.readiness-icon { display: grid; place-items: center; width: 31px; height: 31px; flex: 0 0 31px; border-radius: 50%; background: rgba(114,165,255,.1); color: var(--blue); font-weight: 900; }+.readiness-check.passed .readiness-icon { color: var(--green); background: rgba(72,213,151,.12); }+.readiness-check.failed .readiness-icon { color: #ff8994; background: var(--red-soft); }+.readiness-check.warning .readiness-icon, .readiness-check.skipped .readiness-icon { color: var(--amber); background: rgba(245,185,68,.12); }+.readiness-check p { color: var(--muted); font-size: 12px; line-height: 1.55; margin: 15px 0 12px; }+.readiness-check > small { display: block; color: #b9c2cf; font-size: 11px; line-height: 1.5; }+.readiness-policy { margin-top: 18px; }.timeline-dot { width: 10px; height: 10px; flex: 0 0 10px; border-radius: 50%; border: 2px solid var(--muted); }.timeline-dot.done { border-color: var(--green); background: var(--green); box-shadow: 0 0 0 4px rgba(72, 213, 151, .1); }.activation-share { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--muted); font-size: 12px; padding-top: 4px; }@@ -190,7 +210,7 @@ label small { color: var(--muted); font-weight: 400; }main { padding: 0 18px 60px; }.loading-bar { left: 0; }.stats-grid { grid-template-columns: 1fr 1fr; }- .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid { grid-template-columns: 1fr; }+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid { grid-template-columns: 1fr; }.pipeline-item { grid-template-columns: 1fr auto; }.pipeline-col { display: none; }}diff --git a/database/db.js b/database/db.jsindex da1cf7a..7528897 100644--- a/database/db.js+++ b/database/db.js@@ -321,6 +321,15 @@ class Database {data TEXT,status TEXT DEFAULT 'unread',created_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,+ `CREATE TABLE IF NOT EXISTS readiness_runs (+ id TEXT PRIMARY KEY,+ status TEXT NOT NULL,+ checks TEXT NOT NULL,+ summary TEXT NOT NULL,+ started_at TEXT NOT NULL,+ completed_at TEXT NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP)`,// System Settings`CREATE TABLE IF NOT EXISTS settings (@@ -1268,6 +1277,43 @@ class Database {}, {});}+ // Production readiness+ async saveReadinessRun(run) {+ await this.executeQuery(+ `INSERT OR REPLACE INTO readiness_runs (+ id, status, checks, summary, started_at, completed_at+ ) VALUES (?, ?, ?, ?, ?, ?)`,+ [+ run.id,+ run.status,+ JSON.stringify(run.checks || []),+ JSON.stringify(run.summary || {}),+ run.startedAt,+ run.completedAt+ ]+ );+ return this.getReadinessRun(run.id);+ }++ async getReadinessRun(id) {+ const row = await this.getRow('SELECT * FROM readiness_runs WHERE id = ?', [id]);+ return this.parseReadinessRun(row);+ }++ async getLatestReadinessRun() {+ const row = await this.getRow('SELECT * FROM readiness_runs ORDER BY completed_at DESC LIMIT 1');+ return this.parseReadinessRun(row);+ }++ parseReadinessRun(row) {+ if (!row) return null;+ return {+ ...row,+ checks: JSON.parse(row.checks || '[]'),+ summary: JSON.parse(row.summary || '{}')+ };+ }+// Utility methodsgenerateId(prefix) {return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(7)}`;diff --git a/index.js b/index.jsindex 347dd73..18a71d2 100644--- a/index.js+++ b/index.js@@ -18,6 +18,7 @@ const { OperatorService } = require('./utils/operator-service');const { AutonomousChannelOperator } = require('./utils/autonomous-channel-operator');const { ActivationMetrics } = require('./utils/activation-metrics');const { AnonymousTelemetry } = require('./utils/anonymous-telemetry');+const { ProductionReadinessService } = require('./utils/production-readiness-service');const { version } = require('./package.json');const chalk = require('chalk');@@ -34,6 +35,7 @@ class YouTubeAutomationAgent {this.autonomous = null;this.activation = null;this.telemetry = null;+ this.readiness = null;this.setupRequired = false;}@@ -64,6 +66,7 @@ class YouTubeAutomationAgent {this.logger.info('Loading credentials...');this.credentials = new CredentialManager();const credentialsValid = await this.credentials.validateAll();+ this.readiness = new ProductionReadinessService(this.db, this.credentials);if (!credentialsValid) {console.log(chalk.yellow('\n⚠️ Some credentials are missing or invalid.'));@@ -397,7 +400,7 @@ class YouTubeAutomationAgent {this.app.get('/api/dashboard', async (_req, res) => {try {- const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation, channelStrategy, operatorRuns] = await Promise.all([+ const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation, channelStrategy, operatorRuns, readiness] = await Promise.all([this.db.getStats(),this.db.listGenerationJobs(20),this.db.getPipelineOverview(50),@@ -417,12 +420,15 @@ class YouTubeAutomationAgent {? this.activation.getSummary(): Promise.resolve({ privacy: 'local-only', counts: {}, milestones: {} }),this.db.getChannelStrategy(),- this.db.listOperatorRuns(10)+ this.db.listOperatorRuns(10),+ this.readiness+ ? this.readiness.getSummary()+ : Promise.resolve({ status: 'unverified', stale: false, blockingFailures: [], checks: [] })]);if (this.telemetry) void this.telemetry.sync(activation);res.json({stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation,- channelStrategy, operatorRuns,+ channelStrategy, operatorRuns, readiness,system: {initialized: this.isInitialized,setupRequired: this.setupRequired,@@ -444,6 +450,21 @@ class YouTubeAutomationAgent {return res.json(job);});+ this.app.get('/api/readiness', async (_req, res) => {+ if (!this.readiness) return res.status(503).json({ error: 'Readiness service is not initialized' });+ return res.json(await this.readiness.getSummary());+ });++ this.app.post('/api/readiness/run', protect, async (req, res) => {+ try {+ if (!this.readiness) return res.status(503).json({ error: 'Readiness service is not initialized' });+ const result = await this.readiness.run({ includePaidMedia: req.body?.includePaidMedia === true });+ return res.json({ success: true, result });+ } catch (error) {+ return res.status(error.status || 500).json({ success: false, error: error.message });+ }+ });+this.app.post('/api/jobs/:jobId/cancel', protect, async (req, res) => {const job = await this.db.getGenerationJob(req.params.jobId);if (!job) return res.status(404).json({ error: 'Job not found' });@@ -572,6 +593,7 @@ class YouTubeAutomationAgent {if (this.activeJobs.size) {return res.status(409).json({ success: false, error: 'Wait for the current generation job to finish before starting an autonomous run' });}+ await this.readiness?.assertReady('Autonomous production');const current = await this.db.getChannelStrategy() || {};const strategy = this.validateChannelStrategy({ ...(req.body || {}), status: 'active' }, current);const saved = await this.db.saveChannelStrategy(strategy);@@ -671,6 +693,9 @@ class YouTubeAutomationAgent {error.status = 503;throw error;}+ if (['scheduler', 'autonomous_operator'].includes(input.source)) {+ await this.readiness?.assertReady('Automated generation');+ }const maxConcurrent = Math.max(1, parseInt(process.env.MAX_CONCURRENT_JOBS || '1', 10));if (this.activeJobs.size >= maxConcurrent) {const error = new Error(`Generation is busy (${this.activeJobs.size}/${maxConcurrent} active jobs). Try again when the current job finishes.`);diff --git a/package-lock.json b/package-lock.jsonindex 3db4727..5f61b88 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "youtube-automation-agent",- "version": "2.5.0",+ "version": "2.6.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "youtube-automation-agent",- "version": "2.5.0",+ "version": "2.6.0","dependencies": {"@google-cloud/local-auth": "^3.0.0","@google/genai": "^2.9.0",diff --git a/package.json b/package.jsonindex 5d6fbbe..a62bb6c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "youtube-automation-agent",- "version": "2.5.0",+ "version": "2.6.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 e50e20c..1b94ef3 100644--- a/test.js+++ b/test.js@@ -3,6 +3,8 @@ const { Logger } = require('./utils/logger');const { CredentialManager } = require('./utils/credential-manager');const chalk = require('chalk');const path = require('path');+const { ProductionReadinessService } = require('./utils/production-readiness-service');+const { normalizeTags, validateYouTubeMetadata } = require('./utils/youtube-metadata-validator');class SystemTest {constructor() {@@ -23,6 +25,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: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },@@ -535,6 +538,92 @@ class SystemTest {this.logger.info('Closed-loop channel learning test completed successfully');}+ async testProductionReadinessGate() {+ const fs = require('fs').promises;+ const os = require('os');+ let savedRun = null;+ const db = {+ generateId: () => 'readiness_test',+ saveReadinessRun: async run => {+ savedRun = {+ ...run,+ started_at: run.startedAt,+ completed_at: run.completedAt+ };+ return savedRun;+ },+ getLatestReadinessRun: async () => savedRun+ };+ const passingProbe = label => async () => ({ message: `${label} verified` });+ const service = new ProductionReadinessService(db, { credentials: {} }, {+ probes: {+ text: passingProbe('Text'),+ image: passingProbe('Image'),+ narration: passingProbe('Narration'),+ videoAssembly: passingProbe('Video'),+ youtube: passingProbe('YouTube'),+ metadata: passingProbe('Metadata')+ }+ });+ const passed = await service.run({ includePaidMedia: true });+ if (passed.status !== 'passed' || passed.checks.length !== 6 || !savedRun) {+ throw new Error('A successful readiness run was not persisted correctly');+ }+ await service.assertReady('Test automation');++ const failingService = new ProductionReadinessService(db, { credentials: {} }, {+ probes: {+ text: passingProbe('Text'),+ image: passingProbe('Image'),+ narration: passingProbe('Narration'),+ videoAssembly: passingProbe('Video'),+ youtube: async () => { throw new Error('token rejected sk-secret-value'); },+ metadata: passingProbe('Metadata')+ }+ });+ const failed = await failingService.run();+ if (failed.status !== 'failed' || failed.blockingFailures[0] !== 'youtube_access') {+ throw new Error('A blocking readiness probe did not fail closed');+ }+ if (failed.checks.find(check => check.id === 'youtube_access').message.includes('sk-secret-value')) {+ throw new Error('Readiness diagnostics did not redact a provider-shaped secret');+ }+ let blocked = false;+ try {+ await failingService.assertReady('Test publishing');+ } catch (error) {+ blocked = error.status === 409;+ }+ if (!blocked) throw new Error('Failed readiness did not block protected automation');++ const tags = normalizeTags(['#Automation', 'automation', 'bad"tag', 'x'.repeat(140)]);+ const metadata = validateYouTubeMetadata({+ title: 'A valid title',+ description: 'A valid upload description.',+ tags,+ metadata: { category: 22, language: 'en' }+ });+ if (!metadata.valid || tags[0] !== 'Automation' || tags.includes('automation') || tags.some(tag => tag.includes('"') || tag.length > 100)) {+ throw new Error('YouTube metadata normalization is unsafe or invalid');+ }++ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-readiness-db-'));+ const persistenceDb = new Database();+ persistenceDb.dbPath = path.join(directory, 'readiness.db');+ try {+ await persistenceDb.initialize();+ await persistenceDb.saveReadinessRun(passed);+ const persisted = await persistenceDb.getLatestReadinessRun();+ if (persisted?.id !== passed.id || persisted.checks.length !== 6 || persisted.summary.passed !== 6) {+ throw new Error('Readiness evidence did not round-trip through SQLite');+ }+ } finally {+ await persistenceDb.close();+ await fs.rm(directory, { recursive: true, force: true });+ }+ this.logger.info('Production readiness gate test completed successfully');+ }+async testAPIValidationAndSecurity() {const { YouTubeAutomationAgent } = require('./index');const agent = new YouTubeAutomationAgent();diff --git a/utils/production-readiness-service.js b/utils/production-readiness-service.jsnew file mode 100644index 0000000..f19486e--- /dev/null+++ b/utils/production-readiness-service.js@@ -0,0 +1,245 @@+const fs = require('fs').promises;+const os = require('os');+const path = require('path');+const { AITextService } = require('./ai-text-service');+const { AIVideoGenerator } = require('./ai-video-generator');+const { checkFFmpeg, runFFmpeg } = require('./ffmpeg');+const { validateYouTubeMetadata } = require('./youtube-metadata-validator');+const { Logger } = require('./logger');++const STALE_AFTER_MS = 24 * 60 * 60 * 1000;++class ProductionReadinessService {+ constructor(db, credentialManager, options = {}) {+ this.db = db;+ this.credentialManager = credentialManager;+ this.logger = options.logger || new Logger('ProductionReadiness');+ this.probes = options.probes || {};+ this.now = options.now || (() => new Date());+ this.activeRun = null;+ }++ async getSummary() {+ const latest = await this.db.getLatestReadinessRun();+ if (!latest) {+ return {+ status: 'unverified',+ stale: false,+ blockingFailures: [],+ checks: [],+ message: 'Run the verified readiness check before relying on autonomous production.'+ };+ }+ const age = this.now().getTime() - new Date(latest.completed_at || latest.created_at).getTime();+ return {+ ...latest,+ stale: age > STALE_AFTER_MS,+ blockingFailures: latest.checks.filter(check => check.blocking && check.status === 'failed').map(check => check.id)+ };+ }++ async assertReady(action) {+ const summary = await this.getSummary();+ if (summary.status === 'failed') {+ const error = new Error(`${action} is blocked by the production readiness gate. Fix ${summary.blockingFailures.join(', ')} and run the check again.`);+ error.status = 409;+ error.readiness = summary;+ throw error;+ }+ return summary;+ }++ async run(options = {}) {+ if (this.activeRun) {+ const error = new Error('A production readiness check is already running');+ error.status = 409;+ throw error;+ }++ this.activeRun = this.executeRun(options).finally(() => {+ this.activeRun = null;+ });+ return this.activeRun;+ }++ async executeRun(options) {+ const startedAt = this.now().toISOString();+ const id = this.db.generateId ? this.db.generateId('readiness') : `readiness_${Date.now()}`;+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-readiness-'));+ const checks = [];++ try {+ checks.push(await this.executeCheck('text_provider', 'AI text provider', true, () => this.probeText()));+ checks.push(await this.executeCheck('image_provider', 'Image provider', false, () => this.probeImage(tempDir, Boolean(options.includePaidMedia))));+ checks.push(await this.executeCheck('voice_narration', 'Voice narration', true, () => this.probeNarration(tempDir)));+ checks.push(await this.executeCheck('video_assembly', 'Audio/video assembly', true, () => this.probeVideoAssembly(tempDir)));+ checks.push(await this.executeCheck('youtube_access', 'YouTube channel access', true, () => this.probeYouTube()));+ checks.push(await this.executeCheck('upload_metadata', 'Upload metadata', true, () => this.probeMetadata()));++ const blockingFailures = checks.filter(check => check.blocking && check.status === 'failed');+ const warnings = checks.filter(check =>+ ['warning', 'skipped'].includes(check.status) || (!check.blocking && check.status === 'failed')+ );+ const status = blockingFailures.length ? 'failed' : warnings.length ? 'warning' : 'passed';+ const completedAt = this.now().toISOString();+ const result = {+ id,+ status,+ checks,+ summary: {+ passed: checks.filter(check => check.status === 'passed').length,+ warnings: warnings.length,+ failed: checks.filter(check => check.status === 'failed').length,+ blockingFailures: blockingFailures.map(check => check.id)+ },+ startedAt,+ completedAt+ };+ await this.db.saveReadinessRun(result);+ return { ...result, stale: false, blockingFailures: result.summary.blockingFailures };+ } finally {+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});+ }+ }++ async executeCheck(id, label, blocking, probe) {+ const started = Date.now();+ try {+ const result = await probe();+ return {+ id,+ label,+ blocking,+ status: result.status || 'passed',+ message: result.message,+ remediation: result.remediation || null,+ details: result.details || {},+ durationMs: Date.now() - started+ };+ } catch (error) {+ const safeMessage = this.safeError(error);+ this.logger.warn(`${label} readiness probe failed: ${safeMessage}`);+ return {+ id,+ label,+ blocking,+ status: 'failed',+ message: safeMessage,+ remediation: this.remediationFor(id),+ details: {},+ durationMs: Date.now() - started+ };+ }+ }++ async probeText() {+ if (this.probes.text) return this.probes.text();+ const service = new AITextService(this.credentialManager.credentials || {});+ if (!service.isAvailable()) throw new Error('No AI text provider is configured');+ const response = await service.generateText('Reply with exactly READY.', { maxTokens: 16, temperature: 0 });+ return { message: `${service.providerName} returned a live response.`, details: { provider: service.providerName, responseReceived: Boolean(response) } };+ }++ async probeImage(tempDir, includePaidMedia) {+ if (this.probes.image) return this.probes.image({ tempDir, includePaidMedia });+ const generator = new AIVideoGenerator(this.credentialManager.credentials || {});+ if (!generator.openai && !generator.gemini) {+ return { status: 'warning', message: 'No AI image provider is configured; gradient visuals will be used.', remediation: 'Configure OpenAI or Gemini image access if generated visuals are required.' };+ }+ if (!includePaidMedia) {+ return { status: 'skipped', message: 'Provider is configured; the paid live image probe was not requested.', remediation: 'Enable “Include paid image probe” on the next readiness run to verify image generation.' };+ }+ const outputPath = path.join(tempDir, 'readiness-image.png');+ await generator.generateImage('Simple red circle centered on a plain dark background, no text', outputPath);+ const stats = await fs.stat(outputPath);+ if (stats.size < 100) throw new Error('Image provider returned an empty or invalid asset');+ return { message: 'Image provider created a real test asset.', details: { bytes: stats.size } };+ }++ async probeNarration(tempDir) {+ if (this.probes.narration) return this.probes.narration({ tempDir });+ const generator = new AIVideoGenerator(this.credentialManager.credentials || {});+ const outputPath = path.join(tempDir, 'readiness-narration.mp3');+ const resultPath = await generator.generateTTSAudio('Production readiness audio check.', outputPath);+ if (path.extname(resultPath).toLowerCase() === '.info') throw new Error('No live narration provider is available; the pipeline returned a simulation');+ const stats = await fs.stat(resultPath);+ if (stats.size < 100) throw new Error('Narration provider returned an empty audio file');+ return { message: 'A live narration sample was generated.', details: { bytes: stats.size } };+ }++ async probeVideoAssembly(tempDir) {+ if (this.probes.videoAssembly) return this.probes.videoAssembly({ tempDir });+ if (!await checkFFmpeg()) throw new Error('FFmpeg is not available');+ const outputPath = path.join(tempDir, 'readiness-av.mp4');+ await runFFmpeg([+ '-y', '-f', 'lavfi', '-i', 'color=c=0x111827:s=320x180:d=1',+ '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1',+ '-c:v', 'mpeg4', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', outputPath+ ]);+ const buffer = await fs.readFile(outputPath);+ if (buffer.length < 1000 || buffer.subarray(4, 12).toString('ascii').indexOf('ftyp') === -1) {+ throw new Error('FFmpeg did not produce a valid MP4 container');+ }+ await runFFmpeg(['-v', 'error', '-i', outputPath, '-f', 'null', '-']);+ return { message: 'FFmpeg created and decoded a local MP4 containing audio and video.', details: { bytes: buffer.length } };+ }++ async probeYouTube() {+ if (this.probes.youtube) return this.probes.youtube();+ const youtube = this.credentialManager.getYouTubeClient();+ const response = await youtube.channels.list({ part: 'snippet,status', mine: true, maxResults: 1 });+ const channel = response.data?.items?.[0];+ if (!channel) throw new Error('The authorized Google account does not expose a YouTube channel');+ return {+ message: `Authorized channel access verified for ${channel.snippet?.title || 'the connected channel'}.`,+ details: { channelId: channel.id, channelTitle: channel.snippet?.title || null }+ };+ }++ async probeMetadata() {+ if (this.probes.metadata) return this.probes.metadata();+ const queue = await this.db.getPublishQueue();+ const candidates = queue.length ? queue : [{ title: 'Production readiness test', metadata: { seo: { title: 'Production readiness test', description: 'A safe local metadata validation sample for YouTube upload readiness.', tags: ['readiness', 'youtube', 'automation'], metadata: { category: 22, language: 'en' } } } }];+ const invalid = [];+ let warnings = 0;+ for (const item of candidates) {+ const result = validateYouTubeMetadata(item.metadata?.seo || item.metadata || { title: item.title });+ warnings += result.warnings.length;+ if (!result.valid) invalid.push({ productionId: item.productionId || null, title: item.title, errors: result.errors });+ }+ if (invalid.length) {+ const error = new Error(`${invalid.length} queued upload(s) have invalid YouTube metadata`);+ error.invalid = invalid;+ throw error;+ }+ return {+ status: warnings ? 'warning' : 'passed',+ message: queue.length ? `${queue.length} queued upload(s) passed metadata validation.` : 'Metadata rules passed with a safe local sample.',+ remediation: warnings ? 'Review queued descriptions and tags before publishing.' : null,+ details: { validated: candidates.length, queued: queue.length, warnings }+ };+ }++ safeError(error) {+ return String(error?.message || 'Probe failed')+ .replace(/sk-[A-Za-z0-9_-]+/g, '[redacted]')+ .replace(/AIza[A-Za-z0-9_-]+/g, '[redacted]')+ .replace(/Bearer\s+[A-Za-z0-9._~-]+/gi, 'Bearer [redacted]')+ .replace(/(access_token|refresh_token|api[_-]?key|token)=([^\s&]+)/gi, '$1=[redacted]')+ .slice(0, 500);+ }++ remediationFor(id) {+ const messages = {+ text_provider: 'Run npm run walkthrough, verify the selected model, and confirm provider credits or quota.',+ image_provider: 'Verify paid image access or rely on the built-in gradient visual fallback.',+ voice_narration: 'Configure OpenAI, Gemini TTS, ElevenLabs with a voice ID, or Azure Speech, then rerun.',+ video_assembly: 'Run npm install to restore ffmpeg-static, or configure FFMPEG_PATH to a working binary.',+ youtube_access: 'Reconnect YouTube in npm run walkthrough and ensure the Google account owns a channel.',+ upload_metadata: 'Edit the queued title, description, category, language, and tags before publishing.'+ };+ return messages[id] || 'Correct the configuration and rerun the readiness check.';+ }+}++module.exports = { ProductionReadinessService, STALE_AFTER_MS };diff --git a/utils/youtube-metadata-validator.js b/utils/youtube-metadata-validator.jsnew file mode 100644index 0000000..b3d21b2--- /dev/null+++ b/utils/youtube-metadata-validator.js@@ -0,0 +1,83 @@+const MAX_TITLE_LENGTH = 100;+const MAX_DESCRIPTION_LENGTH = 5000;+const MAX_TAGS_LENGTH = 450;++function removeControlCharacters(value, replacement = '') {+ return Array.from(String(value ?? '')).map(character => {+ const code = character.charCodeAt(0);+ return code <= 31 || code === 127 ? replacement : character;+ }).join('');+}++function cleanText(value) {+ return removeControlCharacters(value, ' ').replace(/\s+/g, ' ').trim();+}++function normalizeTags(input) {+ const values = Array.isArray(input) ? input : String(input || '').split(',');+ const unique = [];+ const seen = new Set();+ let totalLength = 0;++ for (const value of values) {+ const tag = cleanText(value).replace(/^#+/, '').replaceAll('"', '').slice(0, 100).trim();+ const key = tag.toLowerCase();+ if (!tag || seen.has(key)) continue;+ const nextLength = totalLength + tag.length + (unique.length ? 1 : 0);+ if (nextLength > MAX_TAGS_LENGTH || unique.length >= 30) break;+ unique.push(tag);+ seen.add(key);+ totalLength = nextLength;+ }++ return unique;+}++function normalizeYouTubeMetadata(metadata = {}) {+ const snippet = metadata.snippet || metadata.seo || metadata;+ return {+ title: cleanText(snippet.title).slice(0, MAX_TITLE_LENGTH),+ description: removeControlCharacters(snippet.description).slice(0, MAX_DESCRIPTION_LENGTH).trim(),+ tags: normalizeTags(snippet.tags),+ categoryId: String(snippet.categoryId ?? snippet.metadata?.category ?? '22').trim(),+ defaultLanguage: String(snippet.defaultLanguage ?? snippet.metadata?.language ?? 'en').trim(),+ defaultAudioLanguage: String(snippet.defaultAudioLanguage ?? snippet.metadata?.language ?? 'en').trim()+ };+}++function validateYouTubeMetadata(metadata = {}) {+ const value = normalizeYouTubeMetadata(metadata);+ const errors = [];+ const warnings = [];++ if (!value.title) errors.push('A video title is required.');+ if (value.title.length > MAX_TITLE_LENGTH) errors.push(`Title exceeds ${MAX_TITLE_LENGTH} characters.`);+ if (!value.description) warnings.push('The video description is empty.');+ if (value.description.length > MAX_DESCRIPTION_LENGTH) errors.push(`Description exceeds ${MAX_DESCRIPTION_LENGTH} characters.`);+ if (!/^\d{1,3}$/.test(value.categoryId)) errors.push('YouTube category must be a numeric category ID.');+ if (!/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(value.defaultLanguage)) errors.push('Default language must be a valid language code.');+ if (value.tags.length < 3) warnings.push('Fewer than three usable tags remain after validation.');++ return { valid: errors.length === 0, errors, warnings, value };+}++function assertValidYouTubeMetadata(metadata = {}) {+ const result = validateYouTubeMetadata(metadata);+ if (!result.valid) {+ const error = new Error(`YouTube metadata is invalid: ${result.errors.join(' ')}`);+ error.code = 'INVALID_YOUTUBE_METADATA';+ error.validation = result;+ throw error;+ }+ return result;+}++module.exports = {+ MAX_TITLE_LENGTH,+ MAX_DESCRIPTION_LENGTH,+ MAX_TAGS_LENGTH,+ normalizeTags,+ normalizeYouTubeMetadata,+ validateYouTubeMetadata,+ assertValidYouTubeMetadata+};