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 audience_comments store for the engagement studio

darkzOGx796a014028d7
diff --git a/database/db.js b/database/db.js
index c27742c..d66d74c 100644
--- a/database/db.js
+++ b/database/db.js
@@ -194,7 +194,27 @@ class Database {
measured_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(video_id, measurement_window)
)`,
-
+
+ `CREATE TABLE IF NOT EXISTS audience_comments (
+ id TEXT PRIMARY KEY,
+ comment_id TEXT NOT NULL UNIQUE,
+ video_id TEXT NOT NULL,
+ parent_comment_id TEXT,
+ author_name TEXT,
+ author_channel_id TEXT,
+ is_channel_owner INTEGER DEFAULT 0,
+ text TEXT NOT NULL,
+ like_count INTEGER DEFAULT 0,
+ reply_count INTEGER DEFAULT 0,
+ published_at TEXT,
+ updated_at_youtube TEXT,
+ flags TEXT NOT NULL DEFAULT '[]',
+ analysis_state TEXT DEFAULT 'pending',
+ replied_by_agent INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
// Keywords Performance
`CREATE TABLE IF NOT EXISTS keyword_performance (
id TEXT PRIMARY KEY,
@@ -1858,6 +1878,111 @@ class Database {
};
}
+ async upsertAudienceComment(comment) {
+ const existing = await this.getRow(
+ 'SELECT id FROM audience_comments WHERE comment_id = ?',
+ [comment.commentId]
+ );
+ const id = existing?.id || this.generateId('comment');
+ await this.executeQuery(
+ `INSERT INTO audience_comments (
+ id, comment_id, video_id, parent_comment_id, author_name, author_channel_id,
+ is_channel_owner, text, like_count, reply_count, published_at, updated_at_youtube
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(comment_id) DO UPDATE SET
+ text = excluded.text,
+ like_count = excluded.like_count,
+ reply_count = excluded.reply_count,
+ updated_at_youtube = excluded.updated_at_youtube,
+ updated_at = CURRENT_TIMESTAMP`,
+ [
+ id,
+ comment.commentId,
+ comment.videoId,
+ comment.parentCommentId || null,
+ comment.authorName || null,
+ comment.authorChannelId || null,
+ comment.isChannelOwner ? 1 : 0,
+ comment.text,
+ Number(comment.likeCount || 0),
+ Number(comment.replyCount || 0),
+ comment.publishedAt || null,
+ comment.updatedAtYouTube || null
+ ]
+ );
+ return this.getAudienceComment(comment.commentId);
+ }
+
+ async getAudienceComment(commentId) {
+ const row = await this.getRow('SELECT * FROM audience_comments WHERE comment_id = ?', [commentId]);
+ return this.parseAudienceComment(row);
+ }
+
+ async listAudienceComments(options = {}) {
+ const conditions = ['video_id = ?'];
+ const params = [options.videoId];
+ if (options.topLevelOnly) conditions.push('parent_comment_id IS NULL');
+ if (options.analysisState) {
+ conditions.push('analysis_state = ?');
+ params.push(options.analysisState);
+ }
+ const limit = Math.max(1, Math.min(500, Number(options.limit || 200)));
+ const rows = await this.getAllRows(
+ `SELECT * FROM audience_comments WHERE ${conditions.join(' AND ')}
+ ORDER BY like_count DESC, published_at DESC LIMIT ?`,
+ [...params, limit]
+ );
+ return rows.map(row => this.parseAudienceComment(row));
+ }
+
+ async countAudienceComments(videoId) {
+ const row = await this.getRow(
+ `SELECT COUNT(*) AS total,
+ SUM(CASE WHEN parent_comment_id IS NULL THEN 1 ELSE 0 END) AS top_level
+ FROM audience_comments WHERE video_id = ?`,
+ [videoId]
+ );
+ return { total: Number(row?.total || 0), topLevel: Number(row?.top_level || 0) };
+ }
+
+ async setAudienceCommentAnalysis(commentId, flags) {
+ await this.executeQuery(
+ `UPDATE audience_comments
+ SET flags = ?, analysis_state = 'analyzed', updated_at = CURRENT_TIMESTAMP
+ WHERE comment_id = ?`,
+ [JSON.stringify(flags || []), commentId]
+ );
+ return this.getAudienceComment(commentId);
+ }
+
+ async markAudienceCommentReplied(commentId) {
+ await this.executeQuery(
+ `UPDATE audience_comments SET replied_by_agent = 1, updated_at = CURRENT_TIMESTAMP WHERE comment_id = ?`,
+ [commentId]
+ );
+ return this.getAudienceComment(commentId);
+ }
+
+ parseAudienceComment(row) {
+ if (!row) return null;
+ return {
+ ...row,
+ commentId: row.comment_id,
+ videoId: row.video_id,
+ parentCommentId: row.parent_comment_id,
+ authorName: row.author_name,
+ authorChannelId: row.author_channel_id,
+ isChannelOwner: Boolean(row.is_channel_owner),
+ likeCount: Number(row.like_count || 0),
+ replyCount: Number(row.reply_count || 0),
+ publishedAt: row.published_at,
+ updatedAtYouTube: row.updated_at_youtube,
+ flags: JSON.parse(row.flags || '[]'),
+ analysisState: row.analysis_state,
+ repliedByAgent: Boolean(row.replied_by_agent)
+ };
+ }
+
async getPublishedContentContext(youtubeId) {
const schedule = await this.getRow(
`SELECT production_id, published_at, title, metadata
diff --git a/test.js b/test.js
index 73e4b3a..ec242d8 100644
--- a/test.js
+++ b/test.js
@@ -46,7 +46,8 @@ class SystemTest {
{ name: 'Logger System', test: () => this.testLogger() },
{ name: 'Directory Structure', test: () => this.testDirectories() },
{ name: 'Agent Loading', test: () => this.testAgentLoading() },
- { name: 'Configuration Files', test: () => this.testConfiguration() }
+ { name: 'Configuration Files', test: () => this.testConfiguration() },
+ { name: 'Audience Comment Store', test: () => this.testAudienceCommentStore() }
];
let passed = 0;
@@ -2291,6 +2292,45 @@ class SystemTest {
this.logger.info('Agent loading test completed successfully');
}
+ async testAudienceCommentStore() {
+ const db = new Database();
+ await db.initialize();
+ const commentId = `ac_test_${Date.now()}`;
+ const videoId = `vid_test_${Date.now()}`;
+ try {
+ const first = await db.upsertAudienceComment({
+ commentId, videoId,
+ text: 'How does the render cache work?',
+ authorName: 'Viewer One', authorChannelId: 'UC_viewer_1',
+ likeCount: 3, replyCount: 0,
+ publishedAt: new Date().toISOString()
+ });
+ if (!first || first.commentId !== commentId) throw new Error('upsertAudienceComment did not store the comment');
+ if (first.isChannelOwner !== false || first.repliedByAgent !== false) throw new Error('Boolean parsing is wrong');
+
+ const second = await db.upsertAudienceComment({
+ commentId, videoId, text: 'How does the render cache work? (edited)', likeCount: 5
+ });
+ if (second.id !== first.id) throw new Error('Re-syncing the same comment must upsert, not duplicate');
+ if (second.likeCount !== 5 || !second.text.includes('(edited)')) throw new Error('Upsert did not refresh mutable fields');
+
+ const flagged = await db.setAudienceCommentAnalysis(commentId, ['question']);
+ if (flagged.analysisState !== 'analyzed' || !flagged.flags.includes('question')) throw new Error('Analysis flags were not persisted');
+
+ const listed = await db.listAudienceComments({ videoId, topLevelOnly: true });
+ if (listed.length !== 1) throw new Error('listAudienceComments missed the top-level comment');
+
+ const counts = await db.countAudienceComments(videoId);
+ if (counts.total !== 1 || counts.topLevel !== 1) throw new Error('countAudienceComments returned wrong counts');
+
+ const replied = await db.markAudienceCommentReplied(commentId);
+ if (!replied.repliedByAgent) throw new Error('markAudienceCommentReplied did not persist');
+ } finally {
+ await db.executeQuery('DELETE FROM audience_comments WHERE video_id = ?', [videoId]);
+ await db.close();
+ }
+ }
+
async testConfiguration() {
const fs = require('fs').promises;