🎬 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 watermarked YouTube comment sync with refusal on failure
darkzOGxa887c54f023c
diff --git a/test.js b/test.jsindex b2b8610..1b10297 100644--- a/test.js+++ b/test.js@@ -1,6 +1,7 @@const { Database } = require('./database/db');const { Logger } = require('./utils/logger');const { CredentialManager } = require('./utils/credential-manager');+const { AudienceEngagementService } = require('./utils/audience-engagement-service');const chalk = require('chalk');const path = require('path');const { ProductionReadinessService } = require('./utils/production-readiness-service');@@ -50,7 +51,8 @@ class SystemTest {{ name: 'Audience Comment Store', test: () => this.testAudienceCommentStore() },{ name: 'Engagement Insight Store', test: () => this.testEngagementInsightStore() },{ name: 'Reply Draft Lifecycle Store', test: () => this.testReplyDraftStore() },- { name: 'YouTube Scope Detection', test: () => this.testYouTubeScopeDetection() }+ { name: 'YouTube Scope Detection', test: () => this.testYouTubeScopeDetection() },+ { name: 'Audience Comment Sync', test: () => this.testAudienceCommentSync() }];let passed = 0;@@ -2453,6 +2455,78 @@ class SystemTest {this.logger.info('Configuration test completed successfully');}++ async testAudienceCommentSync() {+ const db = new Database();+ await db.initialize();+ const videoId = `vid_sync_${Date.now()}`;+ const iso = offsetMinutes => new Date(Date.now() - offsetMinutes * 60000).toISOString();+ const thread = (id, publishedAt, replies = []) => ({+ id,+ snippet: {+ totalReplyCount: replies.length,+ topLevelComment: { id, snippet: {+ textOriginal: `Comment ${id}`, authorDisplayName: 'Viewer',+ authorChannelId: { value: 'UC_viewer' }, likeCount: 1, publishedAt, updatedAt: publishedAt+ } }+ },+ replies: { comments: replies }+ });+ try {+ const pages = [+ { items: [thread(`${videoId}_c2`, iso(5)), thread(`${videoId}_c1`, iso(60), [{+ id: `${videoId}_c1_r1`, snippet: {+ textOriginal: 'A reply', authorDisplayName: 'Owner',+ authorChannelId: { value: 'UC_channel_owner' }, likeCount: 0, publishedAt: iso(30), updatedAt: iso(30)+ }+ }]) ] }+ ];+ const service = new AudienceEngagementService(db, null, null, {+ listCommentThreads: async () => pages[0],+ getChannelId: async () => 'UC_channel_owner'+ });++ const first = await service.syncVideoComments(videoId, { title: 'Sync test' });+ if (first.fetched !== 3) throw new Error(`Expected 3 stored comments, got ${first.fetched}`);+ if (!first.insight?.newestCommentAt) throw new Error('Sync did not record the watermark');+ const ownerReply = await db.getAudienceComment(`${videoId}_c1_r1`);+ if (!ownerReply.isChannelOwner || ownerReply.parentCommentId !== `${videoId}_c1`) throw new Error('Reply mapping is wrong');++ const second = await service.syncVideoComments(videoId, {});+ if (second.fetched !== 0) throw new Error('Watermark must stop re-ingesting known comments');++ // Refusal policy: API failure stores nothing and rethrows+ const failing = new AudienceEngagementService(db, null, null, {+ listCommentThreads: async () => { throw new Error('quota exceeded'); },+ getChannelId: async () => 'UC_channel_owner'+ });+ let threw = false;+ try { await failing.syncVideoComments(`${videoId}_other`, {}); } catch (_error) { threw = true; }+ if (!threw) throw new Error('API failure must throw');+ if (await db.getEngagementInsight(`${videoId}_other`)) throw new Error('A failed sync must store nothing');++ // Disabled comments are not an error+ const disabledError = new Error('disabled');+ disabledError.errors = [{ reason: 'commentsDisabled' }];+ const disabledService = new AudienceEngagementService(db, null, null, {+ listCommentThreads: async () => { throw disabledError; },+ getChannelId: async () => 'UC_channel_owner'+ });+ const disabled = await disabledService.syncVideoComments(`${videoId}_disabled`, {});+ if (!disabled.disabled || disabled.fetched !== 0) throw new Error('commentsDisabled must be recorded, not thrown');++ // Taper+ if (service.isSyncDue(null, iso(0))) { /* never-synced is due */ } else throw new Error('Never-synced video must be due');+ const fresh = { lastSyncedAt: iso(60) };+ if (service.isSyncDue(fresh, iso(24 * 60))) throw new Error('A 1h-stale sync of a 1-day-old video is not due (4h taper)');+ if (!service.isSyncDue({ lastSyncedAt: iso(5 * 60) }, iso(24 * 60))) throw new Error('A 5h-stale sync of a 1-day-old video is due');+ if (service.isSyncDue({ lastSyncedAt: iso(13 * 60) }, iso(40 * 24 * 60))) throw new Error('Videos older than 30 days are never auto-due');+ } finally {+ await db.executeQuery("DELETE FROM audience_comments WHERE video_id LIKE ?", [`${videoId}%`]);+ await db.executeQuery("DELETE FROM engagement_insights WHERE video_id LIKE ?", [`${videoId}%`]);+ await db.close();+ }+ }}// Run tests if called directlydiff --git a/utils/audience-engagement-service.js b/utils/audience-engagement-service.jsnew file mode 100644index 0000000..9a9143e--- /dev/null+++ b/utils/audience-engagement-service.js@@ -0,0 +1,167 @@+const crypto = require('crypto');+const { Logger } = require('./logger');++const FORCE_SSL_SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl';+const COMMENT_FLAGS = ['question', 'request', 'praise', 'correction', 'spam', 'scam', 'toxic'];+const QUARANTINE_FLAGS = ['spam', 'scam', 'toxic'];+const THEME_KINDS = ['question', 'request', 'feedback', 'correction', 'praise'];++class AudienceEngagementService {+ constructor(db, credentials, aiTextService, options = {}) {+ this.db = db;+ this.credentials = credentials;+ this.aiTextService = aiTextService;+ this.logger = options.logger || new Logger('AudienceEngagement');+ this.maxCommentsPerSync = Number(options.maxCommentsPerSync || 500);+ this.maxCommentsPerAnalysis = Number(options.maxCommentsPerAnalysis || 200);+ this.maxDraftsPerRun = Number(options.maxDraftsPerRun || 10);+ this.dailyReplyCap = Number(options.dailyReplyCap || process.env.ENGAGEMENT_DAILY_REPLY_CAP || 50);+ this.listCommentThreads = options.listCommentThreads || (params => this.defaultListCommentThreads(params));+ this.insertComment = options.insertComment || (params => this.defaultInsertComment(params));+ this.getChannelId = options.getChannelId || (() => this.defaultGetChannelId());+ this.channelId = null;+ }++ async defaultListCommentThreads({ videoId, pageToken }) {+ const youtube = this.credentials.getYouTubeClient();+ const response = await youtube.commentThreads.list({+ part: ['snippet', 'replies'],+ videoId,+ order: 'time',+ maxResults: 100,+ ...(pageToken ? { pageToken } : {})+ });+ return response.data;+ }++ async defaultInsertComment({ parentId, text }) {+ const youtube = this.credentials.getYouTubeClient();+ const response = await youtube.comments.insert({+ part: ['snippet'],+ requestBody: { snippet: { parentId, textOriginal: text } }+ });+ return { id: response.data?.id };+ }++ async defaultGetChannelId() {+ const youtube = this.credentials.getYouTubeClient();+ const response = await youtube.channels.list({ part: ['id'], mine: true });+ return response.data?.items?.[0]?.id || null;+ }++ async resolveChannelId() {+ if (this.channelId) return this.channelId;+ try {+ this.channelId = await this.getChannelId();+ } catch (error) {+ this.logger.warn(`Channel id lookup failed; owner detection disabled: ${error.message}`);+ this.channelId = null;+ }+ return this.channelId;+ }++ permalink(videoId, commentId) {+ return `https://www.youtube.com/watch?v=${videoId}&lc=${commentId}`;+ }++ isSyncDue(insight, publishedAt, now = new Date()) {+ if (!insight?.lastSyncedAt) return true;+ const published = publishedAt ? new Date(publishedAt) : null;+ if (!published || Number.isNaN(published.getTime())) return false;+ const ageHours = (now - published) / 3600000;+ if (ageHours > 24 * 30) return false;+ const staleHours = (now - new Date(insight.lastSyncedAt)) / 3600000;+ if (ageHours <= 48) return staleHours >= 4;+ if (ageHours <= 24 * 7) return staleHours >= 12;+ return staleHours >= 24;+ }++ mapThread(item, videoId, channelId) {+ const top = item.snippet?.topLevelComment;+ const topSnippet = top?.snippet || {};+ const comments = [{+ commentId: top?.id || item.id,+ videoId,+ parentCommentId: null,+ authorName: topSnippet.authorDisplayName || null,+ authorChannelId: topSnippet.authorChannelId?.value || null,+ isChannelOwner: Boolean(channelId && topSnippet.authorChannelId?.value === channelId),+ text: topSnippet.textOriginal || topSnippet.textDisplay || '',+ likeCount: Number(topSnippet.likeCount || 0),+ replyCount: Number(item.snippet?.totalReplyCount || 0),+ publishedAt: topSnippet.publishedAt || null,+ updatedAtYouTube: topSnippet.updatedAt || null+ }];+ for (const reply of item.replies?.comments || []) {+ const snippet = reply.snippet || {};+ comments.push({+ commentId: reply.id,+ videoId,+ parentCommentId: top?.id || item.id,+ authorName: snippet.authorDisplayName || null,+ authorChannelId: snippet.authorChannelId?.value || null,+ isChannelOwner: Boolean(channelId && snippet.authorChannelId?.value === channelId),+ text: snippet.textOriginal || snippet.textDisplay || '',+ likeCount: Number(snippet.likeCount || 0),+ replyCount: 0,+ publishedAt: snippet.publishedAt || null,+ updatedAtYouTube: snippet.updatedAt || null+ });+ }+ return comments.filter(comment => comment.commentId && comment.text);+ }++ // Watermark is keyed on top-level publish time (order=time is newest-first);+ // new replies inside old threads are only picked up when their thread re-enters a page.+ async syncVideoComments(videoId, meta = {}) {+ const existing = await this.db.getEngagementInsight(videoId);+ const watermark = existing?.newestCommentAt ? new Date(existing.newestCommentAt) : null;+ const channelId = await this.resolveChannelId();+ let pageToken;+ let fetched = 0;+ let newest = watermark;+ let reachedWatermark = false;+ let disabled = false;++ try {+ do {+ const page = await this.listCommentThreads({ videoId, pageToken });+ for (const item of page.items || []) {+ const threadComments = this.mapThread(item, videoId, channelId);+ const topPublished = threadComments[0]?.publishedAt ? new Date(threadComments[0].publishedAt) : null;+ if (watermark && topPublished && topPublished <= watermark) {+ reachedWatermark = true;+ break;+ }+ for (const comment of threadComments) {+ await this.db.upsertAudienceComment(comment);+ fetched++;+ const published = comment.publishedAt ? new Date(comment.publishedAt) : null;+ if (published && (!newest || published > newest)) newest = published;+ }+ }+ pageToken = reachedWatermark ? null : page.nextPageToken || null;+ } while (pageToken && fetched < this.maxCommentsPerSync);+ } catch (error) {+ if (error?.errors?.[0]?.reason === 'commentsDisabled') {+ disabled = true;+ } else {+ // Refusal policy: a failed sync records nothing — there is no simulated comment.+ throw error;+ }+ }++ const counts = await this.db.countAudienceComments(videoId);+ const insight = await this.db.saveEngagementInsight({+ videoId,+ productionId: meta.productionId || existing?.productionId || null,+ title: meta.title || existing?.title || null,+ commentCount: counts.total,+ lastSyncedAt: new Date().toISOString(),+ newestCommentAt: newest ? newest.toISOString() : existing?.newestCommentAt || null+ });+ return { videoId, fetched, disabled, insight };+ }+}++module.exports = { AudienceEngagementService };