Skip to content

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

Add autonomous channel operator

darkzOGxed2602fc8ef1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8141568..c1fcfe5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Added a persistent Autonomous Channel Operator that turns a channel objective, audience, pillars, cadence, and guardrails into researched editorial plans and sequential end-to-end production runs
+- Added dashboard strategy controls, operator-run progress and cancellation, scheduled strategy execution, and approval-gated publishing handoff
- Added local-only activation milestones for setup, first real MP4, approval, publication, and repeat generation
- Added an explicit opt-in anonymous milestone reporter with no default endpoint
- Added reproducible GitHub growth baselines and public fork census reports
diff --git a/README.md b/README.md
index 54491a2..be8e6ae 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,7 @@ Research topics β†’ write scripts β†’ generate narration and visuals β†’ assembl
- **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.
- **Provider-flexible:** use Gemini, OpenAI, OpenRouter, Kimi, MiMo, GLM, or another OpenAI-compatible endpoint.
- **Observable:** follow persistent generation jobs, failures, review state, publishing, and local activation milestones from the dashboard.
@@ -38,6 +39,14 @@ Already know what you are doing? `npm run setup` offers a shorter classic flow,
Gemini offers free access for supported text and TTS usage. Gemini AI image generation currently requires paid-tier access; without an image provider, Lumen can assemble gradient-based visuals instead.
+### Run the Autonomous Channel Operator
+
+Open **Autonomous operator** in the dashboard and describe the channel outcomeβ€”not a task list. Set the objective, audience, content pillars, publishing cadence, success metric, and boundaries, then choose **Activate & run now**.
+
+Lumen refreshes YouTube trend and configured-competitor signals, checks recent channel topics, creates an evidence-labeled editorial plan, and sends each planned video through strategy, script, thumbnail, SEO, production, and workflow management. Active strategies also guide scheduled generation at the requested weekly cadence. Operator runs, decisions, progress, and failures persist in SQLite and remain visible in the dashboard.
+
+By default, finished videos wait for factual review, media-rights confirmation, and approval. Once approved, the existing publishing agent schedules and uploads them. Turning on autonomy does not bypass those gates, and simulated videos still cannot publish.
+
## From idea to published video
| Stage | What Lumen does | What you control |
@@ -57,14 +66,17 @@ For release history, see [CHANGELOG.md](CHANGELOG.md).
```mermaid
graph TD
- A[Content Strategy Agent] --> B[Script Writer Agent]
- B --> C[Thumbnail Designer Agent]
- B --> D[SEO Optimizer Agent]
- C --> E[Production Management Agent]
- D --> E
- E --> F[Publishing & Scheduling Agent]
- F --> G[Analytics & Optimization Agent]
- G -->|feedback loop| A
+ O[Autonomous Channel Operator] --> A[Research and Editorial Plan]
+ A --> B[Content Strategy Agent]
+ B --> C[Script Writer Agent]
+ C --> D[Thumbnail Designer Agent]
+ C --> E[SEO Optimizer Agent]
+ D --> F[Production Management Agent]
+ E --> F
+ F --> G[Review and Approval Gates]
+ G --> H[Publishing & Scheduling Agent]
+ H --> I[Analytics & Optimization Agent]
+ I -->|feedback loop| A
```
## How It Works
@@ -207,6 +219,8 @@ gantt
The scheduler runs automatically after `npm start`. Content generation at 06:00, publishing queue processed every 15 minutes, analytics at 09:00, optimization at 22:00. Weekly strategy reviews run on Sundays.
+When an active channel strategy exists, the 06:00 generation check uses its cadence and launches an autonomous research-and-production run when the content buffer needs work. Without an active strategy, the original topic-selection flow remains in place.
+
## API
```bash
@@ -222,6 +236,18 @@ curl -X POST http://localhost:3456/generate \
# inspect the returned background job
curl http://localhost:3456/api/jobs/:jobId
+# save a channel strategy
+curl -X PUT http://localhost:3456/api/operator/strategy \
+ -H "Content-Type: application/json" \
+ -H "x-api-key: $API_KEY" \
+ -d '{"objective":"Own practical AI automation for small teams","audience":"Small business operators","contentPillars":["AI workflows","Automation playbooks"],"cadencePerWeek":2,"videosPerRun":2,"defaultFormat":"tutorial","defaultLength":"medium","status":"draft"}'
+
+# activate the saved strategy and start a background operator run
+curl -X POST http://localhost:3456/api/operator/start \
+ -H "Content-Type: application/json" \
+ -H "x-api-key: $API_KEY" \
+ -d '{}'
+
# view schedule
curl http://localhost:3456/schedule
@@ -310,7 +336,7 @@ youtube-automation-agent/
β”œβ”€β”€ database/ # SQLite schema and access layer
β”œβ”€β”€ data/ # generated content and assets
β”œβ”€β”€ schedules/ # cron-based automation
-β”œβ”€β”€ utils/ # AI service wrappers, logging, credential management
+β”œβ”€β”€ utils/ # AI services, autonomous operator, logging, credential management
β”œβ”€β”€ .github/ # CI workflow (lint + tests on every push/PR)
└── index.js # Express server + agent initialization
```
diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.js
index 023dbde..0834c46 100644
--- a/agents/content-strategy-agent.js
+++ b/agents/content-strategy-agent.js
@@ -36,6 +36,7 @@ class ContentStrategyAgent {
// Analyze competitor channels
const competitors = await this.analyzeCompetitors();
+ this.competitorData = competitors;
// Combine insights
this.trendingTopics = this.mergeTrendData(trends, competitors);
@@ -255,6 +256,117 @@ class ContentStrategyAgent {
}
}
+ async researchAndPlanChannel(channelStrategy) {
+ const targetCount = Math.max(1, Math.min(5, Number(channelStrategy.videos_per_run || 1)));
+ await this.analyzeTrends();
+
+ const recentRows = await this.db.getAllRows(
+ "SELECT topic, created_at FROM content_strategies WHERE created_at >= datetime('now', '-90 days') ORDER BY created_at DESC LIMIT 50"
+ );
+ const signals = this.trendingTopics.slice(0, 15).map(item => ({
+ topic: item.topic,
+ score: Number(item.score || 0),
+ sources: [...new Set(item.sources || [])]
+ }));
+ const signalSources = new Set(signals.flatMap(signal => signal.sources));
+ const researchSources = [
+ ...(signalSources.has('trending') ? ['YouTube most-popular videos'] : []),
+ ...(signalSources.has('competitor') ? ['Configured competitor channels'] : []),
+ ...(recentRows.length ? ['Channel content history'] : [])
+ ];
+ const research = {
+ generatedAt: new Date().toISOString(),
+ sources: researchSources.length ? researchSources : ['No usable live signals returned; evergreen strategy fallback'],
+ signals,
+ recentTopics: recentRows.map(row => row.topic),
+ competitorChannelsAnalyzed: this.competitorData.length
+ };
+
+ let plan = await this.generateAutonomousPlanWithAI(channelStrategy, research, targetCount);
+ plan = this.normalizeAutonomousPlan(plan, channelStrategy, targetCount);
+ if (plan.length < targetCount) {
+ const fallback = this.buildFallbackAutonomousPlan(channelStrategy, research, targetCount);
+ plan = this.normalizeAutonomousPlan([...plan, ...fallback], channelStrategy, targetCount);
+ }
+
+ return { research, plan };
+ }
+
+ async generateAutonomousPlanWithAI(channelStrategy, research, targetCount) {
+ if (!this.aiTextService.isAvailable()) return [];
+ 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"}]
+
+Channel objective: ${channelStrategy.objective}
+Audience: ${channelStrategy.audience}
+Value proposition: ${channelStrategy.value_proposition || 'not specified'}
+Content pillars: ${(channelStrategy.contentPillars || []).join(', ')}
+Preferred format: ${channelStrategy.default_format}
+Preferred length: ${channelStrategy.default_length}
+Success metric: ${channelStrategy.success_metric || 'not specified'}
+Constraints: ${channelStrategy.constraints || 'none'}
+Research signals: ${JSON.stringify(research.signals)}
+Recent topics to avoid repeating: ${JSON.stringify(research.recentTopics)}
+
+Do not invent trend data, statistics, sources, or factual claims. Prefer evergreen topics when the supplied signals are weak.`;
+
+ try {
+ const response = await this.aiTextService.generateText(prompt, { maxTokens: 1800, temperature: 0.65 });
+ const parsed = this.parseAIJsonResponse(response);
+ return Array.isArray(parsed) ? parsed : Array.isArray(parsed.plan) ? parsed.plan : [];
+ } catch (error) {
+ this.logger.warn(`AI channel plan failed; using evidence-aware fallback: ${error.message}`);
+ return [];
+ }
+ }
+
+ buildFallbackAutonomousPlan(channelStrategy, research, targetCount) {
+ const recent = new Set(research.recentTopics.map(topic => String(topic).toLowerCase()));
+ const readableSignals = research.signals
+ .map(signal => signal.topic)
+ .filter(topic => topic.includes(' ') && topic.length >= 8 && !recent.has(topic.toLowerCase()));
+ const pillars = channelStrategy.contentPillars || [];
+ const pillarTopics = pillars.map(pillar => `${pillar}: a practical guide for ${channelStrategy.audience}`);
+ const candidates = [...readableSignals, ...pillarTopics, ...this.getEvergreenFallbackTopics()];
+
+ return candidates.slice(0, targetCount).map((topic, index) => ({
+ topic,
+ angle: `${topic} through the lens of ${channelStrategy.value_proposition || channelStrategy.objective}`,
+ rationale: readableSignals.includes(topic)
+ ? 'Matches a current YouTube or configured competitor signal and fits the channel strategy.'
+ : '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
+ }));
+ }
+
+ normalizeAutonomousPlan(plan, channelStrategy, targetCount) {
+ const formats = new Set(['explainer', 'tutorial', 'list', 'review', 'story']);
+ const lengths = new Set(['short', 'medium', 'long']);
+ const seen = new Set();
+ return plan
+ .map(item => ({
+ topic: String(item.topic || '').trim().slice(0, 200),
+ angle: String(item.angle || '').trim().slice(0, 500),
+ rationale: String(item.rationale || '').trim().slice(0, 1000),
+ format: formats.has(String(item.format || '').toLowerCase())
+ ? String(item.format).toLowerCase()
+ : channelStrategy.default_format,
+ length: lengths.has(String(item.length || '').toLowerCase())
+ ? String(item.length).toLowerCase()
+ : channelStrategy.default_length
+ }))
+ .filter(item => {
+ const key = item.topic.toLowerCase();
+ if (!item.topic || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
+ .slice(0, targetCount);
+ }
+
async generateContentStrategyWithAI(requestedTopic = null) {
if (!this.aiTextService.isAvailable()) {
this.logger.info('Using template content strategy generation because no AI text provider is configured');
diff --git a/agents/script-writer-agent.js b/agents/script-writer-agent.js
index 910a0aa..bd8c424 100644
--- a/agents/script-writer-agent.js
+++ b/agents/script-writer-agent.js
@@ -125,6 +125,9 @@ Tone: ${template.tone}
Pacing: ${template.pacing}
Brand voice: ${strategy.brandVoice || 'clear, credible, and engaging'}
Channel goal: ${strategy.channelGoal || 'help the viewer understand and act'}
+Channel value proposition: ${strategy.channelValueProposition || 'give the viewer practical value'}
+Editorial rationale: ${strategy.planRationale || 'fit the selected topic and audience'}
+Channel 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.`;
diff --git a/dashboard/app.js b/dashboard/app.js
index 8e6a543..9fd5e9f 100644
--- a/dashboard/app.js
+++ b/dashboard/app.js
@@ -137,6 +137,7 @@ function renderDashboard() {
renderIdeas(state.ideas);
renderAnalytics(state.analytics);
renderActivation(state.activation);
+ renderOperator(state.channelStrategy, state.operatorRuns || [], state.system);
populateSettings(state.profile, state.settings);
}
@@ -291,6 +292,63 @@ function renderActivation(activation = {}) {
}
}
+function renderOperator(strategy, runs, system) {
+ const form = $('#strategy-form');
+ const mapping = strategy ? {
+ objective: strategy.objective,
+ audience: strategy.audience,
+ valueProposition: strategy.value_proposition,
+ contentPillars: (strategy.contentPillars || []).join(', '),
+ cadencePerWeek: strategy.cadence_per_week,
+ videosPerRun: strategy.videos_per_run,
+ defaultFormat: strategy.default_format,
+ defaultLength: strategy.default_length,
+ successMetric: strategy.success_metric,
+ constraints: strategy.constraints
+ } : {};
+ for (const [name, value] of Object.entries(mapping)) {
+ if (form.elements[name] && document.activeElement !== form.elements[name]) form.elements[name].value = value ?? '';
+ }
+
+ const strategyStatus = strategy?.status || 'not_configured';
+ $('#operator-strategy-status').className = `status ${escapeHTML(strategyStatus)}`;
+ $('#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').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);
+ if (active) $('#cancel-operator-run').dataset.runId = run.id;
+
+ if (!run) {
+ $('#operator-run-title').textContent = 'Waiting for a strategy';
+ $('#operator-run-summary').innerHTML = empty('Save a channel mandate, then activate it to research and produce the first plan.');
+ $('#operator-plan').innerHTML = empty('No editorial plan yet.');
+ return;
+ }
+
+ $('#operator-run-title').textContent = `${label(run.stage)} Β· ${run.progress || 0}%`;
+ const sources = Array.isArray(run.research?.sources) ? run.research.sources.join(', ') : 'Research pending';
+ $('#operator-run-summary').innerHTML = `<div class="run-summary">
+ <div class="progress"><i style="width:${Math.max(0, Math.min(100, run.progress || 0))}%"></i></div>
+ <div class="run-summary-row"><span>Status</span><strong>${statusChip(run.status)}</strong></div>
+ <div class="run-summary-row"><span>Research</span><strong>${escapeHTML(sources)}</strong></div>
+ <div class="run-summary-row"><span>Produced</span><strong>${escapeHTML(run.summary?.generated || 0)} / ${escapeHTML(run.summary?.planned || run.plan?.length || 0)}</strong></div>
+ <div class="run-summary-row"><span>Needs review</span><strong>${escapeHTML(run.summary?.needsReview || 0)}</strong></div>
+ ${run.error ? `<p class="callout">${escapeHTML(run.error)}</p>` : ''}
+ </div>`;
+ const plan = Array.isArray(run.plan) ? run.plan : [];
+ $('#operator-plan').innerHTML = plan.length ? plan.map((item, index) => {
+ const job = (run.generatedJobs || []).find(candidate => candidate.topic === item.topic);
+ return `<article class="plan-card">
+ <div class="meta-line">${index + 1} Β· ${escapeHTML(item.format)} Β· ${escapeHTML(item.length)} ${job ? `Β· ${statusChip(job.reviewStatus || job.status)}` : ''}</div>
+ <strong>${escapeHTML(item.topic)}</strong>
+ <p>${escapeHTML(item.angle || item.rationale)}</p>
+ </article>`;
+ }).join('') : empty('Research and planning will appear here when the run begins.');
+}
+
function populateSettings(profile = {}, settings = {}) {
const form = $('#profile-form');
const mapping = {
@@ -317,6 +375,7 @@ function switchView(view) {
$$('.view').forEach(item => item.classList.toggle('active', item.id === `${view}-view`));
const titles = {
overview: ['OPERATOR OVERVIEW', 'Know what happens next.'],
+ operator: ['AUTONOMOUS OPERATOR', 'Give Lumen the strategy.'],
pipeline: ['CONTENT OPERATIONS', 'From idea to published.'],
calendar: ['EDITORIAL PLANNING', 'Plan before you generate.'],
analytics: ['PERFORMANCE', 'Turn results into the next move.'],
@@ -465,6 +524,39 @@ $('#automation-toggle').addEventListener('click', async () => {
await mutate(`/api/automation/${action}`, 'POST', {}, `Automation ${action}d.`).catch(() => {});
});
+function strategyFormData(status = ui.state?.channelStrategy?.status || 'draft') {
+ const form = $('#strategy-form');
+ const values = Object.fromEntries(new FormData(form));
+ return {
+ ...values,
+ contentPillars: values.contentPillars.split(',').map(value => value.trim()).filter(Boolean),
+ cadencePerWeek: Number(values.cadencePerWeek),
+ videosPerRun: Number(values.videosPerRun),
+ status
+ };
+}
+
+$('#strategy-form').addEventListener('submit', async event => {
+ event.preventDefault();
+ await mutate('/api/operator/strategy', 'PUT', strategyFormData(), 'Channel strategy saved.').catch(() => {});
+});
+
+$('#activate-operator-button').addEventListener('click', async () => {
+ if (!$('#strategy-form').reportValidity()) return;
+ await mutate('/api/operator/start', 'POST', strategyFormData('active'), 'Autonomous operator started.').catch(() => {});
+});
+
+$('#pause-operator-button').addEventListener('click', async () => {
+ await mutate('/api/operator/pause', 'POST', {}, 'Autonomous operator paused.').catch(() => {});
+});
+
+$('#cancel-operator-run').addEventListener('click', async event => {
+ const runId = event.currentTarget.dataset.runId;
+ if (runId && confirm('Stop this autonomous run after the current agent stage?')) {
+ await mutate(`/api/operator/runs/${encodeURIComponent(runId)}/cancel`, 'POST', {}, 'Operator stop requested.').catch(() => {});
+ }
+});
+
$('#generate-form').addEventListener('submit', async event => {
event.preventDefault();
const values = Object.fromEntries(new FormData(event.currentTarget));
@@ -504,6 +596,6 @@ $('#api-key-button').addEventListener('click', () => {
});
const initialView = location.hash.slice(1);
-if (['overview', 'pipeline', 'calendar', 'analytics', 'settings'].includes(initialView)) switchView(initialView);
+if (['overview', 'operator', 'pipeline', 'calendar', 'analytics', 'settings'].includes(initialView)) switchView(initialView);
refreshDashboard();
setInterval(() => refreshDashboard(true), 8000);
diff --git a/dashboard/index.html b/dashboard/index.html
index 10d962e..e417012 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -16,6 +16,7 @@
</a>
<nav aria-label="Main navigation">
<button class="nav-item active" data-view="overview"><span>βŒ‚</span> Overview</button>
+ <button class="nav-item" data-view="operator"><span>β—Ž</span> Autonomous operator</button>
<button class="nav-item" data-view="pipeline"><span>≋</span> Pipeline <b id="review-badge" class="badge hidden">0</b></button>
<button class="nav-item" data-view="calendar"><span>β–‘</span> Calendar & ideas</button>
<button class="nav-item" data-view="analytics"><span>⌁</span> Analytics</button>
@@ -74,6 +75,39 @@
</div>
</section>
+ <section id="operator-view" class="view">
+ <div class="section-intro"><div><h2>Autonomous Channel Operator</h2><p>Set the destination once. Lumen researches, plans, produces, and manages the channel workflow around it.</p></div><span id="operator-strategy-status" class="status">Not configured</span></div>
+ <div class="operator-grid">
+ <form id="strategy-form" class="panel settings-form">
+ <div class="panel-heading"><div><p class="eyebrow">CHANNEL MANDATE</p><h2>What should this channel achieve?</h2></div></div>
+ <div class="form-grid">
+ <label class="full-row"><span>Objective</span><textarea name="objective" rows="3" maxlength="1000" placeholder="Become the most trusted practical channel for small businesses adopting AI." required></textarea></label>
+ <label class="full-row"><span>Audience</span><textarea name="audience" rows="2" maxlength="500" placeholder="Owners and operators at 5–50 person service businesses" required></textarea></label>
+ <label class="full-row"><span>Value proposition</span><textarea name="valueProposition" rows="2" maxlength="1000" placeholder="Clear, tested advice viewers can apply this week"></textarea></label>
+ <label class="full-row"><span>Content pillars</span><input name="contentPillars" placeholder="AI workflows, automation playbooks, tool reviews" required><small>Separate 1–8 durable themes with commas.</small></label>
+ <label><span>Videos per week</span><input name="cadencePerWeek" type="number" min="1" max="7" value="1"></label>
+ <label><span>Videos per planning run</span><input name="videosPerRun" type="number" min="1" max="5" value="1"></label>
+ <label><span>Default format</span><select name="defaultFormat"><option value="explainer">Explainer</option><option value="tutorial">Tutorial</option><option value="list">List</option><option value="review">Review</option><option value="story">Story</option></select></label>
+ <label><span>Default length</span><select name="defaultLength"><option value="short">Short Β· 2–4 min</option><option value="medium">Medium Β· 8–12 min</option><option value="long">Long Β· 15–20 min</option></select></label>
+ <label class="full-row"><span>Success metric</span><input name="successMetric" maxlength="300" placeholder="Qualified subscribers and returning viewers"></label>
+ <label class="full-row"><span>Boundaries and constraints</span><textarea name="constraints" rows="3" maxlength="2000" placeholder="No hype, no unverified statistics, explain costs and tradeoffs."></textarea></label>
+ </div>
+ <p class="callout">The operator uses YouTube trend signals, configured competitors, and channel history. Publishing still obeys your quality, factual-review, rights, and approval gates.</p>
+ <div class="form-actions"><button type="submit" class="button secondary">Save strategy</button><button id="activate-operator-button" type="button" class="button primary">Activate & run now</button><button id="pause-operator-button" type="button" class="button danger hidden">Pause operator</button></div>
+ </form>
+ <div class="operator-side">
+ <article class="panel">
+ <div class="panel-heading"><div><p class="eyebrow">CURRENT RUN</p><h2 id="operator-run-title">Waiting for a strategy</h2></div><button id="cancel-operator-run" class="text-button hidden">Stop run</button></div>
+ <div id="operator-run-summary"></div>
+ </article>
+ <article class="panel">
+ <div class="panel-heading"><div><p class="eyebrow">EDITORIAL PLAN</p><h2>What Lumen decided to make</h2></div></div>
+ <div id="operator-plan" class="plan-list"></div>
+ </article>
+ </div>
+ </div>
+ </section>
+
<section id="pipeline-view" class="view">
<div class="section-intro"><div><h2>Content pipeline</h2><p>Every generated video, its real state, and the next available action.</p></div><select id="pipeline-filter"><option value="all">All content</option><option value="needs_review">Needs review</option><option value="needs_attention">Needs attention</option><option value="approved">Approved</option><option value="published">Published</option></select></div>
<div id="pipeline-list" class="pipeline-list"></div>
diff --git a/dashboard/styles.css b/dashboard/styles.css
index e202a05..4a9aa31 100644
--- a/dashboard/styles.css
+++ b/dashboard/styles.css
@@ -105,6 +105,16 @@ input:focus, textarea:focus, select:focus { border-color: #636d7c; box-shadow: 0
.pipeline-title span, .pipeline-col span { color: var(--muted); font-size: 11px; }
.pipeline-col strong { display: block; font-size: 13px; margin-top: 4px; }
.calendar-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
+.operator-grid { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(320px, .85fr); gap: 18px; align-items: start; }
+.operator-side { display: grid; gap: 18px; }
+.operator-grid .settings-form { max-width: none; }
+.plan-list { display: grid; gap: 10px; }
+.plan-card { border: 1px solid var(--line); background: rgba(255,255,255,.018); border-radius: 12px; padding: 14px; }
+.plan-card strong { display: block; line-height: 1.35; }
+.plan-card p { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 7px 0 0; }
+.run-summary { display: grid; gap: 12px; }
+.run-summary-row { display: flex; justify-content: space-between; gap: 16px; color: var(--muted); font-size: 12px; }
+.run-summary-row strong { color: var(--text); text-align: right; }
.date-chip { min-width: 52px; text-align: center; border: 1px solid var(--line); border-radius: 9px; padding: 7px; }
.date-chip strong, .date-chip small { display: block; }
.date-chip strong { font-size: 19px; }
@@ -158,7 +168,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 { grid-template-columns: 1fr; }
+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-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.js
index a64fdec..7106426 100644
--- a/database/db.js
+++ b/database/db.js
@@ -248,6 +248,39 @@ class Database {
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`,
+ `CREATE TABLE IF NOT EXISTS channel_strategies (
+ id TEXT PRIMARY KEY,
+ objective TEXT NOT NULL,
+ audience TEXT NOT NULL,
+ value_proposition TEXT,
+ content_pillars TEXT NOT NULL,
+ cadence_per_week INTEGER DEFAULT 1,
+ videos_per_run INTEGER DEFAULT 1,
+ default_format TEXT DEFAULT 'explainer',
+ default_length TEXT DEFAULT 'medium',
+ success_metric TEXT,
+ constraints TEXT,
+ status TEXT DEFAULT 'draft',
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+ `CREATE TABLE IF NOT EXISTS operator_runs (
+ id TEXT PRIMARY KEY,
+ strategy_id TEXT NOT NULL,
+ status TEXT DEFAULT 'queued',
+ stage TEXT DEFAULT 'queued',
+ progress INTEGER DEFAULT 0,
+ research TEXT,
+ plan TEXT,
+ generated_jobs TEXT,
+ summary TEXT,
+ error TEXT,
+ cancel_requested INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ completed_at TEXT,
+ FOREIGN KEY (strategy_id) REFERENCES channel_strategies(id)
+ )`,
`CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
@@ -602,6 +635,11 @@ class Database {
error = 'The application restarted before this job finished', updated_at = datetime('now'),
completed_at = datetime('now') WHERE status IN ('queued', 'running')`
);
+ await this.executeQuery(
+ `UPDATE operator_runs SET status = 'interrupted', stage = 'interrupted',
+ error = 'The application restarted before this operator run finished', updated_at = datetime('now'),
+ completed_at = datetime('now') WHERE status IN ('queued', 'running', 'cancelling')`
+ );
}
async saveContentReview(productionId, review = {}) {
@@ -686,6 +724,113 @@ class Database {
return this.getRow('SELECT * FROM content_ideas WHERE id = ?', [id]);
}
+ async getChannelStrategy() {
+ const row = await this.getRow("SELECT * FROM channel_strategies WHERE id = 'default'");
+ return row ? this.deserializeChannelStrategy(row) : null;
+ }
+
+ async saveChannelStrategy(strategy) {
+ const current = await this.getChannelStrategy() || {};
+ await this.executeQuery(
+ `INSERT INTO channel_strategies (
+ id, objective, audience, value_proposition, content_pillars, cadence_per_week,
+ videos_per_run, default_format, default_length, success_metric, constraints,
+ status, created_at, updated_at
+ ) VALUES ('default', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')), datetime('now'))
+ ON CONFLICT(id) DO UPDATE SET
+ objective = excluded.objective, audience = excluded.audience,
+ value_proposition = excluded.value_proposition, content_pillars = excluded.content_pillars,
+ cadence_per_week = excluded.cadence_per_week, videos_per_run = excluded.videos_per_run,
+ default_format = excluded.default_format, default_length = excluded.default_length,
+ success_metric = excluded.success_metric, constraints = excluded.constraints,
+ status = excluded.status, updated_at = datetime('now')`,
+ [
+ strategy.objective ?? current.objective ?? '',
+ strategy.audience ?? current.audience ?? '',
+ strategy.valueProposition ?? current.value_proposition ?? '',
+ JSON.stringify(strategy.contentPillars ?? current.contentPillars ?? []),
+ strategy.cadencePerWeek ?? current.cadence_per_week ?? 1,
+ strategy.videosPerRun ?? current.videos_per_run ?? 1,
+ strategy.defaultFormat ?? current.default_format ?? 'explainer',
+ strategy.defaultLength ?? current.default_length ?? 'medium',
+ strategy.successMetric ?? current.success_metric ?? '',
+ strategy.constraints ?? current.constraints ?? '',
+ strategy.status ?? current.status ?? 'draft',
+ current.created_at || null
+ ]
+ );
+ return this.getChannelStrategy();
+ }
+
+ deserializeChannelStrategy(row) {
+ return {
+ ...row,
+ contentPillars: JSON.parse(row.content_pillars || '[]')
+ };
+ }
+
+ async createOperatorRun(strategyId = 'default') {
+ const id = this.generateId('operator');
+ await this.executeQuery(
+ `INSERT INTO operator_runs (id, strategy_id, research, plan, generated_jobs, summary)
+ VALUES (?, ?, '{}', '[]', '[]', '{}')`,
+ [id, strategyId]
+ );
+ return this.getOperatorRun(id);
+ }
+
+ async getOperatorRun(id) {
+ const row = await this.getRow('SELECT * FROM operator_runs WHERE id = ?', [id]);
+ return row ? this.deserializeOperatorRun(row) : null;
+ }
+
+ async getActiveOperatorRun() {
+ const row = await this.getRow(
+ "SELECT * FROM operator_runs WHERE status IN ('queued', 'running', 'cancelling') ORDER BY created_at DESC LIMIT 1"
+ );
+ return row ? this.deserializeOperatorRun(row) : null;
+ }
+
+ async listOperatorRuns(limit = 10) {
+ const rows = await this.getAllRows('SELECT * FROM operator_runs ORDER BY created_at DESC LIMIT ?', [limit]);
+ return rows.map(row => this.deserializeOperatorRun(row));
+ }
+
+ async updateOperatorRun(id, changes = {}) {
+ const current = await this.getOperatorRun(id);
+ if (!current) return null;
+ await this.executeQuery(
+ `UPDATE operator_runs SET status = ?, stage = ?, progress = ?, research = ?, plan = ?,
+ generated_jobs = ?, summary = ?, error = ?, cancel_requested = ?,
+ updated_at = datetime('now'), completed_at = ? WHERE id = ?`,
+ [
+ changes.status ?? current.status,
+ changes.stage ?? current.stage,
+ changes.progress ?? current.progress,
+ JSON.stringify(changes.research ?? current.research ?? {}),
+ JSON.stringify(changes.plan ?? current.plan ?? []),
+ JSON.stringify(changes.generatedJobs ?? current.generatedJobs ?? []),
+ JSON.stringify(changes.summary ?? current.summary ?? {}),
+ changes.error === undefined ? current.error : changes.error,
+ changes.cancelRequested === undefined ? current.cancel_requested : Number(changes.cancelRequested),
+ changes.completedAt === undefined ? current.completed_at : changes.completedAt,
+ id
+ ]
+ );
+ return this.getOperatorRun(id);
+ }
+
+ deserializeOperatorRun(row) {
+ return {
+ ...row,
+ research: JSON.parse(row.research || '{}'),
+ plan: JSON.parse(row.plan || '[]'),
+ generatedJobs: JSON.parse(row.generated_jobs || '[]'),
+ summary: JSON.parse(row.summary || '{}'),
+ cancelRequested: Boolean(row.cancel_requested)
+ };
+ }
+
async createNotification(notification) {
const id = this.generateId('notice');
await this.executeQuery(
diff --git a/index.js b/index.js
index a617417..2c623f6 100644
--- a/index.js
+++ b/index.js
@@ -15,6 +15,7 @@ const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-ag
const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');
const { DailyAutomation } = require('./schedules/daily-automation');
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 { version } = require('./package.json');
@@ -30,6 +31,7 @@ class YouTubeAutomationAgent {
this.isInitialized = false;
this.activeJobs = new Map();
this.operator = null;
+ this.autonomous = null;
this.activation = null;
this.telemetry = null;
this.setupRequired = false;
@@ -46,6 +48,15 @@ class YouTubeAutomationAgent {
await this.db.initialize();
await this.db.markInterruptedJobs();
this.operator = new OperatorService(this.db);
+ this.autonomous = new AutonomousChannelOperator(this.db, {
+ researchAndPlan: strategy => {
+ if (!this.agents.strategy) throw new Error('The strategy agent is not configured');
+ return this.agents.strategy.researchAndPlanChannel(strategy);
+ },
+ startGenerationJob: input => this.startGenerationJob(input),
+ waitForGenerationJob: jobId => this.waitForGenerationJob(jobId),
+ notify: notification => this.operator.notify(notification)
+ });
this.activation = new ActivationMetrics(this.db);
this.telemetry = new AnonymousTelemetry(this.db, this.logger);
@@ -80,7 +91,7 @@ class YouTubeAutomationAgent {
// Initialize scheduler
this.logger.info('Setting up automation scheduler...');
this.scheduler = new DailyAutomation(this.agents, this.db, {
- generateContent: input => this.startGenerationJob(input)
+ generateContent: input => this.queueScheduledContent(input)
});
await this.scheduler.initialize();
@@ -178,7 +189,8 @@ class YouTubeAutomationAgent {
const value = {
topic: null,
style: null,
- length: typeof body.length === 'string' ? body.length.toLowerCase() : 'medium'
+ length: typeof body.length === 'string' ? body.length.toLowerCase() : 'medium',
+ strategyContext: null
};
// JSON has no `undefined`, so clients send `null` to mean "no value provided".
@@ -226,8 +238,75 @@ class YouTubeAutomationAgent {
return { valid: false, status: 400, error: 'length must be short, medium, or long' };
}
+ if (body.strategyContext !== undefined && body.strategyContext !== null) {
+ if (typeof body.strategyContext !== 'object' || Array.isArray(body.strategyContext)) {
+ return { valid: false, status: 400, error: 'strategyContext must be an object' };
+ }
+ const limits = { angle: 500, rationale: 1000, audience: 500, objective: 1000, valueProposition: 1000, constraints: 2000 };
+ value.strategyContext = {};
+ for (const [key, max] of Object.entries(limits)) {
+ if (body.strategyContext[key] === undefined || body.strategyContext[key] === null) continue;
+ if (typeof body.strategyContext[key] !== 'string' || body.strategyContext[key].length > max) {
+ return { valid: false, status: 400, error: `strategyContext.${key} must be a string of ${max} characters or less` };
+ }
+ value.strategyContext[key] = body.strategyContext[key].trim();
+ }
+ }
+
return { valid: true, value };
}
+
+ validateChannelStrategy(body = {}, current = {}) {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw new Error('Channel strategy must be a JSON object');
+ }
+ const text = (key, fallback, max) => {
+ const value = String(body[key] ?? fallback ?? '').trim();
+ if (value.length > max) throw new Error(`${key} must be ${max} characters or less`);
+ return value;
+ };
+ const objective = text('objective', current.objective, 1000);
+ const audience = text('audience', current.audience, 500);
+ if (!objective) throw new Error('A channel objective is required');
+ if (!audience) throw new Error('A target audience is required');
+
+ const rawPillars = body.contentPillars ?? current.contentPillars ?? [];
+ if (!Array.isArray(rawPillars)) throw new Error('contentPillars must be an array');
+ const contentPillars = rawPillars.map(value => String(value).trim()).filter(Boolean);
+ if (!contentPillars.length || contentPillars.length > 8 || contentPillars.some(value => value.length > 100)) {
+ throw new Error('Provide 1 to 8 content pillars, each 100 characters or less');
+ }
+
+ const integer = (key, fallback, min, max) => {
+ const value = Number(body[key] ?? fallback);
+ if (!Number.isInteger(value) || value < min || value > max) {
+ throw new Error(`${key} must be an integer from ${min} to ${max}`);
+ }
+ return value;
+ };
+ const defaultFormat = text('defaultFormat', current.default_format || 'explainer', 20).toLowerCase();
+ const defaultLength = text('defaultLength', current.default_length || 'medium', 20).toLowerCase();
+ const status = text('status', current.status || 'draft', 20).toLowerCase();
+ if (!['explainer', 'tutorial', 'list', 'review', 'story'].includes(defaultFormat)) {
+ throw new Error('defaultFormat is not supported');
+ }
+ if (!['short', 'medium', 'long'].includes(defaultLength)) throw new Error('defaultLength is not supported');
+ if (!['draft', 'active', 'paused'].includes(status)) throw new Error('status must be draft, active, or paused');
+
+ return {
+ objective,
+ audience,
+ valueProposition: text('valueProposition', current.value_proposition, 1000),
+ contentPillars,
+ cadencePerWeek: integer('cadencePerWeek', current.cadence_per_week || 1, 1, 7),
+ videosPerRun: integer('videosPerRun', current.videos_per_run || 1, 1, 5),
+ defaultFormat,
+ defaultLength,
+ successMetric: text('successMetric', current.success_metric, 300),
+ constraints: text('constraints', current.constraints, 2000),
+ status
+ };
+ }
setupAPI() {
this.app.use(express.json({ limit: '1mb' }));
this.app.use(express.static(path.join(__dirname, 'dashboard')));
@@ -317,7 +396,7 @@ class YouTubeAutomationAgent {
this.app.get('/api/dashboard', async (_req, res) => {
try {
- const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, activation] = await Promise.all([
+ const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, activation, channelStrategy, operatorRuns] = await Promise.all([
this.db.getStats(),
this.db.listGenerationJobs(20),
this.db.getPipelineOverview(50),
@@ -332,18 +411,22 @@ class YouTubeAutomationAgent {
: Promise.resolve({ totalVideos: 0, averagePerformanceScore: 0, topPerformers: [], insights: [] }),
this.activation
? this.activation.getSummary()
- : Promise.resolve({ privacy: 'local-only', counts: {}, milestones: {} })
+ : Promise.resolve({ privacy: 'local-only', counts: {}, milestones: {} }),
+ this.db.getChannelStrategy(),
+ this.db.listOperatorRuns(10)
]);
if (this.telemetry) void this.telemetry.sync(activation);
res.json({
stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, activation,
+ channelStrategy, operatorRuns,
system: {
initialized: this.isInitialized,
setupRequired: this.setupRequired,
uptime: process.uptime(),
activeJobs: this.activeJobs.size,
automationPaused: this.scheduler ? !this.scheduler.isEnabled : true,
- agents: Object.keys(this.agents)
+ agents: Object.keys(this.agents),
+ autonomousRunning: Boolean(await this.db.getActiveOperatorRun())
}
});
} catch (error) {
@@ -460,6 +543,49 @@ class YouTubeAutomationAgent {
}
});
+ this.app.put('/api/operator/strategy', protect, async (req, res) => {
+ try {
+ const current = await this.db.getChannelStrategy() || {};
+ const strategy = this.validateChannelStrategy(req.body || {}, current);
+ return res.json({ success: true, result: await this.db.saveChannelStrategy(strategy) });
+ } catch (error) {
+ return res.status(400).json({ success: false, error: error.message });
+ }
+ });
+
+ this.app.post('/api/operator/start', protect, async (req, res) => {
+ try {
+ if (this.setupRequired || !this.agents.strategy) {
+ return res.status(503).json({ success: false, error: 'Finish setup with npm run walkthrough before activating the autonomous operator' });
+ }
+ 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' });
+ }
+ const current = await this.db.getChannelStrategy() || {};
+ const strategy = this.validateChannelStrategy({ ...(req.body || {}), status: 'active' }, current);
+ const saved = await this.db.saveChannelStrategy(strategy);
+ const run = await this.autonomous.start(saved);
+ return res.status(202).json({ success: true, result: run });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message });
+ }
+ });
+
+ this.app.post('/api/operator/pause', protect, async (_req, res) => {
+ const strategy = await this.db.getChannelStrategy();
+ if (!strategy) return res.status(404).json({ error: 'Channel strategy not found' });
+ const active = await this.db.getActiveOperatorRun();
+ if (active) await this.autonomous.cancel(active.id);
+ const saved = await this.db.saveChannelStrategy({ ...strategy, status: 'paused' });
+ return res.json({ success: true, result: saved });
+ });
+
+ this.app.post('/api/operator/runs/:runId/cancel', protect, async (req, res) => {
+ const run = await this.autonomous.cancel(req.params.runId);
+ if (!run) return res.status(404).json({ error: 'Operator run not found' });
+ return res.json({ success: true, result: run });
+ });
+
this.app.post('/api/ideas', protect, async (req, res) => {
const topic = String(req.body?.topic || '').trim();
if (!topic || topic.length > 200) return res.status(400).json({ error: 'A topic of 200 characters or less is required' });
@@ -542,10 +668,38 @@ class YouTubeAutomationAgent {
return job;
}
+ async waitForGenerationJob(jobId) {
+ const work = this.activeJobs.get(jobId);
+ if (work) await work;
+ const job = await this.db.getGenerationJob(jobId);
+ if (!job) throw new Error(`Generation job ${jobId} was not found after it ran`);
+ return job;
+ }
+
+ async queueScheduledContent(input = {}) {
+ const strategy = await this.db.getChannelStrategy();
+ if (strategy?.status === 'active') {
+ const weeklyOutput = await this.db.getRow(
+ `SELECT COUNT(*) AS count FROM generation_jobs
+ WHERE source = 'autonomous_operator' AND status = 'completed'
+ AND created_at >= datetime('now', '-7 days')`
+ );
+ const remaining = Math.max(1, strategy.cadence_per_week - Number(weeklyOutput?.count || 0));
+ return this.autonomous.start({
+ ...strategy,
+ videos_per_run: Math.min(strategy.videos_per_run, remaining)
+ });
+ }
+ return this.startGenerationJob(input);
+ }
+
async runGenerationJob(jobId, input) {
try {
await this.db.updateGenerationJob(jobId, { status: 'running', stage: 'starting', progress: 2, error: null });
- const result = await this.generateContent(input.topic, input.style, input.length, { jobId });
+ const result = await this.generateContent(input.topic, input.style, input.length, {
+ jobId,
+ strategyContext: input.strategyContext
+ });
await this.db.updateGenerationJob(jobId, {
status: 'completed',
stage: result.reviewStatus === 'approved' ? 'scheduled' : result.reviewStatus,
@@ -589,7 +743,7 @@ class YouTubeAutomationAgent {
async generateContent(topic = null, style = null, length = 'medium', options = {}) {
this.logger.info('Starting content generation pipeline...');
- const { jobId = null } = options;
+ const { jobId = null, strategyContext = {} } = options;
const profile = await this.db.getChannelProfile() || {};
const lengthLabels = { short: '2-4 minutes', medium: '8-12 minutes', long: '15-20 minutes' };
@@ -604,9 +758,13 @@ class YouTubeAutomationAgent {
strategy.requestedStyle = requestedStyle;
strategy.requestedLengthKey = length;
strategy.requestedLength = lengthLabels[length] || lengthLabels.medium;
- strategy.targetAudience = profile.target_audience || strategy.targetAudience;
+ strategy.angle = strategyContext.angle || strategy.angle;
+ strategy.planRationale = strategyContext.rationale || null;
+ strategy.targetAudience = strategyContext.audience || profile.target_audience || strategy.targetAudience;
strategy.brandVoice = profile.brand_voice || null;
- strategy.channelGoal = profile.goal || null;
+ strategy.channelGoal = strategyContext.objective || profile.goal || null;
+ strategy.channelValueProposition = strategyContext.valueProposition || null;
+ strategy.channelConstraints = strategyContext.constraints || null;
strategy.callToAction = profile.call_to_action || null;
this.logger.info(`Strategy generated: ${strategy.topic}`);
diff --git a/schedules/daily-automation.js b/schedules/daily-automation.js
index 515294b..1cb3a03 100644
--- a/schedules/daily-automation.js
+++ b/schedules/daily-automation.js
@@ -176,8 +176,24 @@ class DailyAutomation {
}
// Check posting frequency settings
- const frequency = await this.db.getSetting('posting_frequency') || 'daily';
const lastGeneration = await this.db.getSetting('last_content_generation');
+ const channelStrategy = this.db.getChannelStrategy ? await this.db.getChannelStrategy() : null;
+
+ if (channelStrategy?.status === 'active') {
+ const weeklyOutput = await this.db.getRow(
+ `SELECT COUNT(*) AS count FROM generation_jobs
+ WHERE source = 'autonomous_operator' AND status = 'completed'
+ AND created_at >= datetime('now', '-7 days')`
+ );
+ if (Number(weeklyOutput?.count || 0) >= channelStrategy.cadence_per_week) return false;
+ if (!lastGeneration) return true;
+ const daysSinceLastGeneration = Math.floor(
+ (new Date() - new Date(lastGeneration)) / (1000 * 60 * 60 * 24)
+ );
+ return daysSinceLastGeneration >= 1;
+ }
+
+ const frequency = await this.db.getSetting('posting_frequency') || 'daily';
if (lastGeneration) {
const lastDate = new Date(lastGeneration);
diff --git a/test.js b/test.js
index dc8991a..1755ba6 100644
--- a/test.js
+++ b/test.js
@@ -21,6 +21,7 @@ class SystemTest {
{ name: 'Local Activation Metrics', test: () => this.testActivationMetrics() },
{ name: 'Anonymous Telemetry Opt-in', test: () => this.testAnonymousTelemetryOptIn() },
{ name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },
+ { name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },
{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },
{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },
{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },
@@ -287,10 +288,19 @@ class SystemTest {
!response.ok ||
!Array.isArray(dashboard.jobs) ||
!Array.isArray(dashboard.pipeline) ||
+ !Array.isArray(dashboard.operatorRuns) ||
dashboard.activation?.privacy !== 'local-only'
) {
throw new Error('Operator dashboard API did not return its data contract');
}
+ const unavailableStart = await fetch(`http://127.0.0.1:${port}/api/operator/start`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}'
+ });
+ if (unavailableStart.status !== 503) {
+ throw new Error('Autonomous operator did not fail closed when its strategy agent was unavailable');
+ }
} finally {
if (server) await new Promise(resolve => server.close(resolve));
if (job) await db.executeQuery('DELETE FROM generation_jobs WHERE id = ?', [job.id]);
@@ -300,6 +310,97 @@ class SystemTest {
this.logger.info('Operator workflow API test completed successfully');
}
+ async testAutonomousChannelOperator() {
+ const { ContentStrategyAgent } = require('./agents/content-strategy-agent');
+ const { AutonomousChannelOperator } = require('./utils/autonomous-channel-operator');
+ const db = new Database();
+ await db.initialize();
+ const previousStrategy = await db.getChannelStrategy();
+ let run;
+
+ try {
+ const strategy = await db.saveChannelStrategy({
+ objective: 'Teach small teams to automate useful work',
+ audience: 'Small business operators',
+ valueProposition: 'Practical steps without hype',
+ contentPillars: ['AI workflows', 'Automation playbooks'],
+ cadencePerWeek: 2,
+ videosPerRun: 2,
+ defaultFormat: 'tutorial',
+ defaultLength: 'short',
+ successMetric: 'Returning viewers',
+ constraints: 'Do not invent statistics',
+ status: 'active'
+ });
+ if (strategy.contentPillars.length !== 2 || strategy.cadence_per_week !== 2) {
+ throw new Error('Channel strategy was not persisted correctly');
+ }
+
+ const strategyAgent = new ContentStrategyAgent(db, {});
+ strategyAgent.analyzeTrends = async function() {
+ this.trendingTopics = [{ topic: 'practical AI workflows', score: 8, sources: ['trending'] }];
+ this.competitorData = [];
+ };
+ const planned = await strategyAgent.researchAndPlanChannel(strategy);
+ if (planned.plan.length !== 2 || !planned.research.sources.includes('YouTube most-popular videos')) {
+ throw new Error('Strategy did not produce an evidence-labeled autonomous plan');
+ }
+
+ const receivedInputs = [];
+ const operator = new AutonomousChannelOperator(db, {
+ researchAndPlan: async () => planned,
+ startGenerationJob: async input => {
+ receivedInputs.push(input);
+ return { id: `fake-job-${receivedInputs.length}` };
+ },
+ waitForGenerationJob: async jobId => ({
+ id: jobId,
+ status: 'completed',
+ production_id: `production-${jobId}`,
+ details: { reviewStatus: 'needs_review' }
+ })
+ });
+ run = await operator.start(strategy);
+ await operator.activeRuns.get(run.id);
+ const completed = await db.getOperatorRun(run.id);
+ if (
+ completed.status !== 'waiting_review' ||
+ completed.generatedJobs.length !== 2 ||
+ receivedInputs.some(input => input.source !== 'autonomous_operator' || !input.strategyContext?.angle)
+ ) {
+ throw new Error('Autonomous operator did not execute the planned workflow');
+ }
+ } finally {
+ if (run) {
+ const stored = await db.getOperatorRun(run.id);
+ for (const item of stored?.generatedJobs || []) {
+ if (item.ideaId) await db.executeQuery('DELETE FROM content_ideas WHERE id = ?', [item.ideaId]);
+ }
+ await db.executeQuery('DELETE FROM operator_runs WHERE id = ?', [run.id]);
+ }
+ if (previousStrategy) {
+ await db.saveChannelStrategy({
+ objective: previousStrategy.objective,
+ audience: previousStrategy.audience,
+ valueProposition: previousStrategy.value_proposition,
+ contentPillars: previousStrategy.contentPillars,
+ cadencePerWeek: previousStrategy.cadence_per_week,
+ videosPerRun: previousStrategy.videos_per_run,
+ defaultFormat: previousStrategy.default_format,
+ defaultLength: previousStrategy.default_length,
+ successMetric: previousStrategy.success_metric,
+ constraints: previousStrategy.constraints,
+ status: previousStrategy.status
+ });
+ } else {
+ await db.executeQuery("DELETE FROM channel_strategies WHERE id = 'default'");
+ }
+ await db.close();
+ }
+
+ this.logger.info('Autonomous channel operator test completed successfully');
+ }
+
async testAPIValidationAndSecurity() {
const { YouTubeAutomationAgent } = require('./index');
const agent = new YouTubeAutomationAgent();
diff --git a/utils/autonomous-channel-operator.js b/utils/autonomous-channel-operator.js
new file mode 100644
index 0000000..86bad23
--- /dev/null
+++ b/utils/autonomous-channel-operator.js
@@ -0,0 +1,181 @@
+const { Logger } = require('./logger');
+
+class AutonomousChannelOperator {
+ constructor(db, options = {}) {
+ this.db = db;
+ this.researchAndPlan = options.researchAndPlan;
+ this.startGenerationJob = options.startGenerationJob;
+ this.waitForGenerationJob = options.waitForGenerationJob;
+ this.notify = options.notify || (async () => null);
+ this.logger = new Logger('AutonomousOperator');
+ this.activeRuns = new Map();
+ }
+
+ async start(strategy) {
+ if (!strategy || strategy.status !== 'active') {
+ const error = new Error('Save and activate a channel strategy before starting the autonomous operator');
+ error.status = 409;
+ throw error;
+ }
+ const active = await this.db.getActiveOperatorRun();
+ if (active || this.activeRuns.size) {
+ const error = new Error('An autonomous operator run is already active');
+ error.status = 409;
+ throw error;
+ }
+
+ const run = await this.db.createOperatorRun(strategy.id);
+ const work = this.execute(run.id, strategy)
+ .catch(error => this.logger.error(`Operator run ${run.id} failed:`, error))
+ .finally(() => this.activeRuns.delete(run.id));
+ this.activeRuns.set(run.id, work);
+ return run;
+ }
+
+ async execute(runId, strategy) {
+ try {
+ await this.update(runId, { status: 'running', stage: 'researching', progress: 5, error: null });
+ const { research, plan } = await this.researchAndPlan(strategy);
+ if (!plan.length) throw new Error('Research did not produce any usable content ideas');
+ await this.assertNotCancelled(runId);
+ await this.update(runId, { stage: 'planning', progress: 20, research, plan });
+
+ const generatedJobs = [];
+ for (let index = 0; index < plan.length; index++) {
+ await this.assertNotCancelled(runId);
+ const item = plan[index];
+ const idea = await this.db.createContentIdea({
+ topic: item.topic,
+ angle: item.angle,
+ style: item.format,
+ status: 'generating',
+ rationale: item.rationale
+ });
+ const progress = 20 + Math.round((index / plan.length) * 70);
+ await this.update(runId, {
+ stage: `producing_${index + 1}_of_${plan.length}`,
+ progress,
+ generatedJobs
+ });
+
+ const record = { jobId: null, ideaId: idea.id, topic: item.topic, status: 'queued' };
+ generatedJobs.push(record);
+ try {
+ await this.update(runId, { generatedJobs });
+ await this.assertNotCancelled(runId);
+ const job = await this.startGenerationJob({
+ topic: item.topic,
+ style: item.format,
+ length: item.length,
+ source: 'autonomous_operator',
+ strategyContext: {
+ angle: item.angle,
+ rationale: item.rationale,
+ audience: strategy.audience,
+ objective: strategy.objective,
+ valueProposition: strategy.value_proposition,
+ constraints: strategy.constraints
+ }
+ });
+ record.jobId = job.id;
+ record.status = 'running';
+ await this.update(runId, { generatedJobs });
+ const completed = await this.waitForGenerationJob(job.id);
+ record.status = completed.status;
+ record.productionId = completed.production_id || null;
+ record.reviewStatus = completed.details?.reviewStatus || null;
+ record.error = completed.error || null;
+ await this.db.updateContentIdea(idea.id, {
+ status: completed.status === 'completed' ? 'generated' : 'failed'
+ });
+ } catch (error) {
+ record.status = error.code === 'OPERATOR_CANCELLED' ? 'cancelled' : 'failed';
+ record.error = error.message;
+ await this.db.updateContentIdea(idea.id, { status: 'failed' });
+ if (error.code === 'OPERATOR_CANCELLED') throw error;
+ }
+ await this.update(runId, {
+ progress: 20 + Math.round(((index + 1) / plan.length) * 70),
+ generatedJobs
+ });
+ }
+
+ const completed = generatedJobs.filter(job => job.status === 'completed');
+ const needsReview = completed.filter(job => ['needs_review', 'needs_attention'].includes(job.reviewStatus));
+ const failed = generatedJobs.filter(job => job.status !== 'completed');
+ const allFailed = completed.length === 0 && failed.length > 0;
+ const status = allFailed ? 'failed' : needsReview.length ? 'waiting_review' : failed.length ? 'completed_with_issues' : 'completed';
+ const summary = {
+ planned: plan.length,
+ generated: completed.length,
+ needsReview: needsReview.length,
+ failed: failed.length
+ };
+ await this.update(runId, {
+ status,
+ stage: allFailed ? 'failed' : needsReview.length ? 'waiting_for_review' : 'complete',
+ progress: 100,
+ generatedJobs,
+ summary,
+ error: allFailed ? 'Every planned video failed during generation' : null,
+ completedAt: new Date().toISOString()
+ });
+ await this.notify({
+ type: 'autonomous_run_complete',
+ level: failed.length ? 'warning' : 'success',
+ title: needsReview.length ? 'Autonomous plan is ready for review' : 'Autonomous plan completed',
+ message: `${completed.length} of ${plan.length} planned videos finished production.`,
+ data: { runId, ...summary }
+ });
+ } catch (error) {
+ const cancelled = error.code === 'OPERATOR_CANCELLED';
+ await this.update(runId, {
+ status: cancelled ? 'cancelled' : 'failed',
+ stage: cancelled ? 'cancelled' : 'failed',
+ error: error.message,
+ completedAt: new Date().toISOString()
+ });
+ if (!cancelled) {
+ await this.notify({
+ type: 'autonomous_run_failure',
+ level: 'error',
+ title: 'Autonomous channel run failed',
+ message: error.message,
+ data: { runId }
+ });
+ }
+ throw error;
+ }
+ }
+
+ async cancel(runId) {
+ const run = await this.db.getOperatorRun(runId);
+ if (!run) return null;
+ if (!['queued', 'running', 'cancelling'].includes(run.status)) return run;
+ for (const item of run.generatedJobs) {
+ const job = await this.db.getGenerationJob(item.jobId);
+ if (job && ['queued', 'running'].includes(job.status)) {
+ await this.db.updateGenerationJob(job.id, {
+ cancelRequested: true,
+ details: { cancelReason: 'Autonomous operator stopped by the channel owner' }
+ });
+ }
+ }
+ return this.update(runId, { status: 'cancelling', cancelRequested: true });
+ }
+
+ async assertNotCancelled(runId) {
+ const run = await this.db.getOperatorRun(runId);
+ if (run?.cancelRequested) {
+ const error = new Error('Autonomous operator stopped by the channel owner');
+ error.code = 'OPERATOR_CANCELLED';
+ throw error;
+ }
+ }
+
+ update(runId, changes) {
+ return this.db.updateOperatorRun(runId, changes);
+ }
+}
+
+module.exports = { AutonomousChannelOperator };