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: approval-gated reply posting with scope gate and daily cap

darkzOGx2b0f8a80cd94
diff --git a/test.js b/test.js
index d951469..59b7c9d 100644
--- a/test.js
+++ b/test.js
@@ -55,7 +55,8 @@ class SystemTest {
{ name: 'Audience Comment Sync', test: () => this.testAudienceCommentSync() },
{ name: 'Audience Comment Analysis', test: () => this.testAudienceCommentAnalysis() },
{ name: 'Audience Idea Mining', test: () => this.testAudienceIdeaMining() },
- { name: 'Reply Drafting', test: () => this.testReplyDrafting() }
+ { name: 'Reply Drafting', test: () => this.testReplyDrafting() },
+ { name: 'Reply Approval and Posting', test: () => this.testReplyApprovalAndPosting() }
];
let passed = 0;
@@ -2709,6 +2710,82 @@ class SystemTest {
await db.close();
}
}
+
+ async testReplyApprovalAndPosting() {
+ const db = new Database();
+ await db.initialize();
+ const videoId = `vid_post_${Date.now()}`;
+ const commentId = `${videoId}_target`;
+ const scopedCredentials = { hasYouTubeScope: scope => scope === 'https://www.googleapis.com/auth/youtube.force-ssl' };
+ try {
+ await db.upsertAudienceComment({ commentId, videoId, text: 'Question?', publishedAt: new Date().toISOString() });
+ const makeDraft = () => db.saveReplyDraft({ commentId, videoId, draftText: 'Answer text' });
+
+ let draft = await makeDraft();
+ const posts = [];
+ const service = new AudienceEngagementService(db, scopedCredentials, null, {
+ insertComment: async ({ parentId, text }) => { posts.push({ parentId, text }); return { id: 'yt_posted_1' }; }
+ });
+
+ let code = null;
+ try { await service.approveReplyDraft(draft.id, {}); } catch (error) { code = error.code; }
+ if (code !== 'REPLY_APPROVAL_REQUIRED') throw new Error('Approval must require confirmed: true');
+
+ const unscoped = new AudienceEngagementService(db, { hasYouTubeScope: () => false }, null, {});
+ code = null;
+ try { await unscoped.approveReplyDraft(draft.id, { confirmed: true }); } catch (error) { code = error.code; }
+ if (code !== 'REPLY_SCOPE_REQUIRED') throw new Error('Missing force-ssl scope must block posting');
+ const gate = unscoped.postingEnabled();
+ if (gate.enabled || gate.reason !== 'missing_scope') {
+ throw new Error('postingEnabled must report missing_scope');
+ }
+
+ const posted = await service.approveReplyDraft(draft.id, { confirmed: true, editedText: 'Edited answer' });
+ if (posted.status !== 'posted' || posted.postedCommentId !== 'yt_posted_1') throw new Error('Posting evidence missing');
+ if (posts[0].parentId !== commentId || posts[0].text !== 'Edited answer') throw new Error('The edited text must be what posts');
+ if (!(await db.getAudienceComment(commentId)).repliedByAgent) throw new Error('Source comment must be marked replied');
+
+ let status = null;
+ try { await service.approveReplyDraft(draft.id, { confirmed: true }); } catch (error) { status = error.status; }
+ if (status !== 409) throw new Error('A posted draft must not post twice');
+
+ // Failure path: failed + reason, manual retry allowed
+ const failingComment = `${videoId}_fail`;
+ await db.upsertAudienceComment({ commentId: failingComment, videoId, text: 'Other?', publishedAt: new Date().toISOString() });
+ const failDraft = await db.saveReplyDraft({ commentId: failingComment, videoId, draftText: 'Will fail' });
+ const failing = new AudienceEngagementService(db, scopedCredentials, null, {
+ insertComment: async () => { throw new Error('commentThreadNotFound'); }
+ });
+ status = null;
+ try { await failing.approveReplyDraft(failDraft.id, { confirmed: true }); } catch (error) { status = error.status; }
+ if (status !== 502) throw new Error('A failed post must throw 502');
+ const failed = await db.getReplyDraft(failDraft.id);
+ if (failed.status !== 'failed' || !failed.failureReason.includes('commentThreadNotFound')) throw new Error('Failure evidence missing');
+
+ // Daily cap
+ const capped = new AudienceEngagementService(db, scopedCredentials, null, { dailyReplyCap: 1, insertComment: async () => ({ id: 'x' }) });
+ status = null;
+ try { await capped.approveReplyDraft(failDraft.id, { confirmed: true }); } catch (error) { status = error.status; }
+ if (status !== 429) throw new Error('The daily reply cap must block further posts');
+
+ // updateReplyDraft rules
+ const edited = await service.updateReplyDraft(failDraft.id, { editedText: 'Retry text' });
+ if (edited.status !== 'proposed' || edited.editedText !== 'Retry text') throw new Error('Editing must re-open a failed draft');
+ const discarded = await service.updateReplyDraft(failDraft.id, { discard: true });
+ if (discarded.status !== 'discarded') throw new Error('Discard failed');
+
+ // Summary
+ const summary = await service.getSummary();
+ if (summary.postedToday < 1) throw new Error('getSummary missed postedToday');
+ if (summary.postingEnabled !== true) throw new Error('getSummary posting flag is wrong');
+ if (!summary.evidencePolicy.includes('operator approval')) throw new Error('evidencePolicy text missing');
+ } finally {
+ await db.executeQuery('DELETE FROM audience_comments WHERE video_id = ?', [videoId]);
+ await db.executeQuery('DELETE FROM reply_drafts WHERE video_id = ?', [videoId]);
+ await db.executeQuery('DELETE FROM engagement_insights WHERE video_id = ?', [videoId]);
+ await db.close();
+ }
+ }
}
// Run tests if called directly
diff --git a/utils/audience-engagement-service.js b/utils/audience-engagement-service.js
index 53558e5..e53fe24 100644
--- a/utils/audience-engagement-service.js
+++ b/utils/audience-engagement-service.js
@@ -1,7 +1,6 @@
const crypto = require('crypto');
const { Logger } = require('./logger');
-// eslint-disable-next-line no-unused-vars -- consumed by postingEnabled() in the reply-posting task, which removes this directive
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'];
@@ -438,6 +437,127 @@ Comments: ${JSON.stringify(payload)}`;
}
return drafts;
}
+
+ postingEnabled() {
+ if (!this.credentials?.hasYouTubeScope) return { enabled: false, reason: 'credentials_unavailable' };
+ if (!this.credentials.hasYouTubeScope(FORCE_SSL_SCOPE)) return { enabled: false, reason: 'missing_scope' };
+ return { enabled: true, reason: null };
+ }
+
+ async requireDraft(draftId) {
+ const draft = await this.db.getReplyDraft(draftId);
+ if (!draft) {
+ const error = new Error('Reply draft not found');
+ error.status = 404;
+ throw error;
+ }
+ return draft;
+ }
+
+ async updateReplyDraft(draftId, changes = {}) {
+ const draft = await this.requireDraft(draftId);
+ if (draft.status === 'posted') {
+ const error = new Error('A posted reply cannot be changed');
+ error.status = 409;
+ throw error;
+ }
+ if (changes.discard === true) {
+ return this.db.updateReplyDraft(draftId, { status: 'discarded' });
+ }
+ if (typeof changes.editedText === 'string') {
+ const text = changes.editedText.trim().slice(0, 1000);
+ if (!text) {
+ const error = new Error('Reply text cannot be empty');
+ error.status = 400;
+ throw error;
+ }
+ return this.db.updateReplyDraft(draftId, { editedText: text, status: 'proposed', failureReason: null });
+ }
+ const error = new Error('Nothing to update');
+ error.status = 400;
+ throw error;
+ }
+
+ async approveReplyDraft(draftId, input = {}) {
+ if (input.confirmed !== true) {
+ const error = new Error('Confirm the reply text before posting to YouTube');
+ error.status = 409;
+ error.code = 'REPLY_APPROVAL_REQUIRED';
+ throw error;
+ }
+ let draft = await this.requireDraft(draftId);
+ if (draft.status === 'posted') {
+ const error = new Error('This reply was already posted');
+ error.status = 409;
+ throw error;
+ }
+ if (draft.status === 'discarded') {
+ const error = new Error('Edit the discarded draft to restore it before approval');
+ error.status = 409;
+ throw error;
+ }
+ const posting = this.postingEnabled();
+ if (!posting.enabled) {
+ const error = new Error('Posting requires re-authorizing YouTube with the comment permission. Run npm run walkthrough to re-connect.');
+ error.status = 409;
+ error.code = 'REPLY_SCOPE_REQUIRED';
+ throw error;
+ }
+ const since = new Date(Date.now() - 86400000).toISOString();
+ if (await this.db.countReplyDraftsPostedSince(since) >= this.dailyReplyCap) {
+ const error = new Error(`The daily reply cap (${this.dailyReplyCap}) was reached; try again tomorrow or raise ENGAGEMENT_DAILY_REPLY_CAP`);
+ error.status = 429;
+ throw error;
+ }
+ if (typeof input.editedText === 'string' && input.editedText.trim()) {
+ draft = await this.db.updateReplyDraft(draftId, { editedText: input.editedText.trim().slice(0, 1000) });
+ }
+ const text = (draft.editedText || draft.draftText || '').trim();
+ try {
+ const posted = await this.insertComment({ parentId: draft.commentId, text });
+ if (!posted?.id) throw new Error('YouTube did not return a comment id for the posted reply');
+ await this.db.markAudienceCommentReplied(draft.commentId);
+ return await this.db.updateReplyDraft(draftId, {
+ status: 'posted',
+ postedCommentId: posted.id,
+ postedAt: new Date().toISOString(),
+ failureReason: null
+ });
+ } catch (error) {
+ await this.db.updateReplyDraft(draftId, {
+ status: 'failed',
+ failureReason: String(error.message || 'Posting failed').slice(0, 300)
+ });
+ const wrapped = new Error(`The reply could not be posted: ${error.message}`);
+ wrapped.status = 502;
+ throw wrapped;
+ }
+ }
+
+ async getSummary() {
+ const [insights, pendingDrafts, pendingRecommendations] = await Promise.all([
+ this.db.listEngagementInsights({ limit: 12 }),
+ this.db.listReplyDrafts({ status: 'proposed', limit: 100 }),
+ this.db.listLearningRecommendations({ status: 'pending', limit: 100 })
+ ]);
+ const since = new Date(Date.now() - 86400000).toISOString();
+ const postedToday = await this.db.countReplyDraftsPostedSince(since);
+ const posting = this.postingEnabled();
+ return {
+ videosTracked: insights.length,
+ pendingDrafts: pendingDrafts.length,
+ postedToday,
+ needsAttentionCount: insights.reduce((sum, insight) => sum + (insight.attentionFlags?.length || 0), 0),
+ pendingAudienceIdeas: pendingRecommendations.filter(item => item.category === 'audience_demand').length,
+ postingEnabled: posting.enabled,
+ postingDisabledReason: posting.reason,
+ insights,
+ recentThemes: insights
+ .flatMap(insight => (insight.themes || []).slice(0, 3).map(theme => ({ ...theme, videoId: insight.videoId, videoTitle: insight.title })))
+ .slice(0, 8),
+ evidencePolicy: 'Comments are fetched read-only from YouTube. Replies post only after operator approval, and fallback analysis never proposes drafts or ideas.'
+ };
+ }
}
module.exports = { AudienceEngagementService };