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.

feat: add controlled growth experiments

darkzOGx07c145a4df4a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d2c6b2..7865c30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## Unreleased
+- Added a Controlled Growth Experiments Studio that turns approved-learning title and thumbnail variants into durable post-publication test plans
+- Added separate plan approval, live-start confirmation, bounded arm rotation, control restoration, and winner-adoption gates; no experiment can silently adopt a live change
+- Added real YouTube evidence samples for each arm using interval deltas for impressions, estimated clicks, CTR, views, watch time, retention, engagement, subscribers, and revenue
+- Added minimum-exposure, 95% evidence, retention-regression, and traffic-mix guardrails with an explicit inconclusive result when the evidence is weak or confounded
+- Added four-hour experiment refresh scheduling, restart-safe SQLite state, dashboard controls, read/mutation APIs, and approved-winner handoff into future channel planning
- Added a structured channel-outcome contract with primary KPI, numeric target, measurement window, monthly production budget, and currency while retaining free-text outcome context
- Added independent YouTube subscriber and monetization collection so unavailable revenue never converts otherwise-real analytics into simulated data or false zeroes
- Extended real performance snapshots with net subscribers, watch hours, subscriber and revenue efficiency, known production cost, net revenue, and ROI evidence
diff --git a/README.md b/README.md
index f2c9a97..7cb26eb 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,11 @@ Research topics → write scripts → generate narration and visuals → assembl
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Node.js 18+](https://img.shields.io/badge/node-18%2B-43853d.svg)](package.json)
+## What's new on master
+
+- **Controlled Growth Experiments Studio:** turn an approved packaging recommendation into a durable control and variant test, rotate only the explicitly approved arms, measure real interval evidence, restore the control, and separately approve an evidence-backed winner.
+- **Outcome & ROI Studio:** align the operator with a measurable KPI, target window, and budget while keeping missing revenue and cost evidence explicit.
+
## What's new in v2.9.0
**The agent now listens to your audience.** Until this release the feedback loop was numbers only — click-through, retention, watch time. It said how people watched, never what they wanted. v2.9.0 closes that gap and rounds out the repairable, provider-flexible, multi-format production workflow:
@@ -118,6 +123,14 @@ Open **Analytics → What the agent learned** to review the evidence and confide
When an approved learning calls for better packaging, Lumen prepares a control plus title and thumbnail variants for new videos. Review Studio shows those options before approval; the selected combination is the only one handed to the publishing queue. Lumen does not silently swap live YouTube metadata.
+### Prove a growth recommendation
+
+Open **Analytics → Controlled Growth Experiments** after a video with approved-learning packaging variants is published. Create a draft plan with a 24–168 hour window per arm and a minimum-impressions threshold, review the exact title and thumbnail combinations, then separately approve and start the live test.
+
+Lumen records a cumulative analytics sample before and after each arm and evaluates only the interval delta. Every arm must reach the configured impression and click floor. The leading CTR must clear a 95% evidence threshold without a material retention regression or traffic-source shift; otherwise the result is explicitly **inconclusive**. Simulated analytics never advance an experiment.
+
+Arm rotations are limited to the plan you approved. After the final arm, Lumen restores the control title and thumbnail before presenting the result. Applying the winner is a separate confirmation; only then does the validated packaging pattern become an approved learning for future Autonomous Operator runs. Experiment state and evidence are stored in SQLite so restarts do not erase progress.
+
### Align the channel with outcomes and ROI
The Autonomous Operator strategy can define a measurable primary outcome—views, watch hours, net subscribers, engagement rate, or estimated revenue—plus a numeric target, evidence window, monthly production budget, and currency. The existing free-text outcome context remains available for goals that need human nuance.
@@ -407,6 +420,17 @@ curl http://localhost:3456/api/outcomes
curl -X POST http://localhost:3456/api/learning/recommendations/:recommendationId/approve \
-H "x-api-key: $API_KEY"
+# inspect controlled experiments and eligible published videos
+curl http://localhost:3456/api/experiments
+
+# create and approve a packaging test plan (start/adopt are separate confirmed actions)
+curl -X POST http://localhost:3456/api/experiments \
+ -H "Content-Type: application/json" -H "x-api-key: $API_KEY" \
+ -d '{"productionId":"production-id","armDurationHours":48,"minImpressions":1000}'
+curl -X POST http://localhost:3456/api/experiments/:experimentId/approve \
+ -H "Content-Type: application/json" -H "x-api-key: $API_KEY" \
+ -d '{"confirmed":true}'
+
# inspect, edit, and approve content before scheduling
curl http://localhost:3456/api/content/:contentId
curl -X POST http://localhost:3456/api/content/:contentId/approve \
diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.js
index 6fe9cdb..1ef0d54 100644
--- a/agents/publishing-scheduling-agent.js
+++ b/agents/publishing-scheduling-agent.js
@@ -336,6 +336,57 @@ class PublishingSchedulingAgent {
}
}
+ async applyVideoPackaging(videoId, packaging = {}, previousPackaging = null) {
+ const title = String(packaging.title || '').trim();
+ if (!videoId || !title || title.length > 100 || !packaging.thumbnailPath) {
+ const error = new Error('A valid video ID, title, and thumbnail are required for a packaging change');
+ error.status = 400;
+ error.code = 'PACKAGING_INVALID';
+ throw error;
+ }
+ const thumbnail = await fs.readFile(packaging.thumbnailPath);
+ const current = await this.youtube.videos.list({ part: 'snippet', id: videoId });
+ const snippet = current.data.items?.[0]?.snippet;
+ if (!snippet) {
+ const error = new Error(`YouTube video not found: ${videoId}`);
+ error.status = 404;
+ error.code = 'PACKAGING_VIDEO_NOT_FOUND';
+ throw error;
+ }
+
+ const updateTitle = async nextTitle => this.youtube.videos.update({
+ part: 'snippet',
+ requestBody: {
+ id: videoId,
+ snippet: {
+ title: nextTitle,
+ description: snippet.description || '',
+ tags: snippet.tags || [],
+ categoryId: snippet.categoryId || '22',
+ defaultLanguage: snippet.defaultLanguage,
+ defaultAudioLanguage: snippet.defaultAudioLanguage
+ }
+ }
+ });
+
+ await updateTitle(title);
+ try {
+ await this.youtube.thumbnails.set({
+ videoId,
+ media: { body: thumbnail }
+ });
+ } catch (error) {
+ try {
+ await updateTitle(String(previousPackaging?.title || snippet.title || '').trim());
+ } catch (rollbackError) {
+ error.message = `${error.message}; title rollback also failed: ${rollbackError.message}`;
+ }
+ throw error;
+ }
+ this.logger.info(`Applied approved growth-experiment packaging to video: ${videoId}`);
+ return { videoId, title, thumbnailPath: packaging.thumbnailPath };
+ }
+
async uploadCaptions(videoId, captionsPath) {
try {
const captionsContent = await fs.readFile(captionsPath, 'utf8');
diff --git a/dashboard/app.js b/dashboard/app.js
index 3e46776..8a1b757 100644
--- a/dashboard/app.js
+++ b/dashboard/app.js
@@ -139,6 +139,7 @@ function renderDashboard() {
renderCalendar(state.schedule);
renderIdeas(state.ideas);
renderAnalytics(state.analytics, state.learning);
+ renderGrowthExperiments(state.experiments || {});
renderEngagement(ui.state.engagement || {});
renderActivation(state.activation);
renderReadiness(state.readiness);
@@ -407,6 +408,49 @@ function renderLearning(learning = {}) {
</article>`).join('') : empty('No recommendation yet. Lumen needs at least two real, sufficiently exposed measurements.');
}
+function renderGrowthExperiments(summary = {}) {
+ const experiments = Array.isArray(summary.experiments) ? summary.experiments : [];
+ const candidates = Array.isArray(summary.candidates) ? summary.candidates : [];
+ const candidate = $('#experiment-candidate');
+ const create = $('#experiment-create-button');
+ candidate.innerHTML = candidates.length
+ ? candidates.map(item => `<option value="${escapeHTML(item.productionId)}">${escapeHTML(item.title || item.productionId)}</option>`).join('')
+ : '<option value="">No eligible published variants</option>';
+ candidate.disabled = !candidates.length;
+ create.disabled = !candidates.length;
+ $('#experiment-status').textContent = `${Number(summary.activeCount || 0)} running · ${Number(summary.awaitingDecisionCount || 0)} decision${Number(summary.awaitingDecisionCount || 0) === 1 ? '' : 's'}`;
+ $('#experiment-policy').textContent = summary.evidencePolicy || 'Only real YouTube evidence advances controlled tests.';
+
+ $('#growth-experiments').innerHTML = experiments.length ? experiments.map(experiment => {
+ const winner = experiment.arms?.find(arm => arm.id === experiment.winningArmId);
+ const actions = [];
+ if (experiment.status === 'draft') actions.push(`<button class="text-button approve" data-experiment-action="approve" data-experiment-id="${escapeHTML(experiment.id)}">Approve plan</button>`);
+ if (experiment.status === 'approved') actions.push(`<button class="button primary small" data-experiment-action="start" data-experiment-id="${escapeHTML(experiment.id)}">Start live test</button>`);
+ if (experiment.status === 'running') {
+ actions.push(`<button class="button secondary small" data-experiment-action="refresh" data-experiment-id="${escapeHTML(experiment.id)}">Refresh evidence</button>`);
+ actions.push(`<button class="text-button" data-experiment-action="cancel" data-experiment-id="${escapeHTML(experiment.id)}">Cancel &amp; restore control</button>`);
+ }
+ if (experiment.status === 'action_required') actions.push(`<button class="text-button" data-experiment-action="cancel" data-experiment-id="${escapeHTML(experiment.id)}">Retry control restore</button>`);
+ if (experiment.status === 'awaiting_winner') actions.push(`<button class="button primary small" data-experiment-action="adopt" data-experiment-id="${escapeHTML(experiment.id)}">Adopt ${escapeHTML(winner?.label || 'winner')}</button>`);
+ const arms = (experiment.arms || []).map(arm => {
+ const result = arm.result || {};
+ const active = arm.id === experiment.currentArmId && experiment.status === 'running';
+ return `<div class="experiment-arm ${active ? 'active' : ''} ${arm.id === experiment.winningArmId ? 'winner' : ''}">
+ <div><strong>${escapeHTML(arm.label)}</strong>${arm.isControl ? '<small>Control</small>' : ''}</div>
+ <span>${escapeHTML(arm.title)}</span>
+ <div class="experiment-arm-metrics"><b>${Number(result.ctr || 0).toFixed(2)}% CTR</b><small>${Number(result.impressions || 0).toLocaleString()} impressions</small></div>
+ </div>`;
+ }).join('');
+ return `<article class="growth-experiment-card">
+ <div class="learning-card-heading"><strong>${escapeHTML(experiment.title)}</strong>${statusChip(experiment.status)}</div>
+ <p>${escapeHTML(experiment.hypothesis)}</p>
+ <div class="experiment-arm-list">${arms}</div>
+ ${experiment.result?.reason ? `<p class="experiment-result"><strong>Result:</strong> ${escapeHTML(experiment.result.reason)}${experiment.result.liftPercent !== undefined ? ` · ${escapeHTML(experiment.result.liftPercent)}% lift` : ''}</p>` : ''}
+ <div class="learning-meta"><span>${Number(experiment.armDurationHours || 0)}h per arm · ${Number(experiment.minImpressions || 0).toLocaleString()} minimum impressions</span><span class="learning-actions">${actions.join('')}</span></div>
+ </article>`;
+ }).join('') : empty('Publish content with approved-learning title and thumbnail variants to create the first controlled test.');
+}
+
function renderRetention(retention = {}) {
const snapshots = Array.isArray(retention.snapshots) ? retention.snapshots : [];
const select = $('#retention-snapshot-select');
@@ -1166,6 +1210,27 @@ document.addEventListener('click', async event => {
await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});
}
+ const experiment = event.target.closest('[data-experiment-action]');
+ if (experiment) {
+ const action = experiment.dataset.experimentAction;
+ const id = experiment.dataset.experimentId;
+ const prompts = {
+ approve: 'Approve this complete experiment plan? This does not change YouTube yet.',
+ start: 'Start this live test? Lumen will rotate only the approved arms and restore the control before asking you to adopt a winner.',
+ adopt: 'Adopt the evidence-backed winner on YouTube and approve its learning for future plans?',
+ cancel: 'Cancel this experiment and restore the control title and thumbnail?'
+ };
+ if (prompts[action] && !confirm(prompts[action])) return;
+ const messages = {
+ approve: 'Experiment plan approved.',
+ start: 'Controlled experiment started.',
+ refresh: 'Experiment evidence refreshed.',
+ adopt: 'Winner adopted and approved for future planning.',
+ cancel: 'Experiment cancelled and control restored.'
+ };
+ await mutate(`/api/experiments/${encodeURIComponent(id)}/${action}`, 'POST', prompts[action] ? { confirmed: true } : {}, messages[action]).catch(() => {});
+ }
+
const refreshRetention = event.target.closest('#refresh-retention-button');
if (refreshRetention?.dataset.videoId) {
refreshRetention.disabled = true;
@@ -1471,6 +1536,16 @@ $('#add-idea-button').addEventListener('click', () => $('#idea-dialog').showModa
$('#refresh-button').addEventListener('click', () => refreshDashboard());
$('#pipeline-filter').addEventListener('change', () => renderPipeline(ui.state?.pipeline || []));
+$('#experiment-create-form').addEventListener('submit', async event => {
+ event.preventDefault();
+ const values = Object.fromEntries(new FormData(event.currentTarget));
+ await mutate('/api/experiments', 'POST', {
+ productionId: values.productionId,
+ armDurationHours: Number(values.armDurationHours),
+ minImpressions: Number(values.minImpressions)
+ }, 'Draft growth experiment created for review.').catch(() => {});
+});
+
$('#run-readiness-button').addEventListener('click', async event => {
const button = event.currentTarget;
button.disabled = true;
diff --git a/dashboard/index.html b/dashboard/index.html
index 391a908..b49f492 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -160,6 +160,20 @@
<div id="learning-recommendations" class="learning-list"></div>
</article>
</div>
+ <article class="panel growth-experiment-studio">
+ <div class="panel-heading experiment-heading">
+ <div><p class="eyebrow">CONTROLLED GROWTH EXPERIMENTS</p><h2>Prove the next move</h2><p>Run approved title and thumbnail arms against real YouTube evidence, then separately approve the winner.</p></div>
+ <span id="experiment-status" class="status">0 running</span>
+ </div>
+ <form id="experiment-create-form" class="experiment-create-form">
+ <label><span>Published production</span><select name="productionId" id="experiment-candidate" required></select></label>
+ <label><span>Hours per arm</span><select name="armDurationHours"><option value="24">24 hours</option><option value="48" selected>48 hours</option><option value="72">72 hours</option></select></label>
+ <label><span>Minimum impressions</span><input name="minImpressions" type="number" min="100" max="1000000" step="100" value="1000" required></label>
+ <button id="experiment-create-button" class="button secondary small" type="submit">Create test plan</button>
+ </form>
+ <div id="growth-experiments" class="growth-experiment-list"></div>
+ <p id="experiment-policy" class="callout"></p>
+ </article>
<article class="panel retention-studio">
<div class="panel-heading retention-heading">
<div><p class="eyebrow">SCENE-AWARE RETENTION</p><h2>Where viewers stay—and leave</h2><p>Real YouTube retention points mapped onto the exact production timeline.</p></div>
diff --git a/dashboard/styles.css b/dashboard/styles.css
index 246ec44..df9c151 100644
--- a/dashboard/styles.css
+++ b/dashboard/styles.css
@@ -313,10 +313,10 @@ main { padding: 0 3.2vw 72px; min-width: 0; }
border: 1px solid transparent; white-space: nowrap;
}
.status::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; box-shadow: 0 0 6px currentColor; flex: 0 0 5px; }
-.status.needs_review, .status.queued, .status.warning, .status.skipped, .status.unverified { color: var(--amber); background: var(--amber-soft); border-color: rgba(255, 194, 71, .18); }
-.status.needs_attention, .status.failed, .status.interrupted, .status.reconciliation_required, .status.rejected, .status.drop_off { color: var(--red-hot); background: var(--red-soft); border-color: rgba(255, 77, 94, .2); }
-.status.approved, .status.scheduled, .status.published, .status.completed, .status.passed, .status.success, .status.strong_hold, .status.rewatch, .status.narration_current { color: var(--green); background: var(--green-soft); border-color: rgba(61, 220, 151, .18); }
-.status.steady, .status.insufficient, .status.narration_intentional_silence { color: var(--blue); background: var(--blue-soft); }
+.status.needs_review, .status.queued, .status.warning, .status.skipped, .status.unverified, .status.awaiting_winner, .status.inconclusive { color: var(--amber); background: var(--amber-soft); border-color: rgba(255, 194, 71, .18); }
+.status.needs_attention, .status.failed, .status.interrupted, .status.reconciliation_required, .status.rejected, .status.drop_off, .status.action_required { color: var(--red-hot); background: var(--red-soft); border-color: rgba(255, 77, 94, .2); }
+.status.approved, .status.scheduled, .status.published, .status.completed, .status.passed, .status.success, .status.strong_hold, .status.rewatch, .status.narration_current, .status.adopted { color: var(--green); background: var(--green-soft); border-color: rgba(61, 220, 151, .18); }
+.status.steady, .status.insufficient, .status.narration_intentional_silence, .status.running { color: var(--blue); background: var(--blue-soft); }
.status.narration_stale, .status.narration_unavailable, .status.narration_failed, .status.narration_generating, .status.needs_rebuild, .status.visual_stale, .status.missing_asset, .status.generating { color: var(--amber); background: var(--amber-soft); border-color: rgba(255, 194, 71, .18); }
/* ============ Progress ============ */
@@ -466,6 +466,24 @@ label:has(input:disabled) > span { color: var(--muted); }
.learning-meta { color: var(--muted); font-size: 11px; }
.learning-actions { display: flex; gap: 10px; }
+.growth-experiment-studio { display: grid; gap: 16px; margin-bottom: 16px; overflow: hidden; }
+.experiment-heading { align-items: flex-start; margin-bottom: 0; }
+.experiment-heading p:not(.eyebrow) { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 7px 0 0; }
+.experiment-create-form { display: grid; grid-template-columns: minmax(240px, 1fr) 150px 180px auto; gap: 10px; align-items: end; padding: 13px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-inset); }
+.growth-experiment-list { display: grid; gap: 12px; }
+.growth-experiment-card { display: grid; gap: 12px; padding: 15px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-2); }
+.growth-experiment-card > p { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 0; }
+.experiment-arm-list { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 9px; }
+.experiment-arm { display: grid; gap: 7px; min-width: 0; padding: 11px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-inset); }
+.experiment-arm.active { border-color: rgba(110, 168, 255, .45); box-shadow: inset 0 0 0 1px rgba(110, 168, 255, .12); }
+.experiment-arm.winner { border-color: rgba(61, 220, 151, .4); background: rgba(61, 220, 151, .05); }
+.experiment-arm > div:first-child, .experiment-arm-metrics { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
+.experiment-arm > div:first-child small, .experiment-arm-metrics small { color: var(--muted); font-size: 9px; font-family: var(--font-mono); text-transform: uppercase; letter-spacing: .07em; }
+.experiment-arm > span { min-height: 34px; color: var(--text-2); font-size: 11px; line-height: 1.45; overflow-wrap: anywhere; }
+.experiment-arm-metrics { padding-top: 8px; border-top: 1px solid var(--line); }
+.experiment-arm-metrics b { color: var(--text); font-size: 12px; font-family: var(--font-mono); }
+.experiment-result { padding: 10px 12px; border-left: 2px solid var(--blue); background: var(--blue-soft); }
+
/* ============ Retention studio ============ */
.retention-studio { display: grid; gap: 16px; margin-bottom: 16px; overflow: hidden; }
.retention-heading { align-items: flex-start; margin-bottom: 0; }
@@ -684,7 +702,8 @@ label:has(input:disabled) > span { color: var(--muted); }
main { width: 100%; max-width: 100vw; padding: 0 18px 60px; }
.loading-bar { left: 0; }
.stats-grid { grid-template-columns: 1fr 1fr; }
- .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list, .outcome-breakdowns { grid-template-columns: 1fr; }
+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list, .outcome-breakdowns, .experiment-create-form { grid-template-columns: 1fr; }
+ .experiment-arm-list { grid-template-columns: 1fr; }
.overview-grid, .card-list, .job-card { min-width: 0; max-width: 100%; }
.pipeline-item { grid-template-columns: 1fr auto; }
.pipeline-col { display: none; }
@@ -707,6 +726,9 @@ label:has(input:disabled) > span { color: var(--muted); }
.narration-recovery { align-items: flex-start; flex-direction: column; }
.retention-controls { width: 100%; min-width: 0; align-items: stretch; flex-direction: column; }
.retention-controls select { min-width: 0; }
+ .growth-experiment-card .learning-meta { align-items: stretch; flex-direction: column; }
+ .growth-experiment-card .learning-actions { flex-wrap: wrap; }
+ .growth-experiment-card .learning-actions .button, .growth-experiment-card .learning-actions .text-button { flex: 1 1 140px; justify-content: center; text-align: center; }
.scene-actions { gap: 4px 11px; }
.toast { left: 16px; right: 16px; max-width: none; }
}
diff --git a/database/db.js b/database/db.js
index 80a1e81..9bc01ec 100644
--- a/database/db.js
+++ b/database/db.js
@@ -177,6 +177,60 @@ class Database {
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
reviewed_at TEXT
)`,
+ `CREATE TABLE IF NOT EXISTS growth_experiments (
+ id TEXT PRIMARY KEY,
+ production_id TEXT NOT NULL,
+ video_id TEXT NOT NULL,
+ recommendation_id TEXT,
+ title TEXT NOT NULL,
+ hypothesis TEXT NOT NULL,
+ primary_metric TEXT NOT NULL DEFAULT 'ctr',
+ status TEXT NOT NULL DEFAULT 'draft',
+ arm_duration_hours INTEGER NOT NULL DEFAULT 48,
+ min_impressions INTEGER NOT NULL DEFAULT 1000,
+ guardrails TEXT NOT NULL DEFAULT '{}',
+ current_arm_id TEXT,
+ winning_arm_id TEXT,
+ result TEXT NOT NULL DEFAULT '{}',
+ approved_at TEXT,
+ started_at TEXT,
+ completed_at TEXT,
+ adopted_at TEXT,
+ cancelled_at TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (production_id) REFERENCES productions(id)
+ )`,
+ `CREATE TABLE IF NOT EXISTS experiment_arms (
+ id TEXT PRIMARY KEY,
+ experiment_id TEXT NOT NULL,
+ arm_index INTEGER NOT NULL,
+ label TEXT NOT NULL,
+ title TEXT NOT NULL,
+ thumbnail_path TEXT NOT NULL,
+ is_control INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'pending',
+ baseline_metrics TEXT NOT NULL DEFAULT '{}',
+ final_metrics TEXT NOT NULL DEFAULT '{}',
+ result TEXT NOT NULL DEFAULT '{}',
+ started_at TEXT,
+ ended_at TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(experiment_id, arm_index),
+ FOREIGN KEY (experiment_id) REFERENCES growth_experiments(id)
+ )`,
+ `CREATE TABLE IF NOT EXISTS experiment_samples (
+ id TEXT PRIMARY KEY,
+ experiment_id TEXT NOT NULL,
+ arm_id TEXT NOT NULL,
+ metrics TEXT NOT NULL,
+ traffic_sources TEXT NOT NULL DEFAULT '[]',
+ captured_at TEXT NOT NULL,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (experiment_id) REFERENCES growth_experiments(id),
+ FOREIGN KEY (arm_id) REFERENCES experiment_arms(id)
+ )`,
`CREATE TABLE IF NOT EXISTS retention_snapshots (
id TEXT PRIMARY KEY,
video_id TEXT NOT NULL,
@@ -1930,6 +1984,182 @@ class Database {
};
}
+ async createGrowthExperiment(experiment, arms) {
+ const id = experiment.id || this.generateId('experiment');
+ await this.executeQuery(
+ `INSERT INTO growth_experiments (
+ id, production_id, video_id, recommendation_id, title, hypothesis,
+ primary_metric, status, arm_duration_hours, min_impressions, guardrails
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [
+ id, experiment.productionId, experiment.videoId, experiment.recommendationId || null,
+ experiment.title, experiment.hypothesis, experiment.primaryMetric || 'ctr',
+ experiment.status || 'draft', experiment.armDurationHours || 48,
+ experiment.minImpressions || 1000, JSON.stringify(experiment.guardrails || {})
+ ]
+ );
+ for (const [index, arm] of arms.entries()) {
+ await this.executeQuery(
+ `INSERT INTO experiment_arms (
+ id, experiment_id, arm_index, label, title, thumbnail_path, is_control
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ [
+ arm.id || this.generateId('arm'), id, index, arm.label,
+ arm.title, arm.thumbnailPath, arm.isControl ? 1 : 0
+ ]
+ );
+ }
+ return this.getGrowthExperiment(id);
+ }
+
+ async getGrowthExperiment(id) {
+ const row = await this.getRow('SELECT * FROM growth_experiments WHERE id = ?', [id]);
+ if (!row) return null;
+ const arms = await this.getAllRows(
+ 'SELECT * FROM experiment_arms WHERE experiment_id = ? ORDER BY arm_index ASC',
+ [id]
+ );
+ return this.parseGrowthExperiment(row, arms);
+ }
+
+ async listGrowthExperiments(options = {}) {
+ const conditions = [];
+ const params = [];
+ if (options.status) {
+ const statuses = Array.isArray(options.status) ? options.status : [options.status];
+ conditions.push(`status IN (${statuses.map(() => '?').join(', ')})`);
+ params.push(...statuses);
+ }
+ if (options.productionId) {
+ conditions.push('production_id = ?');
+ params.push(options.productionId);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const limit = Math.max(1, Math.min(100, Number(options.limit || 25)));
+ const rows = await this.getAllRows(
+ `SELECT * FROM growth_experiments ${where} ORDER BY updated_at DESC LIMIT ?`,
+ [...params, limit]
+ );
+ return Promise.all(rows.map(async row => {
+ const arms = await this.getAllRows(
+ 'SELECT * FROM experiment_arms WHERE experiment_id = ? ORDER BY arm_index ASC',
+ [row.id]
+ );
+ return this.parseGrowthExperiment(row, arms);
+ }));
+ }
+
+ async updateGrowthExperiment(id, changes = {}) {
+ const allowed = {
+ status: 'status', currentArmId: 'current_arm_id', winningArmId: 'winning_arm_id',
+ result: 'result', approvedAt: 'approved_at', startedAt: 'started_at',
+ completedAt: 'completed_at', adoptedAt: 'adopted_at', cancelledAt: 'cancelled_at'
+ };
+ const assignments = [];
+ const params = [];
+ for (const [key, column] of Object.entries(allowed)) {
+ if (changes[key] === undefined) continue;
+ assignments.push(`${column} = ?`);
+ params.push(key === 'result' ? JSON.stringify(changes[key] || {}) : changes[key]);
+ }
+ if (!assignments.length) return this.getGrowthExperiment(id);
+ assignments.push('updated_at = CURRENT_TIMESTAMP');
+ await this.executeQuery(
+ `UPDATE growth_experiments SET ${assignments.join(', ')} WHERE id = ?`,
+ [...params, id]
+ );
+ return this.getGrowthExperiment(id);
+ }
+
+ async updateExperimentArm(id, changes = {}) {
+ const allowed = {
+ status: 'status', baselineMetrics: 'baseline_metrics', finalMetrics: 'final_metrics',
+ result: 'result', startedAt: 'started_at', endedAt: 'ended_at'
+ };
+ const assignments = [];
+ const params = [];
+ for (const [key, column] of Object.entries(allowed)) {
+ if (changes[key] === undefined) continue;
+ assignments.push(`${column} = ?`);
+ params.push(['baselineMetrics', 'finalMetrics', 'result'].includes(key)
+ ? JSON.stringify(changes[key] || {})
+ : changes[key]);
+ }
+ if (!assignments.length) return null;
+ assignments.push('updated_at = CURRENT_TIMESTAMP');
+ await this.executeQuery(`UPDATE experiment_arms SET ${assignments.join(', ')} WHERE id = ?`, [...params, id]);
+ const row = await this.getRow('SELECT * FROM experiment_arms WHERE id = ?', [id]);
+ return this.parseExperimentArm(row);
+ }
+
+ async saveExperimentSample(sample) {
+ const id = this.generateId('sample');
+ await this.executeQuery(
+ `INSERT INTO experiment_samples (
+ id, experiment_id, arm_id, metrics, traffic_sources, captured_at
+ ) VALUES (?, ?, ?, ?, ?, ?)`,
+ [
+ id, sample.experimentId, sample.armId, JSON.stringify(sample.metrics || {}),
+ JSON.stringify(sample.trafficSources || []), sample.capturedAt || new Date().toISOString()
+ ]
+ );
+ return id;
+ }
+
+ async listExperimentSamples(experimentId, limit = 250) {
+ const rows = await this.getAllRows(
+ `SELECT * FROM experiment_samples WHERE experiment_id = ?
+ ORDER BY captured_at ASC LIMIT ?`,
+ [experimentId, Math.max(1, Math.min(1000, Number(limit || 250)))]
+ );
+ return rows.map(row => ({
+ ...row,
+ experimentId: row.experiment_id,
+ armId: row.arm_id,
+ capturedAt: row.captured_at,
+ metrics: JSON.parse(row.metrics || '{}'),
+ trafficSources: JSON.parse(row.traffic_sources || '[]')
+ }));
+ }
+
+ parseExperimentArm(row) {
+ if (!row) return null;
+ return {
+ ...row,
+ experimentId: row.experiment_id,
+ index: Number(row.arm_index),
+ thumbnailPath: row.thumbnail_path,
+ isControl: Boolean(row.is_control),
+ baselineMetrics: JSON.parse(row.baseline_metrics || '{}'),
+ finalMetrics: JSON.parse(row.final_metrics || '{}'),
+ result: JSON.parse(row.result || '{}'),
+ startedAt: row.started_at,
+ endedAt: row.ended_at
+ };
+ }
+
+ parseGrowthExperiment(row, arms = []) {
+ return {
+ ...row,
+ productionId: row.production_id,
+ videoId: row.video_id,
+ recommendationId: row.recommendation_id,
+ primaryMetric: row.primary_metric,
+ armDurationHours: Number(row.arm_duration_hours),
+ minImpressions: Number(row.min_impressions),
+ currentArmId: row.current_arm_id,
+ winningArmId: row.winning_arm_id,
+ approvedAt: row.approved_at,
+ startedAt: row.started_at,
+ completedAt: row.completed_at,
+ adoptedAt: row.adopted_at,
+ cancelledAt: row.cancelled_at,
+ guardrails: JSON.parse(row.guardrails || '{}'),
+ result: JSON.parse(row.result || '{}'),
+ arms: arms.map(arm => this.parseExperimentArm(arm))
+ };
+ }
+
async upsertAudienceComment(comment) {
const existing = await this.getRow(
'SELECT id FROM audience_comments WHERE comment_id = ?',
diff --git a/index.js b/index.js
index 927ee48..62c0d26 100644
--- a/index.js
+++ b/index.js
@@ -24,6 +24,7 @@ const { ProvenanceService } = require('./utils/provenance-service');
const { SceneRepairService } = require('./utils/scene-repair-service');
const { ShortsRepurposingService } = require('./utils/shorts-repurposing-service');
const { AudienceEngagementService } = require('./utils/audience-engagement-service');
+const { GrowthExperimentService } = require('./utils/growth-experiment-service');
const { AITextService } = require('./utils/ai-text-service');
const { version } = require('./package.json');
const chalk = require('chalk');
@@ -47,6 +48,7 @@ class YouTubeAutomationAgent {
this.scenes = null;
this.shorts = null;
this.engagement = null;
+ this.experiments = null;
this.setupRequired = false;
}
@@ -110,6 +112,12 @@ class YouTubeAutomationAgent {
new AITextService(this.credentials?.credentials || {}),
{ logger: this.logger }
);
+ this.experiments = new GrowthExperimentService(
+ this.db,
+ this.agents.analytics,
+ this.agents.publishing,
+ { logger: this.logger }
+ );
// Show which pipeline stages will run for real vs. be simulated
const capabilities = await this.logCapabilitySummary();
@@ -124,7 +132,8 @@ class YouTubeAutomationAgent {
this.logger.info('Setting up automation scheduler...');
this.scheduler = new DailyAutomation(this.agents, this.db, {
generateContent: input => this.queueScheduledContent(input),
- engagement: this.engagement
+ engagement: this.engagement,
+ experiments: this.experiments
});
await this.scheduler.initialize();
@@ -462,7 +471,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, readiness, engagement] = await Promise.all([
+ const [stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation, channelStrategy, operatorRuns, readiness, engagement, experiments] = await Promise.all([
this.db.getStats(),
this.db.listGenerationJobs(20),
this.db.getPipelineOverview(50),
@@ -493,12 +502,15 @@ class YouTubeAutomationAgent {
pendingAudienceIdeas: 0, postingEnabled: false, postingDisabledReason: 'setup_required',
insights: [], recentThemes: [],
evidencePolicy: 'Comments are fetched read-only from YouTube. Replies post only after operator approval, and fallback analysis never proposes drafts or ideas.'
- })
+ }),
+ this.experiments
+ ? this.experiments.getSummary()
+ : Promise.resolve({ experiments: [], candidates: [], activeCount: 0, awaitingDecisionCount: 0, evidencePolicy: 'Finish setup to create a controlled growth experiment.' })
]);
if (this.telemetry) void this.telemetry.sync(activation);
res.json({
stats, jobs, pipeline, schedule, events, notifications, profile, settings, ideas, analytics, learning, activation,
- channelStrategy, operatorRuns, readiness, engagement,
+ channelStrategy, operatorRuns, readiness, engagement, experiments,
system: {
initialized: this.isInitialized,
setupRequired: this.setupRequired,
@@ -946,6 +958,52 @@ class YouTubeAutomationAgent {
return res.json({ success: true, result: recommendation });
});
+ this.app.get('/api/experiments', async (_req, res) => {
+ try {
+ const summary = this.experiments
+ ? await this.experiments.getSummary()
+ : { experiments: [], candidates: [], activeCount: 0, awaitingDecisionCount: 0 };
+ return res.json({ success: true, result: summary });
+ } catch (error) {
+ return res.status(500).json({ success: false, error: error.message });
+ }
+ });
+
+ this.app.post('/api/experiments', protect, async (req, res) => {
+ try {
+ if (!this.experiments) return res.status(503).json({ error: 'Finish setup before creating experiments' });
+ const experiment = await this.experiments.create(req.body || {});
+ return res.status(201).json({ success: true, result: experiment });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });
+ }
+ });
+
+ this.app.post('/api/experiments/:experimentId/:action', protect, async (req, res) => {
+ try {
+ if (!this.experiments) return res.status(503).json({ error: 'Finish setup before controlling experiments' });
+ const actions = {
+ approve: () => this.experiments.approve(req.params.experimentId, req.body),
+ start: () => this.experiments.start(req.params.experimentId, req.body),
+ refresh: () => this.experiments.refresh(req.params.experimentId),
+ adopt: () => this.experiments.adoptWinner(req.params.experimentId, req.body),
+ cancel: () => this.experiments.cancel(req.params.experimentId, req.body)
+ };
+ if (!actions[req.params.action]) return res.status(400).json({ error: 'Unsupported experiment action' });
+ const experiment = await actions[req.params.action]();
+ await this.operator.notify({
+ type: 'growth_experiment_updated',
+ level: ['adopt', 'approve'].includes(req.params.action) ? 'success' : 'info',
+ title: `Growth experiment ${req.params.action}`,
+ message: experiment.title,
+ data: { experimentId: experiment.id, status: experiment.status }
+ });
+ return res.json({ success: true, result: experiment });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });
+ }
+ });
+
this.app.get('/api/retention/:videoId', async (req, res) => {
const videoId = String(req.params.videoId || '').trim();
if (!/^[A-Za-z0-9_-]{1,100}$/.test(videoId)) {
diff --git a/schedules/daily-automation.js b/schedules/daily-automation.js
index 2549a41..f699a56 100644
--- a/schedules/daily-automation.js
+++ b/schedules/daily-automation.js
@@ -12,6 +12,7 @@ class DailyAutomation {
this.lastHealthCheck = null;
this.generateContent = options.generateContent || null;
this.engagement = options.engagement || null;
+ this.experiments = options.experiments || null;
}
async initialize() {
@@ -90,6 +91,15 @@ class DailyAutomation {
}, { scheduled: false })
);
+ // Collect controlled experiment evidence and advance only pre-approved arms.
+ this.scheduledTasks.set('growth-experiment-refresh',
+ cron.schedule('30 */4 * * *', async () => {
+ if (this.isEnabled) {
+ await this.refreshGrowthExperiments();
+ }
+ }, { scheduled: false })
+ );
+
// Start all scheduled tasks
this.scheduledTasks.forEach((task, name) => {
task.start();
@@ -308,6 +318,19 @@ class DailyAutomation {
}
}
+ async refreshGrowthExperiments() {
+ if (!this.experiments) return;
+ try {
+ const result = await this.experiments.refreshDue();
+ if (result.refreshed || result.failed) {
+ await this.logAutomationEvent('growth_experiment_refresh', result.failed ? 'warning' : 'success', result);
+ }
+ } catch (error) {
+ this.logger.error('Growth experiment refresh failed:', error);
+ await this.logAutomationEvent('growth_experiment_refresh', 'error', { error: error.message });
+ }
+ }
+
async weeklyStrategyReview() {
try {
this.logger.info('Starting weekly strategy review...');
diff --git a/test.js b/test.js
index 636ebb2..e1ca785 100644
--- a/test.js
+++ b/test.js
@@ -27,6 +27,7 @@ class SystemTest {
{ name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },
{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },
{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },
+ { name: 'Controlled Growth Experiments Studio', test: () => this.testGrowthExperimentsStudio() },
{ name: 'Outcome and ROI Studio', test: () => this.testOutcomeROIStudio() },
{ name: 'Scene-Aware Retention Studio', test: () => this.testSceneAwareRetentionStudio() },
{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },
@@ -60,7 +61,8 @@ class SystemTest {
{ name: 'Reply Drafting', test: () => this.testReplyDrafting() },
{ name: 'Reply Approval and Posting', test: () => this.testReplyApprovalAndPosting() },
{ name: 'Engagement AI Provider Wiring', test: () => this.testEngagementAIProviderWiring() },
- { name: 'Engagement Sync Schedule', test: () => this.testEngagementSyncSchedule() }
+ { name: 'Engagement Sync Schedule', test: () => this.testEngagementSyncSchedule() },
+ { name: 'Growth Experiment Refresh Schedule', test: () => this.testGrowthExperimentRefreshSchedule() }
];
let passed = 0;
@@ -597,6 +599,141 @@ class SystemTest {
this.logger.info('Closed-loop channel learning test completed successfully');
}
+ async testGrowthExperimentsStudio() {
+ const fs = require('fs').promises;
+ const os = require('os');
+ const { GrowthExperimentService } = require('./utils/growth-experiment-service');
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-experiments-'));
+ const db = new Database();
+ db.dbPath = path.join(directory, 'experiments.db');
+ await db.initialize();
+ const productionId = 'experiment-production';
+ const thumbnails = await Promise.all(['control', 'variant-a', 'variant-b'].map(async name => {
+ const file = path.join(directory, `${name}.jpg`);
+ await fs.writeFile(file, Buffer.from(`thumbnail-${name}`));
+ return file;
+ }));
+
+ try {
+ await db.saveProductionData({
+ id: productionId, status: 'published',
+ assets: { thumbnail: { path: thumbnails[0] }, finalVideo: { path: 'fixture.mp4' } },
+ timeline: {}, scheduledPublishTime: new Date().toISOString(), priority: 50, estimatedDuration: '8:00'
+ });
+ await db.saveProductionSnapshot({
+ id: productionId,
+ strategy: { topic: 'Controlled growth' },
+ script: { title: 'Control title' },
+ thumbnail: { path: thumbnails[0] },
+ seo: { title: 'Control title', description: 'Fixture', tags: [] }
+ });
+ const sourceLearning = await db.saveLearningRecommendation({
+ fingerprint: 'growth-experiment-source', category: 'packaging',
+ title: 'Test packaging', rationale: 'CTR trails the channel baseline.',
+ evidence: { measuredVideos: 4 }, proposedChange: { experiment: 'title_thumbnail_variant' }, confidence: 'medium'
+ });
+ await db.reviewLearningRecommendation(sourceLearning.id, 'approved');
+ await db.saveContentReview(productionId, {
+ status: 'approved',
+ editorData: {
+ packagingExperiment: {
+ sourceRecommendationId: sourceLearning.id,
+ hypothesis: 'A clearer promise improves qualified clicks.',
+ titleVariants: [
+ { label: 'Control', title: 'Control title' },
+ { label: 'Clear benefit', title: 'A Clearer Automation Benefit' },
+ { label: 'Curiosity', title: 'The Automation Detail You Missed' }
+ ],
+ thumbnailVariants: [
+ { label: 'Control', path: thumbnails[0] },
+ { label: 'Clear benefit', path: thumbnails[1] },
+ { label: 'Curiosity', path: thumbnails[2] }
+ ]
+ }
+ }
+ });
+ const schedule = await db.saveScheduleEntry({
+ productionId, title: 'Control title', publishTime: new Date(Date.now() - 8 * 86400000).toISOString(),
+ status: 'published', priority: 50,
+ metadata: { seo: { title: 'Control title', description: 'Fixture', tags: [] }, thumbnail: { path: thumbnails[0] } }
+ });
+ schedule.status = 'published';
+ schedule.youtubeId = 'youtube-experiment-1';
+ schedule.youtubeUrl = 'https://www.youtube.com/watch?v=youtube-experiment-1';
+ schedule.publishedAt = new Date(Date.now() - 8 * 86400000).toISOString();
+ await db.updateScheduleEntry(schedule);
+
+ const cumulative = [
+ { impressions: 10000, clicks: 500, views: 700 },
+ { impressions: 11000, clicks: 550, views: 770 },
+ { impressions: 12000, clicks: 650, views: 860 },
+ { impressions: 13000, clicks: 690, views: 920 }
+ ];
+ let reportIndex = 0;
+ const analytics = {
+ analyzeVideoPerformance: async () => {
+ const point = cumulative[Math.min(reportIndex++, cumulative.length - 1)];
+ return {
+ analytics: {
+ simulated: false,
+ views: { totalViews: point.views, totalImpressions: point.impressions, averageCTR: point.clicks / point.impressions * 100 },
+ watchTime: { totalWatchTime: point.views * 4, averageViewPercentage: 55 },
+ engagement: { engagementRate: 4.5 },
+ outcomes: { netSubscribers: Math.floor(point.views / 100), estimatedRevenue: point.views / 100 }
+ },
+ thumbnailMetrics: { impressions: point.impressions, clickThroughRate: point.clicks / point.impressions * 100 }
+ };
+ }
+ };
+ const applied = [];
+ const publishing = {
+ applyVideoPackaging: async (videoId, packaging) => applied.push({ videoId, ...packaging })
+ };
+ let clock = Date.now();
+ const service = new GrowthExperimentService(db, analytics, publishing, { now: () => new Date(clock) });
+ let experiment = await service.create({ productionId, armDurationHours: 24, minImpressions: 100 });
+ if (experiment.status !== 'draft' || experiment.arms.length !== 3 || !experiment.arms[0].isControl) {
+ throw new Error('Experiment plan did not persist a control and complete variant arms');
+ }
+
+ let confirmationBlocked = false;
+ try { await service.approve(experiment.id); } catch (error) { confirmationBlocked = error.code === 'EXPERIMENT_CONFIRMATION_REQUIRED'; }
+ if (!confirmationBlocked) throw new Error('Experiment approval did not require explicit confirmation');
+ experiment = await service.approve(experiment.id, { confirmed: true });
+ experiment = await service.start(experiment.id, { confirmed: true });
+ if (experiment.status !== 'running' || applied.length !== 1) throw new Error('Approved experiment did not start on its control arm');
+
+ for (let index = 0; index < 3; index++) {
+ clock += 24 * 3600000;
+ experiment = await service.refresh(experiment.id);
+ }
+ if (
+ experiment.status !== 'awaiting_winner' || !experiment.winningArmId ||
+ experiment.arms.find(arm => arm.id === experiment.winningArmId)?.label !== 'Clear benefit' ||
+ experiment.result.guardrails.passed !== true || applied.at(-1).title !== 'Control title'
+ ) {
+ throw new Error('Experiment did not select an evidence-backed winner and restore the control');
+ }
+
+ experiment = await service.adoptWinner(experiment.id, { confirmed: true });
+ const learned = (await db.listLearningRecommendations({ status: 'approved', limit: 20 }))
+ .find(item => item.evidence?.experimentId === experiment.id);
+ if (experiment.status !== 'adopted' || !learned || applied.at(-1).title !== 'A Clearer Automation Benefit') {
+ throw new Error('Winner adoption did not update packaging and approve the resulting learning');
+ }
+
+ const storedSamples = await db.listExperimentSamples(experiment.id);
+ if (storedSamples.length < 6 || storedSamples.some(sample => !Number.isFinite(sample.metrics.impressions))) {
+ throw new Error('Experiment evidence samples were not durably stored');
+ }
+ } finally {
+ await db.close();
+ await fs.rm(directory, { recursive: true, force: true });
+ }
+
+ this.logger.info('Controlled Growth Experiments Studio test completed successfully');
+ }
+
async testOutcomeROIStudio() {
const fs = require('fs').promises;
const os = require('os');
@@ -2934,6 +3071,28 @@ class SystemTest {
const noService = new DailyAutomation({}, fakeDb, { generateContent: async () => {} });
await noService.collectAudienceEngagement(); // must be a silent no-op, not a crash
}
+
+ async testGrowthExperimentRefreshSchedule() {
+ const events = [];
+ let refreshes = 0;
+ const scheduler = new DailyAutomation({}, {}, {
+ experiments: {
+ refreshDue: async () => {
+ refreshes++;
+ return { running: 2, refreshed: 1, failed: 0 };
+ }
+ }
+ });
+ scheduler.logAutomationEvent = async (type, status, data) => events.push({ type, status, data });
+ await scheduler.refreshGrowthExperiments();
+ if (refreshes !== 1 || !events.some(event =>
+ event.type === 'growth_experiment_refresh' && event.status === 'success' && event.data.refreshed === 1
+ )) {
+ throw new Error('The scheduler did not refresh and record due controlled experiments');
+ }
+ const noService = new DailyAutomation({}, {}, {});
+ await noService.refreshGrowthExperiments();
+ }
}
// Run tests if called directly
diff --git a/utils/growth-experiment-service.js b/utils/growth-experiment-service.js
new file mode 100644
index 0000000..69cdc92
--- /dev/null
+++ b/utils/growth-experiment-service.js
@@ -0,0 +1,473 @@
+const fs = require('fs').promises;
+const { Logger } = require('./logger');
+
+const ACTIVE_STATUSES = new Set(['draft', 'approved', 'running', 'awaiting_winner', 'action_required']);
+
+class GrowthExperimentService {
+ constructor(db, analytics, publishing, options = {}) {
+ this.db = db;
+ this.analytics = analytics;
+ this.publishing = publishing;
+ this.logger = options.logger || new Logger('GrowthExperiments');
+ this.now = options.now || (() => new Date());
+ this.activeRefreshes = new Set();
+ }
+
+ error(message, status = 400, code = 'EXPERIMENT_INVALID') {
+ const error = new Error(message);
+ error.status = status;
+ error.code = code;
+ return error;
+ }
+
+ async create(input = {}) {
+ const productionId = String(input.productionId || '').trim();
+ if (!productionId) throw this.error('Choose a published production to test');
+ const armDurationHours = Number(input.armDurationHours || 48);
+ const minImpressions = Number(input.minImpressions || 1000);
+ if (!Number.isInteger(armDurationHours) || armDurationHours < 24 || armDurationHours > 168) {
+ throw this.error('Each experiment arm must run for 24 to 168 hours');
+ }
+ if (!Number.isInteger(minImpressions) || minImpressions < 100 || minImpressions > 1000000) {
+ throw this.error('Minimum impressions must be an integer from 100 to 1,000,000');
+ }
+
+ const existing = await this.db.listGrowthExperiments({ productionId, limit: 20 });
+ if (existing.some(experiment => ACTIVE_STATUSES.has(experiment.status))) {
+ throw this.error('This production already has an unfinished growth experiment', 409, 'EXPERIMENT_EXISTS');
+ }
+ const bundle = await this.db.getProductionBundle(productionId);
+ const schedule = bundle?.schedule;
+ if (!bundle || schedule?.status !== 'published' || !schedule.youtube_id) {
+ throw this.error('Growth experiments require a published YouTube production', 409, 'EXPERIMENT_NOT_PUBLISHED');
+ }
+ const packaging = bundle.editorData?.packagingExperiment;
+ if (!packaging?.titleVariants?.length || !packaging?.thumbnailVariants?.length) {
+ throw this.error('This production has no approved-learning packaging variants to test', 409, 'EXPERIMENT_VARIANTS_MISSING');
+ }
+ const sourceRecommendation = packaging.sourceRecommendationId
+ ? await this.db.getLearningRecommendation(packaging.sourceRecommendationId)
+ : null;
+ if (!sourceRecommendation || sourceRecommendation.status !== 'approved') {
+ throw this.error('The source packaging recommendation is no longer approved', 409, 'EXPERIMENT_LEARNING_NOT_APPROVED');
+ }
+
+ const control = {
+ label: 'Control',
+ title: schedule.metadata?.seo?.title || schedule.title || bundle.seo?.title || bundle.script?.title,
+ thumbnailPath: schedule.metadata?.thumbnail?.path || bundle.assets?.thumbnail?.path || bundle.thumbnail?.path,
+ isControl: true
+ };
+ const variants = packaging.titleVariants
+ .map((variant, index) => ({
+ label: variant.label === 'Control' ? 'Original package' : (variant.label || `Variant ${index + 1}`),
+ title: variant.title,
+ thumbnailPath: packaging.thumbnailVariants[index]?.path,
+ isControl: false
+ }))
+ .filter(arm => arm.title && arm.thumbnailPath)
+ .filter(arm => arm.title !== control.title || arm.thumbnailPath !== control.thumbnailPath);
+ const arms = [control, ...variants].filter((arm, index, list) =>
+ arm.title && arm.thumbnailPath && list.findIndex(candidate =>
+ candidate.title === arm.title && candidate.thumbnailPath === arm.thumbnailPath
+ ) === index
+ ).slice(0, 3);
+ if (arms.length < 2) {
+ throw this.error('At least one complete title and thumbnail variant is required', 409, 'EXPERIMENT_VARIANTS_MISSING');
+ }
+ for (const arm of arms) {
+ if (arm.title.length > 100) throw this.error(`${arm.label} title exceeds YouTube's 100-character limit`);
+ await this.requireFile(arm.thumbnailPath, `${arm.label} thumbnail is missing from disk`);
+ }
+
+ return this.db.createGrowthExperiment({
+ productionId,
+ videoId: schedule.youtube_id,
+ recommendationId: packaging.sourceRecommendationId || null,
+ title: `Packaging test: ${control.title}`,
+ hypothesis: packaging.hypothesis || 'A new title and thumbnail package will improve qualified click-through rate.',
+ armDurationHours,
+ minImpressions,
+ guardrails: {
+ maximumRetentionDropPoints: 5,
+ maximumTrafficSourceShiftPoints: 20,
+ simulatedEvidenceAllowed: false,
+ automaticWinnerAdoption: false
+ }
+ }, arms);
+ }
+
+ async approve(id, input = {}) {
+ const experiment = await this.requireExperiment(id);
+ if (experiment.status !== 'draft') throw this.error('Only a draft experiment can be approved', 409);
+ if (input.confirmed !== true) throw this.error('Confirm the complete experiment plan before approval', 409, 'EXPERIMENT_CONFIRMATION_REQUIRED');
+ return this.db.updateGrowthExperiment(id, { status: 'approved', approvedAt: this.isoNow() });
+ }
+
+ async start(id, input = {}) {
+ const experiment = await this.requireExperiment(id);
+ if (experiment.status !== 'approved' || !experiment.approvedAt) {
+ throw this.error('Approve the experiment plan before starting it', 409, 'EXPERIMENT_APPROVAL_REQUIRED');
+ }
+ if (input.confirmed !== true) throw this.error('Confirm activation before changing live YouTube packaging', 409, 'EXPERIMENT_CONFIRMATION_REQUIRED');
+ const baseline = await this.captureMetrics(experiment.videoId);
+ const arm = experiment.arms[0];
+ const startedAt = this.isoNow();
+ await this.db.updateExperimentArm(arm.id, {
+ status: 'running', baselineMetrics: baseline.metrics, startedAt
+ });
+ await this.db.saveExperimentSample({
+ experimentId: experiment.id, armId: arm.id,
+ metrics: baseline.metrics, trafficSources: baseline.trafficSources, capturedAt: startedAt
+ });
+ try {
+ await this.applyArm(experiment, arm, arm);
+ } catch (error) {
+ await this.db.updateExperimentArm(arm.id, { status: 'failed' });
+ await this.db.updateGrowthExperiment(id, {
+ status: 'action_required', currentArmId: arm.id, startedAt,
+ result: { activationError: error.message }
+ });
+ throw error;
+ }
+ return this.db.updateGrowthExperiment(id, {
+ status: 'running', currentArmId: arm.id, startedAt
+ });
+ }
+
+ async refresh(id, options = {}) {
+ if (this.activeRefreshes.has(id)) {
+ throw this.error('This experiment is already refreshing', 409, 'EXPERIMENT_BUSY');
+ }
+ this.activeRefreshes.add(id);
+ try {
+ return await this.refreshUnlocked(id, options);
+ } finally {
+ this.activeRefreshes.delete(id);
+ }
+ }
+
+ async refreshUnlocked(id, options = {}) {
+ const experiment = await this.requireExperiment(id);
+ if (experiment.status !== 'running') throw this.error('Only a running experiment can collect evidence', 409);
+ const arm = experiment.arms.find(candidate => candidate.id === experiment.currentArmId);
+ if (!arm) throw this.error('The running experiment has no active arm', 409, 'EXPERIMENT_STATE_INVALID');
+ const capturedAt = this.isoNow();
+ const evidence = await this.captureMetrics(experiment.videoId);
+ await this.db.saveExperimentSample({
+ experimentId: experiment.id, armId: arm.id,
+ metrics: evidence.metrics, trafficSources: evidence.trafficSources, capturedAt
+ });
+
+ const elapsedHours = (this.now().getTime() - new Date(arm.startedAt).getTime()) / 3600000;
+ if (!options.forceAdvance && elapsedHours < experiment.armDurationHours) {
+ return this.db.getGrowthExperiment(id);
+ }
+
+ const armResult = this.calculateArmResult(arm.baselineMetrics, evidence.metrics);
+ await this.db.updateExperimentArm(arm.id, {
+ status: 'completed', finalMetrics: evidence.metrics, result: armResult, endedAt: capturedAt
+ });
+ const next = experiment.arms.find(candidate => candidate.index === arm.index + 1);
+ if (next) {
+ await this.db.updateExperimentArm(next.id, {
+ status: 'running', baselineMetrics: evidence.metrics, startedAt: capturedAt
+ });
+ await this.db.saveExperimentSample({
+ experimentId: experiment.id, armId: next.id,
+ metrics: evidence.metrics, trafficSources: evidence.trafficSources, capturedAt
+ });
+ await this.db.updateGrowthExperiment(id, { currentArmId: next.id });
+ try {
+ await this.applyArm(experiment, next, arm);
+ } catch (error) {
+ await this.failRestore(experiment, error);
+ throw error;
+ }
+ return this.db.getGrowthExperiment(id);
+ }
+
+ const completed = await this.db.getGrowthExperiment(id);
+ const result = await this.evaluate(completed);
+ const control = completed.arms.find(candidate => candidate.isControl);
+ try {
+ await this.applyArm(completed, control, arm);
+ } catch (error) {
+ await this.failRestore(completed, error, result);
+ throw error;
+ }
+ return this.db.updateGrowthExperiment(id, {
+ status: result.winnerArmId ? 'awaiting_winner' : 'inconclusive',
+ currentArmId: null,
+ winningArmId: result.winnerArmId || null,
+ result,
+ completedAt: capturedAt
+ });
+ }
+
+ async adoptWinner(id, input = {}) {
+ const experiment = await this.requireExperiment(id);
+ if (experiment.status !== 'awaiting_winner' || !experiment.winningArmId) {
+ throw this.error('This experiment has no evidence-backed winner to adopt', 409);
+ }
+ if (input.confirmed !== true) throw this.error('Confirm the winner before changing live YouTube packaging', 409, 'EXPERIMENT_CONFIRMATION_REQUIRED');
+ const winner = experiment.arms.find(arm => arm.id === experiment.winningArmId);
+ const control = experiment.arms.find(arm => arm.isControl);
+ await this.applyArm(experiment, winner, control);
+ const recommendation = await this.db.saveLearningRecommendation({
+ fingerprint: `growth-experiment:${experiment.id}:winner`,
+ category: 'packaging_experiment',
+ title: `Reuse the ${winner.label} packaging pattern`,
+ rationale: `${winner.label} produced ${winner.result.ctr.toFixed(2)}% CTR across ${winner.result.impressions} qualified impressions in a controlled test.`,
+ evidence: {
+ experimentId: experiment.id,
+ videoId: experiment.videoId,
+ winnerArmId: winner.id,
+ liftPercent: experiment.result.liftPercent,
+ zScore: experiment.result.zScore,
+ guardrails: experiment.result.guardrails
+ },
+ proposedChange: {
+ target: 'future_packaging',
+ experiment: 'validated_title_thumbnail_pattern',
+ winningTitle: winner.title,
+ hypothesis: experiment.hypothesis,
+ autoApply: false
+ },
+ confidence: experiment.result.confidence || 'medium'
+ });
+ await this.db.reviewLearningRecommendation(recommendation.id, 'approved');
+ return this.db.updateGrowthExperiment(id, {
+ status: 'adopted', adoptedAt: this.isoNow(), currentArmId: winner.id
+ });
+ }
+
+ async cancel(id, input = {}) {
+ const experiment = await this.requireExperiment(id);
+ if (!['draft', 'approved', 'running', 'action_required'].includes(experiment.status)) {
+ throw this.error('This experiment can no longer be cancelled', 409);
+ }
+ if (input.confirmed !== true) throw this.error('Confirm cancellation before restoring the control packaging', 409, 'EXPERIMENT_CONFIRMATION_REQUIRED');
+ if (['running', 'action_required'].includes(experiment.status)) {
+ const control = experiment.arms.find(arm => arm.isControl);
+ const current = experiment.arms.find(arm => arm.id === experiment.currentArmId) || control;
+ await this.applyArm(experiment, control, current);
+ }
+ return this.db.updateGrowthExperiment(id, {
+ status: 'cancelled', currentArmId: null, cancelledAt: this.isoNow()
+ });
+ }
+
+ async refreshDue() {
+ const running = await this.db.listGrowthExperiments({ status: 'running', limit: 50 });
+ let refreshed = 0;
+ let failed = 0;
+ for (const experiment of running) {
+ const samples = await this.db.listExperimentSamples(experiment.id, 250);
+ const latest = samples.at(-1);
+ const ageHours = latest ? (this.now().getTime() - new Date(latest.capturedAt).getTime()) / 3600000 : Infinity;
+ if (ageHours < 4) continue;
+ try {
+ await this.refresh(experiment.id);
+ refreshed++;
+ } catch (error) {
+ failed++;
+ this.logger.error(`Growth experiment refresh failed for ${experiment.id}: ${error.message}`);
+ }
+ }
+ return { running: running.length, refreshed, failed };
+ }
+
+ async getSummary() {
+ const experiments = await this.db.listGrowthExperiments({ limit: 25 });
+ const rows = await this.db.getAllRows(
+ `SELECT p.id AS production_id, ps.title, ps.youtube_id, cr.editor_data
+ FROM publish_schedule ps
+ JOIN productions p ON p.id = ps.production_id
+ JOIN content_reviews cr ON cr.production_id = p.id
+ WHERE ps.status = 'published' AND ps.youtube_id IS NOT NULL
+ ORDER BY ps.published_at DESC LIMIT 50`
+ );
+ const activeProductionIds = new Set(experiments.filter(item => ACTIVE_STATUSES.has(item.status)).map(item => item.productionId));
+ const candidates = (await Promise.all(rows.map(async row => {
+ const packaging = this.parseJSON(row.editor_data, {}).packagingExperiment;
+ if (!packaging?.sourceRecommendationId || activeProductionIds.has(row.production_id)) return null;
+ const recommendation = await this.db.getLearningRecommendation(packaging.sourceRecommendationId);
+ if (recommendation?.status !== 'approved') return null;
+ return { productionId: row.production_id, videoId: row.youtube_id, title: row.title };
+ }))).filter(Boolean);
+ return {
+ experiments,
+ candidates,
+ activeCount: experiments.filter(item => item.status === 'running').length,
+ awaitingDecisionCount: experiments.filter(item => item.status === 'awaiting_winner').length,
+ evidencePolicy: 'Only real YouTube evidence counts. Plan approval authorizes bounded arm rotations; adopting a winner always requires a separate confirmation.'
+ };
+ }
+
+ async evaluate(experiment) {
+ const samples = await this.db.listExperimentSamples(experiment.id, 1000);
+ const arms = experiment.arms.map(arm => {
+ const armSamples = samples.filter(sample => sample.armId === arm.id);
+ const trafficShift = this.trafficSourceShift(armSamples.at(0)?.trafficSources, armSamples.at(-1)?.trafficSources);
+ return { ...arm, result: { ...arm.result, trafficSourceShiftPoints: trafficShift } };
+ });
+ await Promise.all(arms.map(arm => this.db.updateExperimentArm(arm.id, { result: arm.result })));
+ const eligible = arms.filter(arm => arm.result.impressions >= experiment.minImpressions && arm.result.clicks >= 10);
+ const result = {
+ primaryMetric: 'ctr',
+ minImpressions: experiment.minImpressions,
+ eligibleArms: eligible.length,
+ totalArms: arms.length,
+ winnerArmId: null,
+ confidence: 'low',
+ reason: '',
+ guardrails: { passed: false }
+ };
+ if (eligible.length !== arms.length) {
+ result.reason = 'Inconclusive: every arm must reach the minimum qualified impressions and clicks.';
+ return result;
+ }
+ const ranked = [...eligible].sort((a, b) => b.result.ctr - a.result.ctr);
+ const [best, runnerUp] = ranked;
+ const zScore = this.twoProportionZ(best.result, runnerUp.result);
+ const control = arms.find(arm => arm.isControl);
+ const retentionDrop = control && best.id !== control.id
+ ? Number((best.result.averageViewPercentage - control.result.averageViewPercentage).toFixed(2))
+ : 0;
+ const trafficShift = Number(best.result.trafficSourceShiftPoints || 0);
+ const guardrailsPassed = retentionDrop >= -Number(experiment.guardrails.maximumRetentionDropPoints || 5)
+ && trafficShift <= Number(experiment.guardrails.maximumTrafficSourceShiftPoints || 20);
+ Object.assign(result, {
+ zScore: Number(zScore.toFixed(3)),
+ liftPercent: runnerUp.result.ctr > 0
+ ? Number((((best.result.ctr - runnerUp.result.ctr) / runnerUp.result.ctr) * 100).toFixed(1))
+ : null,
+ guardrails: { passed: guardrailsPassed, retentionDropPoints: retentionDrop, trafficSourceShiftPoints: trafficShift }
+ });
+ if (zScore < 1.96) {
+ result.reason = 'Inconclusive: the leading arm did not clear the 95% evidence threshold.';
+ } else if (!guardrailsPassed) {
+ result.reason = 'Inconclusive: the leading arm regressed a retention or traffic-mix guardrail.';
+ } else {
+ result.winnerArmId = best.id;
+ result.confidence = zScore >= 2.576 ? 'high' : 'medium';
+ result.reason = `${best.label} cleared the evidence and guardrail thresholds.`;
+ }
+ return result;
+ }
+
+ calculateArmResult(start = {}, end = {}) {
+ const impressions = Math.max(0, Number(end.impressions || 0) - Number(start.impressions || 0));
+ const clicks = Math.max(0, Number(end.clicks || 0) - Number(start.clicks || 0));
+ const views = Math.max(0, Number(end.views || 0) - Number(start.views || 0));
+ const intervalAverage = key => {
+ if (!views) return Number(end[key] || 0);
+ const weighted = (Number(end[key] || 0) * Number(end.views || 0))
+ - (Number(start[key] || 0) * Number(start.views || 0));
+ return Number(Math.max(0, weighted / views).toFixed(3));
+ };
+ return {
+ impressions,
+ clicks: Number(clicks.toFixed(3)),
+ ctr: impressions > 0 ? Number(((clicks / impressions) * 100).toFixed(3)) : 0,
+ views,
+ watchMinutes: Math.max(0, Number(end.watchMinutes || 0) - Number(start.watchMinutes || 0)),
+ netSubscribers: Number(end.netSubscribers || 0) - Number(start.netSubscribers || 0),
+ estimatedRevenue: Number((Number(end.estimatedRevenue || 0) - Number(start.estimatedRevenue || 0)).toFixed(3)),
+ averageViewPercentage: intervalAverage('averageViewPercentage'),
+ engagementRate: intervalAverage('engagementRate')
+ };
+ }
+
+ twoProportionZ(first, second) {
+ const n1 = Number(first.impressions || 0);
+ const n2 = Number(second.impressions || 0);
+ if (!n1 || !n2) return 0;
+ const p1 = Number(first.clicks || 0) / n1;
+ const p2 = Number(second.clicks || 0) / n2;
+ const pooled = (Number(first.clicks || 0) + Number(second.clicks || 0)) / (n1 + n2);
+ const standardError = Math.sqrt(pooled * (1 - pooled) * ((1 / n1) + (1 / n2)));
+ return standardError > 0 ? Math.abs(p1 - p2) / standardError : 0;
+ }
+
+ trafficSourceShift(start = [], end = []) {
+ const toMap = sources => new Map((sources || []).map(source => [source.source, Number(source.percentage || 0)]));
+ const a = toMap(start);
+ const b = toMap(end);
+ const keys = new Set([...a.keys(), ...b.keys()]);
+ return Number(Math.max(0, ...[...keys].map(key => Math.abs((b.get(key) || 0) - (a.get(key) || 0)))).toFixed(2));
+ }
+
+ async captureMetrics(videoId) {
+ const report = await this.analytics.analyzeVideoPerformance(videoId, { measurementWindow: 'rolling' });
+ if (!report || report.analytics?.simulated) {
+ throw this.error('Real YouTube analytics are unavailable; simulated evidence cannot advance an experiment', 409, 'EXPERIMENT_EVIDENCE_UNAVAILABLE');
+ }
+ const views = report.analytics?.views || {};
+ const ctr = Number(report.thumbnailMetrics?.clickThroughRate ?? views.averageCTR ?? 0);
+ const impressions = Number(report.thumbnailMetrics?.impressions ?? views.totalImpressions ?? 0);
+ const dailyRows = Array.isArray(views.dailyData) ? views.dailyData : [];
+ const clicks = dailyRows.length
+ ? dailyRows.reduce((sum, row) => sum + (Number(row[2] || 0) * Number(row[3] || 0) / 100), 0)
+ : impressions * ctr / 100;
+ return {
+ metrics: {
+ impressions,
+ clicks: Number(clicks.toFixed(3)),
+ ctr,
+ views: Number(views.totalViews || 0),
+ watchMinutes: Number(report.analytics?.watchTime?.totalWatchTime || 0),
+ averageViewPercentage: Number(report.analytics?.watchTime?.averageViewPercentage || 0),
+ engagementRate: Number(report.analytics?.engagement?.engagementRate || 0),
+ netSubscribers: Number(report.analytics?.outcomes?.netSubscribers || 0),
+ estimatedRevenue: Number(report.analytics?.outcomes?.estimatedRevenue || 0)
+ },
+ trafficSources: report.analytics?.trafficSources?.sources || []
+ };
+ }
+
+ async applyArm(experiment, arm, previousArm) {
+ if (!arm) throw this.error('Experiment arm is missing', 409, 'EXPERIMENT_STATE_INVALID');
+ await this.publishing.applyVideoPackaging(experiment.videoId, {
+ title: arm.title,
+ thumbnailPath: arm.thumbnailPath
+ }, previousArm ? {
+ title: previousArm.title,
+ thumbnailPath: previousArm.thumbnailPath
+ } : null);
+ }
+
+ async failRestore(experiment, error, result = {}) {
+ await this.db.updateGrowthExperiment(experiment.id, {
+ status: 'action_required',
+ result: { ...result, restoreError: error.message },
+ completedAt: this.isoNow()
+ });
+ }
+
+ async requireExperiment(id) {
+ const experiment = await this.db.getGrowthExperiment(String(id || ''));
+ if (!experiment) throw this.error('Growth experiment not found', 404, 'EXPERIMENT_NOT_FOUND');
+ return experiment;
+ }
+
+ async requireFile(filePath, message) {
+ try {
+ const stats = await fs.stat(filePath);
+ if (!stats.isFile() || stats.size === 0) throw new Error('empty');
+ } catch (_error) {
+ throw this.error(message, 409, 'EXPERIMENT_ASSET_MISSING');
+ }
+ }
+
+ isoNow() {
+ return this.now().toISOString();
+ }
+
+ parseJSON(value, fallback) {
+ try { return JSON.parse(value || ''); } catch (_error) { return fallback; }
+ }
+}
+
+module.exports = { GrowthExperimentService };