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 reply_drafts store with posted-row protection

darkzOGxfdbc5274551f
diff --git a/database/db.js b/database/db.js
index 5b9cde9..bf701e2 100644
--- a/database/db.js
+++ b/database/db.js
@@ -231,6 +231,20 @@ class Database {
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`,
+ `CREATE TABLE IF NOT EXISTS reply_drafts (
+ id TEXT PRIMARY KEY,
+ comment_id TEXT NOT NULL UNIQUE,
+ video_id TEXT NOT NULL,
+ draft_text TEXT NOT NULL,
+ edited_text TEXT,
+ status TEXT DEFAULT 'proposed',
+ rationale TEXT,
+ posted_comment_id TEXT,
+ posted_at TEXT,
+ failure_reason TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
// Keywords Performance
`CREATE TABLE IF NOT EXISTS keyword_performance (
@@ -2074,6 +2088,103 @@ class Database {
};
}
+ async saveReplyDraft(draft) {
+ const existing = await this.getRow('SELECT id, status FROM reply_drafts WHERE comment_id = ?', [draft.commentId]);
+ if (existing?.status === 'posted') {
+ const error = new Error('A posted reply cannot be replaced');
+ error.status = 409;
+ throw error;
+ }
+ const id = existing?.id || this.generateId('reply');
+ await this.executeQuery(
+ `INSERT INTO reply_drafts (id, comment_id, video_id, draft_text, rationale)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(comment_id) DO UPDATE SET
+ draft_text = excluded.draft_text,
+ rationale = excluded.rationale,
+ edited_text = NULL,
+ status = 'proposed',
+ posted_comment_id = NULL,
+ posted_at = NULL,
+ failure_reason = NULL,
+ updated_at = CURRENT_TIMESTAMP`,
+ [id, draft.commentId, draft.videoId, draft.draftText, draft.rationale || null]
+ );
+ return this.getReplyDraft(id);
+ }
+
+ async getReplyDraft(id) {
+ const row = await this.getRow('SELECT * FROM reply_drafts WHERE id = ?', [id]);
+ return this.parseReplyDraft(row);
+ }
+
+ async listReplyDrafts(options = {}) {
+ const conditions = [];
+ const params = [];
+ if (options.videoId) {
+ conditions.push('video_id = ?');
+ params.push(options.videoId);
+ }
+ if (options.status) {
+ conditions.push('status = ?');
+ params.push(options.status);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const limit = Math.max(1, Math.min(100, Number(options.limit || 50)));
+ const rows = await this.getAllRows(
+ `SELECT * FROM reply_drafts ${where} ORDER BY updated_at DESC LIMIT ?`,
+ [...params, limit]
+ );
+ return rows.map(row => this.parseReplyDraft(row));
+ }
+
+ async updateReplyDraft(id, changes = {}) {
+ const columns = {
+ editedText: 'edited_text',
+ status: 'status',
+ postedCommentId: 'posted_comment_id',
+ postedAt: 'posted_at',
+ failureReason: 'failure_reason'
+ };
+ const sets = [];
+ const params = [];
+ for (const [key, column] of Object.entries(columns)) {
+ if (key in changes) {
+ sets.push(`${column} = ?`);
+ params.push(changes[key]);
+ }
+ }
+ if (sets.length) {
+ await this.executeQuery(
+ `UPDATE reply_drafts SET ${sets.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
+ [...params, id]
+ );
+ }
+ return this.getReplyDraft(id);
+ }
+
+ async countReplyDraftsPostedSince(isoTime) {
+ const row = await this.getRow(
+ "SELECT COUNT(*) AS posted FROM reply_drafts WHERE status = 'posted' AND posted_at >= ?",
+ [isoTime]
+ );
+ return Number(row?.posted || 0);
+ }
+
+ parseReplyDraft(row) {
+ if (!row) return null;
+ return {
+ ...row,
+ commentId: row.comment_id,
+ videoId: row.video_id,
+ draftText: row.draft_text,
+ editedText: row.edited_text,
+ postedCommentId: row.posted_comment_id,
+ postedAt: row.posted_at,
+ failureReason: row.failure_reason
+ };
+ }
+
async getPublishedContentContext(youtubeId) {
const schedule = await this.getRow(
`SELECT production_id, published_at, title, metadata
diff --git a/test.js b/test.js
index 9dd504f..a4e01be 100644
--- a/test.js
+++ b/test.js
@@ -48,7 +48,8 @@ class SystemTest {
{ name: 'Agent Loading', test: () => this.testAgentLoading() },
{ name: 'Configuration Files', test: () => this.testConfiguration() },
{ name: 'Audience Comment Store', test: () => this.testAudienceCommentStore() },
- { name: 'Engagement Insight Store', test: () => this.testEngagementInsightStore() }
+ { name: 'Engagement Insight Store', test: () => this.testEngagementInsightStore() },
+ { name: 'Reply Draft Lifecycle Store', test: () => this.testReplyDraftStore() }
];
let passed = 0;
@@ -2293,6 +2294,46 @@ class SystemTest {
this.logger.info('Agent loading test completed successfully');
}
+ async testReplyDraftStore() {
+ const db = new Database();
+ await db.initialize();
+ const commentId = `rc_test_${Date.now()}`;
+ const videoId = `vid_reply_${Date.now()}`;
+ try {
+ const draft = await db.saveReplyDraft({ commentId, videoId, draftText: 'Thanks! The cache works per scene.', rationale: 'Direct question' });
+ if (!draft || draft.status !== 'proposed') throw new Error('saveReplyDraft did not create a proposed draft');
+
+ const edited = await db.updateReplyDraft(draft.id, { editedText: 'Thanks! Each scene caches separately.' });
+ if (edited.editedText !== 'Thanks! Each scene caches separately.') throw new Error('editedText was not persisted');
+
+ const replaced = await db.saveReplyDraft({ commentId, videoId, draftText: 'New draft text' });
+ if (replaced.id !== draft.id) throw new Error('Re-drafting must reuse the comment row');
+ if (replaced.editedText !== null || replaced.status !== 'proposed') throw new Error('Re-drafting must reset the lifecycle');
+
+ const postedAt = new Date().toISOString();
+ await db.updateReplyDraft(draft.id, { status: 'posted', postedCommentId: 'yt_reply_1', postedAt });
+ const posted = await db.getReplyDraft(draft.id);
+ if (posted.status !== 'posted' || posted.postedCommentId !== 'yt_reply_1') throw new Error('Posting evidence was not stored');
+
+ let blocked = false;
+ try {
+ await db.saveReplyDraft({ commentId, videoId, draftText: 'Should not overwrite' });
+ } catch (error) {
+ blocked = error.status === 409;
+ }
+ if (!blocked) throw new Error('A posted reply draft must never be replaced');
+
+ const postedCount = await db.countReplyDraftsPostedSince(new Date(Date.now() - 60000).toISOString());
+ if (postedCount < 1) throw new Error('countReplyDraftsPostedSince missed the posted draft');
+
+ const listed = await db.listReplyDrafts({ videoId, status: 'posted' });
+ if (listed.length !== 1) throw new Error('listReplyDrafts filter failed');
+ } finally {
+ await db.executeQuery('DELETE FROM reply_drafts WHERE video_id = ?', [videoId]);
+ await db.close();
+ }
+ }
+
async testEngagementInsightStore() {
const db = new Database();
await db.initialize();