🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
feat: add scene-aware retention studio
darkzOGxc14e79c71a58
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de5997e..92959b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@## Unreleased+- Added persistent scene-aware audience-retention snapshots using YouTube's granular elapsed-time curve, with separate long-form and Shorts evidence+- Mapped retention points onto durable production scenes and classified scene-level drop-off, rewatch, strong-hold, and steady signals+- Added an accessible dashboard retention curve, scene evidence cards, manual read-only refresh, and stored-evidence API+- Added approval-gated scene-retention recommendations; missing, sparse, and simulated curves remain excluded and published videos are never edited automatically- Added a persistent Shorts Repurposing Studio that proposes source-scene-backed vertical excerpts from an existing production without new provider calls- Added local 9:16 FFmpeg rendering with blurred-canvas, center-crop, and stacked-focus layouts plus mobile-safe burned captions and SRT output- Added independent Short review, evidence inheritance, scheduling, publishing-state reconciliation, and Shorts-specific analytics contextdiff --git a/README.md b/README.mdindex 9458666..d3d374c 100644--- a/README.md+++ b/README.md@@ -12,6 +12,7 @@ Research topics → write scripts → generate narration and visuals → assemblThe latest build expands AgentTube from evidence-first long-form production into a repairable, provider-flexible, multi-format channel workflow:+- **Scene-aware retention:** collect YouTube's real 100-point audience-retention curve, map it to the durable production timeline, and review scene-specific drop-off, rewatch, and strong-hold evidence before it can guide future work.- **Shorts Repurposing Studio:** turn an approved production into three source-scene-backed 9:16 drafts, choose blurred, cropped, or stacked layouts, render mobile captions locally, and approve each Short on its own schedule.- **Scene-level repair:** edit, reorder, lock, replace, or regenerate one scene, then rebuild the final MP4 without discarding the rest of the production.- **Narration reliability:** missing, stale, simulated, or failed TTS now blocks assembly, approval, scheduling, and publishing; narration-only recovery and reasoned intentional silence are explicit operator actions.@@ -111,6 +112,12 @@ Open **Analytics → What the agent learned** to review the evidence and confideWhen an approved learning calls for better packaging, Lumen prepares a control plus title and thumbnail variants for new videos. Review Studio shows those options before approval; the selected combination is the only one handed to the publishing queue. Lumen does not silently swap live YouTube metadata.+### Find the exact scene that lost viewers++At each real analytics window, AgentTube also requests YouTube's audience-retention curve and maps its 100 elapsed-time points onto the stored scene durations. Open **Analytics → Scene-aware retention** to see the curve divided by scene, compare absolute and relative retention, and inspect drop-off, rewatch, strong-hold, or steady signals for each beat.++Retention snapshots are stored separately for long-form videos and Shorts. Missing, sparse, or simulated curves never enter this evidence layer. A scene finding creates a pending learning recommendation; it cannot guide future scripts, pacing, or scene structure until the operator approves it, and AgentTube never rewrites a published video. Use **Refresh curve** for a read-only update from YouTube Analytics, or `GET /api/retention/:videoId` to inspect stored evidence.+## From idea to published video| Stage | What Lumen does | What you control |diff --git a/agents/analytics-optimization-agent.js b/agents/analytics-optimization-agent.jsindex 7950707..2e6eb56 100644--- a/agents/analytics-optimization-agent.js+++ b/agents/analytics-optimization-agent.js@@ -65,6 +65,13 @@ class AnalyticsOptimizationAgent {// Get analytics dataconst analytics = await this.getVideoAnalytics(videoId, period);+ const context = await this.db.getPublishedContentContext(videoId);++ // Fetch the granular retention curve separately so its absence never+ // converts otherwise-real channel analytics into simulated data.+ const retention = analytics.simulated+ ? { available: false, simulated: true, reason: 'base_analytics_unavailable', points: [] }+ : await this.getAudienceRetention(videoId, period, videoDetails.duration);// Analyze thumbnail performanceconst thumbnailMetrics = await this.analyzeThumbnailPerformance(videoId, period);@@ -79,6 +86,7 @@ class AnalyticsOptimizationAgent {videoId,videoDetails,analytics,+ retention,thumbnailMetrics,seoMetrics,insights,@@ -92,12 +100,27 @@ class AnalyticsOptimizationAgent {// Save to databaseawait this.db.saveAnalyticsReport(performanceReport);- const context = await this.db.getPublishedContentContext(videoId);performanceReport.learningSnapshot = await this.learning.capture(performanceReport,context,measurementWindow);+ if (retention.available) {+ performanceReport.retentionSnapshot = await this.learning.captureRetention(+ {+ ...retention,+ videoId,+ title: videoDetails.title,+ publishedAt: videoDetails.publishedAt+ },+ context,+ measurementWindow,+ {+ views: analytics.views?.totalViews,+ impressions: analytics.views?.totalImpressions+ }+ );+ }this.logger.info(`Analysis complete. Performance score: ${performanceReport.performance.score}/100`);return performanceReport;@@ -701,6 +724,52 @@ class AnalyticsOptimizationAgent {};}+ async getAudienceRetention(videoId, period = null, isoDuration = null) {+ const endDate = period?.endDate || new Date().toISOString().split('T')[0];+ const startDate = period?.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];+ try {+ const response = await this.youtubeAnalytics.reports.query({+ ids: 'channel==MINE',+ startDate,+ endDate,+ metrics: 'audienceWatchRatio,relativeRetentionPerformance,startedWatching,stoppedWatching,totalSegmentImpressions',+ dimensions: 'elapsedVideoTimeRatio',+ filters: `video==${videoId}`+ });+ const headers = (response.data.columnHeaders || []).map(header => header.name);+ const index = name => headers.indexOf(name);+ const value = (row, name) => {+ const position = index(name);+ return position >= 0 ? Number(row[position] || 0) : 0;+ };+ const points = (response.data.rows || []).map(row => ({+ elapsedRatio: value(row, 'elapsedVideoTimeRatio'),+ audienceWatchRatio: value(row, 'audienceWatchRatio'),+ relativeRetentionPerformance: value(row, 'relativeRetentionPerformance'),+ startedWatching: value(row, 'startedWatching'),+ stoppedWatching: value(row, 'stoppedWatching'),+ totalSegmentImpressions: value(row, 'totalSegmentImpressions')+ })).filter(point => point.elapsedRatio > 0);+ return {+ available: points.length > 0,+ simulated: false,+ reason: points.length ? null : 'no_retention_rows',+ period: { startDate, endDate },+ durationSeconds: this.parseISODurationSeconds(isoDuration),+ points+ };+ } catch (error) {+ this.logger.warn(`Audience retention curve unavailable for ${videoId}: ${error.message}`);+ return { available: false, simulated: false, reason: 'retention_api_unavailable', points: [] };+ }+ }++ parseISODurationSeconds(value) {+ const match = String(value || '').match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/);+ if (!match) return 0;+ return Number(match[1] || 0) * 86400 + Number(match[2] || 0) * 3600 + Number(match[3] || 0) * 60 + Number(match[4] || 0);+ }+getLearningSummary() {return this.learning.getSummary();}diff --git a/dashboard/app.js b/dashboard/app.jsindex 602999d..aef7b9c 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -2,7 +2,8 @@ const ui = {state: null,currentView: 'overview',refreshing: false,- toastTimer: null+ toastTimer: null,+ retentionSnapshotId: null};const $ = selector => document.querySelector(selector);@@ -312,6 +313,7 @@ function renderAnalytics(analytics, learning = {}) {$('#top-performers').innerHTML = performers.length ? performers.map(item => `<article class="performer-card"><strong>${escapeHTML(item.videoDetails?.title || item.title || 'Untitled video')}</strong><div class="meta-line">Performance ${escapeHTML(item.performance?.score ?? item.performance_score ?? '—')} / 100</div></article>`).join('') : empty('No analyzed videos yet.');renderLearning(learning);+ renderRetention(learning.retention || {});}function renderLearning(learning = {}) {@@ -341,6 +343,86 @@ function renderLearning(learning = {}) {</article>`).join('') : empty('No recommendation yet. Lumen needs at least two real, sufficiently exposed measurements.');}+function renderRetention(retention = {}) {+ const snapshots = Array.isArray(retention.snapshots) ? retention.snapshots : [];+ const select = $('#retention-snapshot-select');+ const refresh = $('#refresh-retention-button');+ if (!snapshots.length) {+ ui.retentionSnapshotId = null;+ select.innerHTML = '<option value="">No measured curves yet</option>';+ select.disabled = true;+ refresh.disabled = true;+ $('#retention-meta').innerHTML = '';+ $('#retention-chart').innerHTML = empty('Retention curves appear after a published video reaches a real analytics measurement window.');+ $('#retention-scenes').innerHTML = '';+ return;+ }++ if (!snapshots.some(item => item.id === ui.retentionSnapshotId)) ui.retentionSnapshotId = snapshots[0].id;+ select.disabled = false;+ refresh.disabled = false;+ select.innerHTML = snapshots.map(item => `<option value="${escapeHTML(item.id)}" ${item.id === ui.retentionSnapshotId ? 'selected' : ''}>${escapeHTML(item.title || item.videoId)} · ${escapeHTML(label(item.surface))} · ${escapeHTML(item.measurementWindow)}</option>`).join('');+ const snapshot = snapshots.find(item => item.id === ui.retentionSnapshotId) || snapshots[0];+ refresh.dataset.videoId = snapshot.videoId;+ refresh.dataset.measurementWindow = snapshot.measurementWindow;++ const summary = snapshot.summary || {};+ $('#retention-meta').innerHTML = [+ `${snapshot.points?.length || 0} real points`,+ `${snapshot.sceneMetrics?.length || 0} scenes`,+ `${summary.dropoffCount || 0} drop-offs`,+ `${summary.rewatchCount || 0} rewatch signals`,+ `${escapeHTML(label(snapshot.confidence))} confidence`,+ `${escapeHTML(snapshot.measurementWindow)} window`+ ].map(item => `<span>${item}</span>`).join('');+ $('#retention-chart').innerHTML = retentionChart(snapshot);+ $('#retention-scenes').innerHTML = (snapshot.sceneMetrics || []).map(scene => `+ <article class="retention-scene ${escapeHTML(scene.signal)}">+ <div class="retention-scene-heading"><div><span>Scene ${Number(scene.position || 0) + 1}</span><strong>${escapeHTML(scene.label)}</strong></div>${statusChip(scene.signal)}</div>+ <div class="retention-metrics">+ <div><span>Average watching</span><strong>${(Number(scene.averageWatchRatio || 0) * 100).toFixed(1)}%</strong></div>+ <div><span>Scene change</span><strong>${Number(scene.changePoints || 0) > 0 ? '+' : ''}${Number(scene.changePoints || 0).toFixed(1)} pts</strong></div>+ <div><span>Relative retention</span><strong>${(Number(scene.averageRelativeRetention || 0) * 100).toFixed(1)}%</strong></div>+ <div><span>Sharpest drop</span><strong>${Number(scene.largestDropPoints || 0).toFixed(1)} pts</strong></div>+ </div>+ </article>`).join('') || empty('The saved curve could not be mapped to a scene timeline.');+}++function retentionChart(snapshot = {}) {+ const points = Array.isArray(snapshot.points) ? snapshot.points : [];+ if (points.length < 2) return empty('This snapshot does not contain enough points for a curve.');+ const width = 1000;+ const height = 280;+ const left = 46;+ const right = 18;+ const top = 18;+ const bottom = 38;+ const plotWidth = width - left - right;+ const plotHeight = height - top - bottom;+ const maxRatio = Math.max(1, Math.min(1.5, Math.max(...points.map(point => Number(point.audienceWatchRatio || 0))) * 1.05));+ const x = ratio => left + Math.max(0, Math.min(1, Number(ratio || 0))) * plotWidth;+ const y = ratio => top + (1 - Math.max(0, Math.min(maxRatio, Number(ratio || 0))) / maxRatio) * plotHeight;+ const line = points.map(point => `${x(point.elapsedRatio).toFixed(1)},${y(point.audienceWatchRatio).toFixed(1)}`).join(' ');+ const duration = Math.max(1, Number(snapshot.durationSeconds || 1));+ const sceneBands = (snapshot.sceneMetrics || []).map((scene, index) => {+ const start = x(Number(scene.startSeconds || 0) / duration);+ const end = x(Number(scene.endSeconds || 0) / duration);+ return `<g><rect x="${start.toFixed(1)}" y="${top}" width="${Math.max(1, end - start).toFixed(1)}" height="${plotHeight}" class="retention-band band-${index % 2}"/><line x1="${start.toFixed(1)}" y1="${top}" x2="${start.toFixed(1)}" y2="${top + plotHeight}" class="scene-boundary"/><title>${escapeHTML(scene.label)}</title></g>`;+ }).join('');+ const grid = [0.25, 0.5, 0.75, 1].map(value => {+ const lineY = y(value);+ return `<line x1="${left}" y1="${lineY.toFixed(1)}" x2="${width - right}" y2="${lineY.toFixed(1)}" class="retention-grid-line"/><text x="${left - 8}" y="${(lineY + 4).toFixed(1)}" text-anchor="end">${Math.round(value * 100)}%</text>`;+ }).join('');+ return `<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="retention-chart-title retention-chart-desc">+ <title id="retention-chart-title">Audience retention for ${escapeHTML(snapshot.title || snapshot.videoId)}</title>+ <desc id="retention-chart-desc">A ${points.length}-point audience retention curve divided by ${snapshot.sceneMetrics?.length || 0} production scenes.</desc>+ ${sceneBands}${grid}+ <polyline points="${line}" class="retention-line"/>+ <text x="${left}" y="${height - 10}" text-anchor="start">Start</text>+ <text x="${width - right}" y="${height - 10}" text-anchor="end">End</text>+ </svg>`;+}+function renderActivation(activation = {}) {const container = $('#activation-list');if (!container) return;@@ -891,6 +973,23 @@ document.addEventListener('click', async event => {await mutate(`/api/learning/recommendations/${encodeURIComponent(id)}/${action}`, 'POST', {}, message).catch(() => {});}+ const refreshRetention = event.target.closest('#refresh-retention-button');+ if (refreshRetention?.dataset.videoId) {+ refreshRetention.disabled = true;+ try {+ await api(`/api/retention/${encodeURIComponent(refreshRetention.dataset.videoId)}/refresh`, {+ method: 'POST',+ body: JSON.stringify({ measurementWindow: refreshRetention.dataset.measurementWindow || 'rolling' })+ });+ showToast('Retention curve refreshed from YouTube Analytics.');+ await refreshDashboard(true);+ } catch (error) {+ showToast(error.message, 'error');+ } finally {+ refreshRetention.disabled = false;+ }+ }+const proposeShorts = event.target.closest('[data-propose-shorts]');if (proposeShorts) {const productionId = proposeShorts.dataset.proposeShorts;@@ -1098,6 +1197,10 @@ document.addEventListener('click', async event => {});document.addEventListener('change', event => {+ if (event.target.matches('#retention-snapshot-select')) {+ ui.retentionSnapshotId = event.target.value;+ renderRetention(ui.state?.learning?.retention || {});+ }if (event.target.matches('[name="selectedTitleVariant"]')) {const title = event.target.selectedOptions[0]?.dataset.title;const input = $('#content-review-form [name="title"]');diff --git a/dashboard/index.html b/dashboard/index.htmlindex 1315c0e..446c081 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -140,6 +140,19 @@<div id="learning-recommendations" class="learning-list"></div></article></div>+ <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>+ <div class="retention-controls">+ <label><span class="sr-only">Retention snapshot</span><select id="retention-snapshot-select" aria-label="Choose a retention snapshot"></select></label>+ <button id="refresh-retention-button" class="button secondary small" disabled>Refresh curve</button>+ </div>+ </div>+ <div id="retention-meta" class="scene-summary"></div>+ <div id="retention-chart" class="retention-chart"></div>+ <div id="retention-scenes" class="retention-scene-list"></div>+ <p class="callout retention-policy">Scene findings remain evidence only. They influence future scripts and pacing only after their recommendation is approved above; published videos are never edited automatically.</p>+ </article><article class="panel"><div class="panel-heading"><div><p class="eyebrow">TOP PERFORMERS</p><h2>What is working</h2></div></div><div id="top-performers" class="card-list"></div></article><article class="panel activation-panel"><div class="panel-heading"><div><p class="eyebrow">LOCAL ACTIVATION</p><h2>First-run journey</h2></div></div><p class="callout">Calculated locally from your database and video files. Nothing is transmitted unless anonymous telemetry is explicitly enabled.</p><div id="activation-list" class="timeline"></div></article></section>diff --git a/dashboard/styles.css b/dashboard/styles.cssindex 186de36..651abd5 100644--- a/dashboard/styles.css+++ b/dashboard/styles.css@@ -140,6 +140,37 @@ input:focus, textarea:focus, select:focus { border-color: #636d7c; box-shadow: 0.learning-meta { color: var(--muted); font-size: 11px; }.learning-actions { display: flex; gap: 12px; }.text-button.approve { color: var(--green); }+.retention-studio { display: grid; gap: 16px; margin-bottom: 18px; overflow: hidden; }+.retention-heading { align-items: flex-start; margin-bottom: 0; }+.retention-heading p:not(.eyebrow) { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 7px 0 0; }+.retention-controls { display: flex; align-items: end; gap: 9px; min-width: min(100%, 360px); }+.retention-controls label { flex: 1; }+.retention-controls select { min-width: 220px; }+.retention-chart { min-width: 0; border: 1px solid var(--line); border-radius: 12px; background: #090c10; overflow: hidden; }+.retention-chart svg { display: block; width: 100%; height: auto; min-height: 210px; }+.retention-chart text { fill: var(--muted); font-size: 11px; }+.retention-band.band-0 { fill: rgba(114,165,255,.035); }+.retention-band.band-1 { fill: rgba(204,121,255,.035); }+.scene-boundary { stroke: rgba(255,255,255,.14); stroke-width: 1; stroke-dasharray: 4 5; }+.retention-grid-line { stroke: rgba(255,255,255,.09); stroke-width: 1; }+.retention-line { fill: none; stroke: var(--red); stroke-width: 4; stroke-linecap: round; stroke-linejoin: round; filter: drop-shadow(0 3px 8px rgba(255,77,94,.2)); }+.retention-scene-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }+.retention-scene { display: grid; gap: 12px; min-width: 0; border: 1px solid var(--line); border-radius: 11px; padding: 13px; background: rgba(255,255,255,.018); }+.retention-scene.drop_off { border-color: rgba(255,137,148,.34); }+.retention-scene.strong_hold, .retention-scene.rewatch { border-color: rgba(72,213,151,.25); }+.retention-scene-heading { display: flex; justify-content: space-between; align-items: start; gap: 12px; }+.retention-scene-heading span, .retention-scene-heading strong { display: block; }+.retention-scene-heading span { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .07em; margin-bottom: 4px; }+.retention-metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }+.retention-metrics > div { border-top: 1px solid var(--line); padding-top: 8px; }+.retention-metrics span, .retention-metrics strong { display: block; }+.retention-metrics span { color: var(--muted); font-size: 9px; text-transform: uppercase; letter-spacing: .05em; }+.retention-metrics strong { margin-top: 4px; font-size: 13px; }+.retention-policy { margin-top: 0; }+.status.drop_off { color: #ff8994; background: var(--red-soft); }+.status.strong_hold, .status.rewatch { color: var(--green); background: rgba(72,213,151,.12); }+.status.steady, .status.insufficient { color: var(--blue); background: rgba(114,165,255,.12); }+.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }.settings-form { max-width: 920px; }.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }.form-grid.two { grid-template-columns: 1fr 1fr; }@@ -284,7 +315,7 @@ label small { color: var(--muted); font-weight: 400; }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 { grid-template-columns: 1fr; }+ .overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid, .retention-scene-list { grid-template-columns: 1fr; }.overview-grid, .card-list, .job-card { min-width: 0; max-width: 100%; }.pipeline-item { grid-template-columns: 1fr auto; }.pipeline-col { display: none; }@@ -304,5 +335,7 @@ label small { color: var(--muted); font-weight: 400; }.short-preview { max-width: 230px; justify-self: center; }.scene-options { align-items: flex-start; flex-direction: column; }.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; }.scene-actions { gap: 4px 11px; }}diff --git a/database/db.js b/database/db.jsindex ec7636a..c27742c 100644--- a/database/db.js+++ b/database/db.js@@ -177,6 +177,23 @@ class Database {updated_at TEXT DEFAULT CURRENT_TIMESTAMP,reviewed_at TEXT)`,+ `CREATE TABLE IF NOT EXISTS retention_snapshots (+ id TEXT PRIMARY KEY,+ video_id TEXT NOT NULL,+ production_id TEXT,+ short_clip_id TEXT,+ title TEXT,+ surface TEXT NOT NULL DEFAULT 'long_form',+ measurement_window TEXT NOT NULL,+ published_at TEXT,+ duration_seconds REAL NOT NULL,+ points TEXT NOT NULL,+ scene_metrics TEXT NOT NULL,+ summary TEXT NOT NULL,+ confidence TEXT DEFAULT 'low',+ measured_at TEXT DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(video_id, measurement_window)+ )`,// Keywords Performance`CREATE TABLE IF NOT EXISTS keyword_performance (@@ -1673,6 +1690,96 @@ class Database {};}+ async saveRetentionSnapshot(snapshot) {+ const existing = await this.getRow(+ 'SELECT id FROM retention_snapshots WHERE video_id = ? AND measurement_window = ?',+ [snapshot.videoId, snapshot.measurementWindow]+ );+ const id = existing?.id || this.generateId('retention');+ await this.executeQuery(+ `INSERT INTO retention_snapshots (+ id, video_id, production_id, short_clip_id, title, surface,+ measurement_window, published_at, duration_seconds, points,+ scene_metrics, summary, confidence, measured_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(video_id, measurement_window) DO UPDATE SET+ production_id = excluded.production_id,+ short_clip_id = excluded.short_clip_id,+ title = excluded.title,+ surface = excluded.surface,+ published_at = excluded.published_at,+ duration_seconds = excluded.duration_seconds,+ points = excluded.points,+ scene_metrics = excluded.scene_metrics,+ summary = excluded.summary,+ confidence = excluded.confidence,+ measured_at = excluded.measured_at`,+ [+ id,+ snapshot.videoId,+ snapshot.productionId || null,+ snapshot.shortClipId || null,+ snapshot.title || null,+ snapshot.surface || 'long_form',+ snapshot.measurementWindow,+ snapshot.publishedAt || null,+ Number(snapshot.durationSeconds || 0),+ JSON.stringify(snapshot.points || []),+ JSON.stringify(snapshot.sceneMetrics || []),+ JSON.stringify(snapshot.summary || {}),+ snapshot.confidence || 'low',+ snapshot.measuredAt || new Date().toISOString()+ ]+ );+ return this.getRetentionSnapshot(id);+ }++ async getRetentionSnapshot(id) {+ const row = await this.getRow('SELECT * FROM retention_snapshots WHERE id = ?', [id]);+ return this.parseRetentionSnapshot(row);+ }++ async listRetentionSnapshots(options = {}) {+ const conditions = [];+ const params = [];+ if (options.videoId) {+ conditions.push('video_id = ?');+ params.push(options.videoId);+ }+ if (options.surface) {+ conditions.push('surface = ?');+ params.push(options.surface);+ }+ if (options.measurementWindow) {+ conditions.push('measurement_window = ?');+ params.push(options.measurementWindow);+ }+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';+ const limit = Math.max(1, Math.min(50, Number(options.limit || 12)));+ const rows = await this.getAllRows(+ `SELECT * FROM retention_snapshots ${where} ORDER BY measured_at DESC LIMIT ?`,+ [...params, limit]+ );+ return rows.map(row => this.parseRetentionSnapshot(row));+ }++ parseRetentionSnapshot(row) {+ if (!row) return null;+ return {+ ...row,+ videoId: row.video_id,+ productionId: row.production_id,+ shortClipId: row.short_clip_id,+ measurementWindow: row.measurement_window,+ publishedAt: row.published_at,+ durationSeconds: Number(row.duration_seconds || 0),+ measuredAt: row.measured_at,+ points: JSON.parse(row.points || '[]'),+ sceneMetrics: JSON.parse(row.scene_metrics || '[]'),+ summary: JSON.parse(row.summary || '{}')+ };+ }+async saveLearningRecommendation(recommendation) {const existing = await this.getRow('SELECT id FROM learning_recommendations WHERE fingerprint = ?',@@ -1772,6 +1879,8 @@ class Database {const selectedThumbnail = editorData.packagingExperiment?.thumbnailVariants?.[editorData.selectedThumbnailVariant];const isShort = metadata.contentType === 'short';const strategy = JSON.parse(row.strategy || '{}');+ const sourceScenes = await this.listProductionScenes(sourceProductionId);+ const shortClip = isShort && metadata.shortClipId ? await this.getShortClip(metadata.shortClipId) : null;return {productionId: sourceProductionId,shortClipId: metadata.shortClipId || null,@@ -1783,10 +1892,40 @@ class Database {: strategy,script: JSON.parse(row.script || '{}'),thumbnail: selectedThumbnail?.concept ? { ...thumbnail, concept: selectedThumbnail.concept } : thumbnail,- seo: JSON.parse(row.seo || '{}')+ seo: JSON.parse(row.seo || '{}'),+ retentionScenes: this.buildRetentionSceneContext(sourceScenes, shortClip),+ retentionDuration: isShort ? shortClip?.duration || null : sourceScenes.reduce((sum, scene) => sum + Number(scene.duration || 0), 0)};}+ buildRetentionSceneContext(scenes = [], shortClip = null) {+ let cursor = 0;+ const timeline = scenes.map(scene => {+ const duration = Math.max(0, Number(scene.duration || 0));+ const item = { ...scene, startSeconds: cursor, endSeconds: cursor + duration };+ cursor += duration;+ return item;+ });+ if (!shortClip) return timeline;++ const clipStart = Math.max(0, Number(shortClip.startSeconds || 0));+ const clipEnd = clipStart + Math.max(0, Number(shortClip.duration || 0));+ const allowed = new Set(shortClip.sourceSceneIds || []);+ return timeline.flatMap(scene => {+ if (allowed.size && !allowed.has(scene.id)) return [];+ const start = Math.max(scene.startSeconds, clipStart);+ const end = Math.min(scene.endSeconds, clipEnd);+ if (end <= start) return [];+ return [{+ ...scene,+ sourceStartSeconds: start,+ startSeconds: start - clipStart,+ endSeconds: end - clipStart,+ duration: end - start+ }];+ });+ }+// Keyword performanceasync updateKeywordPerformance(keyword, views, videoId) {const existing = await this.getRow(diff --git a/index.js b/index.jsindex 0cfbee1..1c636e1 100644--- a/index.js+++ b/index.js@@ -897,6 +897,39 @@ class YouTubeAutomationAgent {return res.json({ success: true, result: recommendation });});+ 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)) {+ return res.status(400).json({ error: 'A valid YouTube video ID is required' });+ }+ const snapshots = await this.db.listRetentionSnapshots({ videoId, limit: 10 });+ return res.json({ success: true, result: snapshots });+ });++ this.app.post('/api/retention/:videoId/refresh', protect, async (req, res) => {+ try {+ const videoId = String(req.params.videoId || '').trim();+ const measurementWindow = String(req.body?.measurementWindow || 'rolling');+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(videoId)) {+ return res.status(400).json({ error: 'A valid YouTube video ID is required' });+ }+ if (!['24h', '7d', 'rolling'].includes(measurementWindow)) {+ return res.status(400).json({ error: 'Measurement window must be 24h, 7d, or rolling' });+ }+ if (!this.agents.analytics) {+ return res.status(503).json({ error: 'YouTube Analytics is not initialized' });+ }+ const report = await this.agents.analytics.analyzeVideoPerformance(videoId, { measurementWindow });+ return res.json({+ success: true,+ result: report.retentionSnapshot || null,+ retention: report.retention+ });+ } catch (error) {+ return res.status(error.status || 400).json({ error: error.message });+ }+ });+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' });diff --git a/test.js b/test.jsindex 298e48c..73e4b3a 100644--- a/test.js+++ b/test.js@@ -25,6 +25,7 @@ class SystemTest {{ name: 'Operator Workflow API', test: () => this.testOperatorWorkflowAPI() },{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },+ { name: 'Scene-Aware Retention Studio', test: () => this.testSceneAwareRetentionStudio() },{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },{ name: 'Durable Multi-Provider Video Generation', test: () => this.testVideoProviderLayer() },{ name: 'Scene Repair Studio', test: () => this.testSceneRepairStudio() },@@ -582,6 +583,130 @@ class SystemTest {this.logger.info('Closed-loop channel learning test completed successfully');}+ async testSceneAwareRetentionStudio() {+ const fs = require('fs').promises;+ const os = require('os');+ const { ChannelLearningEngine } = require('./utils/channel-learning-engine');+ const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-retention-'));+ const db = new Database();+ db.dbPath = path.join(directory, 'retention.db');+ await db.initialize();++ try {+ const learning = new ChannelLearningEngine(db);+ const points = Array.from({ length: 100 }, (_, index) => {+ const elapsedRatio = (index + 1) / 100;+ let audienceWatchRatio;+ let relativeRetentionPerformance;+ if (elapsedRatio <= 0.17) {+ audienceWatchRatio = 1 - elapsedRatio * 0.4;+ relativeRetentionPerformance = 0.64;+ } else if (elapsedRatio <= 0.5) {+ audienceWatchRatio = 0.93 - ((elapsedRatio - 0.17) / 0.33) * 0.48;+ relativeRetentionPerformance = 0.31;+ } else {+ audienceWatchRatio = 0.45 - (elapsedRatio - 0.5) * 0.08;+ relativeRetentionPerformance = 0.7;+ }+ return {+ elapsedRatio,+ audienceWatchRatio,+ relativeRetentionPerformance,+ startedWatching: index === 0 ? 800 : 0,+ stoppedWatching: elapsedRatio > 0.17 && elapsedRatio <= 0.5 ? 5 : 1,+ totalSegmentImpressions: 800+ };+ });+ const context = {+ productionId: 'retention-production',+ contentFormat: 'long_form',+ title: 'Scene retention fixture',+ publishedAt: new Date(Date.now() - 8 * 86400000).toISOString(),+ retentionDuration: 90,+ retentionScenes: [+ { id: 'scene-hook', position: 0, label: 'Hook', duration: 15 },+ { id: 'scene-intro', position: 1, label: 'Introduction', duration: 30 },+ { id: 'scene-demo', position: 2, label: 'Demonstration', duration: 45 }+ ]+ };+ const snapshot = await learning.captureRetention({+ available: true,+ simulated: false,+ videoId: 'retention-video-1',+ title: context.title,+ publishedAt: context.publishedAt,+ durationSeconds: 90,+ points+ }, context, '7d', { views: 800, impressions: 12000 });++ if (+ !snapshot || snapshot.points.length !== 100 || snapshot.sceneMetrics.length !== 3 ||+ snapshot.summary.primaryDropoff?.id !== 'scene-intro' || snapshot.confidence !== 'high'+ ) {+ throw new Error('The real retention curve was not mapped to the expected scene evidence');+ }+ const recommendation = (await db.listLearningRecommendations({ limit: 20 }))+ .find(item => item.category === 'scene_retention');+ if (!recommendation || recommendation.status !== 'pending' || recommendation.proposedChange.autoEditPublishedContent !== false) {+ throw new Error('Scene retention learning bypassed pending review or published-content safety');+ }+ const approvedBeforeReview = await db.listLearningRecommendations({ status: 'approved', limit: 20 });+ if (approvedBeforeReview.some(item => item.id === recommendation.id)) {+ throw new Error('Pending scene retention learning entered autonomous planning');+ }+ await db.reviewLearningRecommendation(recommendation.id, 'approved');+ const approvedAfterReview = await db.listLearningRecommendations({ status: 'approved', limit: 20 });+ if (!approvedAfterReview.some(item => item.id === recommendation.id)) {+ throw new Error('Approved scene retention learning was not made available to planning');+ }++ const skipped = await learning.captureRetention({+ available: true,+ simulated: true,+ videoId: 'retention-simulated',+ durationSeconds: 90,+ points+ }, context, '7d', { views: 1000 });+ if (skipped !== null || (await db.listRetentionSnapshots({ limit: 10 })).length !== 1) {+ throw new Error('Simulated retention evidence was persisted');+ }++ const clipped = db.buildRetentionSceneContext(context.retentionScenes, {+ startSeconds: 10,+ duration: 35,+ sourceSceneIds: ['scene-hook', 'scene-intro']+ });+ if (clipped.length !== 2 || clipped[0].duration !== 5 || clipped[1].duration !== 30) {+ throw new Error('Shorts retention context did not clip the source scene timeline correctly');+ }++ const analytics = new AnalyticsOptimizationAgent(db, { getYouTubeAuth: () => ({}) });+ analytics.youtubeAnalytics = {+ reports: {+ query: async () => ({+ data: {+ columnHeaders: [+ 'elapsedVideoTimeRatio', 'audienceWatchRatio', 'relativeRetentionPerformance',+ 'startedWatching', 'stoppedWatching', 'totalSegmentImpressions'+ ].map(name => ({ name })),+ rows: [[0.01, 0.99, 0.7, 10, 1, 10]]+ }+ })+ }+ };+ const apiCurve = await analytics.getAudienceRetention('fixture-video', null, 'PT2M30S');+ if (!apiCurve.available || apiCurve.durationSeconds !== 150 || apiCurve.points[0].audienceWatchRatio !== 0.99) {+ throw new Error('YouTube audience retention response was not normalized correctly');+ }+ } finally {+ await db.close();+ await fs.rm(directory, { recursive: true, force: true });+ }++ this.logger.info('Scene-Aware Retention Studio test completed successfully');+ }+async testProductionReadinessGate() {const fs = require('fs').promises;const os = require('os');diff --git a/utils/channel-learning-engine.js b/utils/channel-learning-engine.jsindex 467887c..1c3d085 100644--- a/utils/channel-learning-engine.js+++ b/utils/channel-learning-engine.js@@ -1,10 +1,12 @@const crypto = require('crypto');const { Logger } = require('./logger');+const { SceneRetentionEngine } = require('./scene-retention-engine');class ChannelLearningEngine {constructor(db) {this.db = db;this.logger = new Logger('ChannelLearning');+ this.sceneRetention = new SceneRetentionEngine(db);}async capture(performanceReport, context = {}, measurementWindow = 'rolling') {@@ -200,8 +202,11 @@ class ChannelLearningEngine {}async getSummary() {- const snapshots = await this.db.listPerformanceSnapshots({ reliableOnly: true });- const recommendations = await this.db.listLearningRecommendations({ limit: 50 });+ const [snapshots, recommendations, retentionSnapshots] = await Promise.all([+ this.db.listPerformanceSnapshots({ reliableOnly: true }),+ this.db.listLearningRecommendations({ limit: 50 }),+ this.db.listRetentionSnapshots ? this.db.listRetentionSnapshots({ limit: 12 }) : Promise.resolve([])+ ]);const preferred = this.preferredSnapshotPerVideo(snapshots);return {measuredVideos: preferred.length,@@ -215,10 +220,20 @@ class ChannelLearningEngine {approvedCount: recommendations.filter(item => item.status === 'approved').length,pendingCount: recommendations.filter(item => item.status === 'pending').length,lastMeasuredAt: snapshots[0]?.measuredAt || null,- evidencePolicy: 'Only real YouTube analytics are eligible; simulated fallbacks are excluded.'+ evidencePolicy: 'Only real YouTube analytics are eligible; simulated fallbacks are excluded.',+ retention: {+ snapshotCount: retentionSnapshots.length,+ longFormCount: retentionSnapshots.filter(item => item.surface === 'long_form').length,+ shortsCount: retentionSnapshots.filter(item => item.surface === 'shorts').length,+ snapshots: retentionSnapshots+ }};}+ captureRetention(retentionReport, context = {}, measurementWindow = 'rolling', exposure = {}) {+ return this.sceneRetention.capture(retentionReport, context, measurementWindow, exposure);+ }+async getDueMeasurementWindows(video) {const published = new Date(video.published_at || video.publishedAt);if (Number.isNaN(published.getTime())) return [];diff --git a/utils/scene-retention-engine.js b/utils/scene-retention-engine.jsnew file mode 100644index 0000000..953ad23--- /dev/null+++ b/utils/scene-retention-engine.js@@ -0,0 +1,258 @@+const crypto = require('crypto');+const { Logger } = require('./logger');++class SceneRetentionEngine {+ constructor(db) {+ this.db = db;+ this.logger = new Logger('SceneRetention');+ }++ async capture(retentionReport = {}, context = {}, measurementWindow = 'rolling', exposure = {}) {+ if (retentionReport.simulated || retentionReport.available === false) return null;+ const points = this.normalizePoints(retentionReport.points || []);+ const sourceScenes = Array.isArray(context.retentionScenes) ? context.retentionScenes : [];+ if (points.length < 10 || !sourceScenes.length) {+ this.logger.warn(`Retention curve for ${retentionReport.videoId || 'unknown video'} was not stored because it lacks real curve or scene evidence`);+ return null;+ }++ const durationSeconds = Math.max(+ 1,+ this.number(retentionReport.durationSeconds) ||+ this.number(context.retentionDuration) ||+ sourceScenes.reduce((sum, scene) => sum + this.number(scene.duration), 0)+ );+ const timeline = this.scaleTimeline(sourceScenes, durationSeconds);+ const sceneMetrics = this.mapPointsToScenes(points, timeline, durationSeconds);+ if (!sceneMetrics.length) return null;++ const confidence = this.confidenceFor(points, exposure);+ const summary = this.summarize(sceneMetrics, points);+ const snapshot = await this.db.saveRetentionSnapshot({+ videoId: retentionReport.videoId,+ productionId: context.productionId || null,+ shortClipId: context.shortClipId || null,+ title: retentionReport.title || context.title || '',+ surface: context.contentFormat === 'short' ? 'shorts' : 'long_form',+ measurementWindow,+ publishedAt: retentionReport.publishedAt || context.publishedAt || null,+ durationSeconds,+ points: points.map(point => ({+ ...point,+ elapsedSeconds: Number((point.elapsedRatio * durationSeconds).toFixed(2))+ })),+ sceneMetrics,+ summary,+ confidence+ });++ const recommendation = this.buildRecommendation(snapshot, exposure);+ if (recommendation) {+ await this.db.saveLearningRecommendation({+ ...recommendation,+ fingerprint: this.fingerprint(recommendation)+ });+ }+ return snapshot;+ }++ normalizePoints(points) {+ return points.map(point => ({+ elapsedRatio: this.clamp(this.number(point.elapsedRatio), 0, 1),+ audienceWatchRatio: Math.max(0, this.number(point.audienceWatchRatio)),+ relativeRetentionPerformance: this.clamp(this.number(point.relativeRetentionPerformance), 0, 1),+ startedWatching: Math.max(0, this.number(point.startedWatching)),+ stoppedWatching: Math.max(0, this.number(point.stoppedWatching)),+ totalSegmentImpressions: Math.max(0, this.number(point.totalSegmentImpressions))+ }))+ .filter(point => point.elapsedRatio > 0)+ .sort((a, b) => a.elapsedRatio - b.elapsedRatio)+ .filter((point, index, all) => index === 0 || point.elapsedRatio !== all[index - 1].elapsedRatio);+ }++ scaleTimeline(scenes, durationSeconds) {+ const total = scenes.reduce((sum, scene) => sum + Math.max(0, this.number(scene.duration)), 0);+ if (!total) return [];+ const scale = durationSeconds / total;+ let cursor = 0;+ return scenes.map((scene, index) => {+ const duration = Math.max(0.01, this.number(scene.duration) * scale);+ const item = {+ id: scene.id || `scene_${index}`,+ position: Number.isFinite(Number(scene.position)) ? Number(scene.position) : index,+ label: String(scene.label || `Scene ${index + 1}`),+ startSeconds: Number(cursor.toFixed(2)),+ endSeconds: Number(Math.min(durationSeconds, cursor + duration).toFixed(2)),+ duration: Number(duration.toFixed(2))+ };+ cursor += duration;+ if (index === scenes.length - 1) item.endSeconds = durationSeconds;+ return item;+ });+ }++ mapPointsToScenes(points, timeline, durationSeconds) {+ return timeline.map((scene, sceneIndex) => {+ const selected = points.filter(point => {+ const second = point.elapsedRatio * durationSeconds;+ return second > scene.startSeconds && (second <= scene.endSeconds || sceneIndex === timeline.length - 1);+ });+ if (!selected.length) return null;+ const firstPointIndex = points.indexOf(selected[0]);+ const preceding = firstPointIndex > 0 ? points[firstPointIndex - 1] : selected[0];+ let largestDrop = Math.max(0, preceding.audienceWatchRatio - selected[0].audienceWatchRatio);+ let largestLift = 0;+ for (let index = 1; index < selected.length; index++) {+ largestDrop = Math.max(largestDrop, selected[index - 1].audienceWatchRatio - selected[index].audienceWatchRatio);+ largestLift = Math.max(largestLift, selected[index].audienceWatchRatio - selected[index - 1].audienceWatchRatio);+ }+ const start = selected[0].audienceWatchRatio;+ const end = selected.at(-1).audienceWatchRatio;+ const stopped = selected.reduce((sum, point) => sum + point.stoppedWatching, 0);+ const impressions = selected.reduce((sum, point) => sum + point.totalSegmentImpressions, 0);+ const metric = {+ ...scene,+ pointCount: selected.length,+ startWatchRatio: this.round(start),+ endWatchRatio: this.round(end),+ averageWatchRatio: this.round(this.average(selected.map(point => point.audienceWatchRatio))),+ averageRelativeRetention: this.round(this.average(selected.map(point => point.relativeRetentionPerformance))),+ changePoints: this.round((end - start) * 100, 1),+ largestDropPoints: this.round(largestDrop * 100, 1),+ largestLiftPoints: this.round(largestLift * 100, 1),+ stopRate: impressions > 0 ? this.round((stopped / impressions) * 100, 1) : null,+ replayPeak: this.round(Math.max(...selected.map(point => point.audienceWatchRatio)) * 100, 1)+ };+ metric.signal = this.classify(metric);+ return metric;+ }).filter(Boolean);+ }++ classify(scene) {+ if (scene.pointCount < 2) return 'insufficient';+ if (scene.changePoints <= -8 || scene.largestDropPoints >= 10 || scene.stopRate >= 12) return 'drop_off';+ if (scene.replayPeak >= 105 || scene.largestLiftPoints >= 8) return 'rewatch';+ if (scene.changePoints >= -4 && scene.averageRelativeRetention >= 0.6) return 'strong_hold';+ return 'steady';+ }++ summarize(sceneMetrics, points) {+ const dropoffs = sceneMetrics.filter(scene => scene.signal === 'drop_off')+ .sort((a, b) => this.dropSeverity(b) - this.dropSeverity(a));+ const positive = sceneMetrics.filter(scene => ['strong_hold', 'rewatch'].includes(scene.signal))+ .sort((a, b) => (b.averageRelativeRetention + b.replayPeak / 100) - (a.averageRelativeRetention + a.replayPeak / 100));+ return {+ pointCount: points.length,+ sceneCount: sceneMetrics.length,+ dropoffCount: dropoffs.length,+ rewatchCount: sceneMetrics.filter(scene => scene.signal === 'rewatch').length,+ strongHoldCount: sceneMetrics.filter(scene => scene.signal === 'strong_hold').length,+ primaryDropoff: dropoffs[0] || null,+ strongestScene: positive[0] || null+ };+ }++ buildRecommendation(snapshot, exposure = {}) {+ if (this.number(exposure.views) < 20 || snapshot.points.length < 20) return null;+ const drop = snapshot.summary?.primaryDropoff;+ const strong = snapshot.summary?.strongestScene;+ if (!drop && !strong) return null;+ const source = drop || strong;+ const surface = snapshot.surface === 'shorts' ? 'Shorts' : 'long-form videos';+ const sourceIdentity = {+ sourceVideoId: snapshot.videoId,+ measurementWindow: snapshot.measurementWindow,+ sceneId: source.id+ };++ if (drop) {+ return {+ category: 'scene_retention',+ title: `Rework the ${drop.label} beat in future ${surface}`,+ rationale: `${drop.label} lost ${Math.abs(drop.changePoints).toFixed(1)} audience percentage points across ${drop.pointCount} measured curve segments; its sharpest single decline was ${drop.largestDropPoints.toFixed(1)} points.`,+ evidence: {+ metric: 'audience_retention_curve',+ ...sourceIdentity,+ surface: snapshot.surface,+ scene: drop+ },+ proposedChange: {+ target: 'future_scripts',+ experiment: 'scene_retention',+ surface: snapshot.surface,+ sceneRole: this.slug(drop.label),+ action: /hook|intro/i.test(drop.label) ? 'shorten_and_front_load_value' : 'tighten_transition_and_pacing',+ autoEditPublishedContent: false,+ ...sourceIdentity+ },+ confidence: snapshot.confidence+ };+ }++ return {+ category: 'scene_retention',+ title: `Reuse the ${strong.label} pattern in future ${surface}`,+ rationale: `${strong.label} held viewers with ${(strong.averageWatchRatio * 100).toFixed(1)}% average absolute retention and ${(strong.averageRelativeRetention * 100).toFixed(1)}% relative retention across ${strong.pointCount} curve segments.`,+ evidence: {+ metric: 'audience_retention_curve',+ ...sourceIdentity,+ surface: snapshot.surface,+ scene: strong+ },+ proposedChange: {+ target: 'future_scripts',+ experiment: 'scene_retention',+ surface: snapshot.surface,+ sceneRole: this.slug(strong.label),+ action: 'reuse_structure_and_pacing',+ autoEditPublishedContent: false,+ ...sourceIdentity+ },+ confidence: snapshot.confidence+ };+ }++ confidenceFor(points, exposure = {}) {+ const views = this.number(exposure.views);+ if (points.length >= 80 && views >= 500) return 'high';+ if (points.length >= 40 && views >= 100) return 'medium';+ return 'low';+ }++ fingerprint(candidate) {+ const identity = {+ category: candidate.category,+ title: candidate.title,+ proposedChange: candidate.proposedChange+ };+ return crypto.createHash('sha256').update(JSON.stringify(identity)).digest('hex');+ }++ dropSeverity(scene) {+ return Math.abs(Math.min(0, scene.changePoints)) + scene.largestDropPoints + (scene.stopRate || 0);+ }++ average(values) {+ return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;+ }++ number(value) {+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : 0;+ }++ clamp(value, minimum, maximum) {+ return Math.max(minimum, Math.min(maximum, value));+ }++ round(value, precision = 4) {+ const factor = 10 ** precision;+ return Math.round(value * factor) / factor;+ }++ slug(value) {+ return String(value || 'scene').trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '') || 'scene';+ }+}++module.exports = { SceneRetentionEngine };