Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(automations): give a scheduled Instagram post its own comment automation

spacesdrive5edea4ae5b15
diff --git a/DECISIONS.md b/DECISIONS.md
index e4bebbc..b3fefe1 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1162,3 +1162,23 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
- The CPU cost of copying 8 MiB per chunk on the Free plan is unmeasured; the paid plan is the fallback.
- A session lost after the last byte goes to a person (`needs_review`) instead of a retry, trading automation for never publishing twice.
- Changing `TOKEN_ENCRYPTION_KEY` signs everyone out of YouTube.
+
+---
+
+## ADR-054: A scheduled post carries its comment automation, and the Worker makes the rule once the post is published
+
+**Date:** 2026-11-05
+**Status:** Accepted
+
+**Decision:** A scheduled Instagram post may store an `automation` (`{ replyText, publicReplyTexts }`) in its `data`. After each publish run and each reconcile run, `postAutomation.attachPublished` lists published posts whose automation has no rule yet and creates, through `automations.createRule` for the post's owner, an enabled rule that answers any comment on that one post. The post then records `automationRuleId`, or `automationError` when the rule cannot be made (#176).
+
+**Context:** A rule for one post needs the post's Instagram id, which only exists after publishing. Posts are scheduled weeks ahead, each with its own message, so making each rule by hand means coming back for every post.
+
+**Alternatives considered:**
+- Making the rule in the publisher. Both schedulers would need it, and the GitHub Actions script has no dependencies and no access to the rule checks or the webhook subscription.
+- Matching comments to scheduled posts in the webhook. It would add a lookup to every comment for a feature most comments never use.
+- A new column for the automation. The post's other content already lives in `data` and changes through the merge functions; no migration was needed.
+
+**Trade-offs:**
+- A post the GitHub Actions scheduler publishes gets its rule at the next Worker publish or reconcile run, up to about ten minutes later; comments in that gap are not answered.
+- The rule is an ordinary rule afterwards: editing the scheduled post does not change it, and it is edited or paused on the Instagram automation page.
diff --git a/backend/container.ts b/backend/container.ts
index 1a69f6d..b5bd8e6 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -41,6 +41,7 @@ import { createAutomationProcessor } from './services/automationProcessor.ts';
import { createAutomationFollowupProcessor } from './services/automationFollowupProcessor.ts';
import { createAutomationPublicReplyProcessor } from './services/automationPublicReplyProcessor.ts';
import { createAutomationReconciler } from './services/automationReconciler.ts';
+import { createPostAutomationService } from './services/postAutomationService.ts';
import { createRetentionService } from './services/retentionService.ts';
import { createHealthService } from './services/healthService.ts';
import { createMcpAccessService } from './services/mcpAccessService.ts';
@@ -66,6 +67,7 @@ import type { AutomationProcessor } from './services/automationProcessor.ts';
import type { AutomationFollowupProcessor } from './services/automationFollowupProcessor.ts';
import type { AutomationPublicReplyProcessor } from './services/automationPublicReplyProcessor.ts';
import type { AutomationReconciler } from './services/automationReconciler.ts';
+import type { PostAutomationService } from './services/postAutomationService.ts';
import type { RetentionService } from './services/retentionService.ts';
import type { McpAccessService, McpPrincipal } from './services/mcpAccessService.ts';
import type { McpService } from './services/mcpService.ts';
@@ -107,6 +109,7 @@ export interface Services {
automationFollowups: AutomationFollowupProcessor;
automationPublicReplies: AutomationPublicReplyProcessor;
automationReconciler: AutomationReconciler;
+ postAutomation: PostAutomationService;
retention: RetentionService;
health: HealthService;
mcpAccess: McpAccessService;
@@ -137,6 +140,7 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
const youtubeConnect = createYouTubeConnectService({ connections: youtubeConnections, uploads: youtubeUploadRows, accounts, audit, config, context });
// counters on the fail-fast client the rate limits use: without Redis nothing is metered
const youtubeQuota = createYouTubeQuotaService({ quota: createYouTubeQuotaRepository(clients.rateLimitRedis) });
+ const automations = createAutomationService({ accounts, rules, comments, followups, publicReplies, automationAccounts, audit, automation, context });
const services: Services = {
accounts: createAccountService({ accounts, cache, audit, config, context, youtubeQuota, youtubePublishing: youtubeConnect }),
youtubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context, youtubeQuota }),
@@ -154,12 +158,13 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
youtubeRunner: createYouTubeUploadRunner({ uploads: youtubeUploadRows, connections: youtubeConnections, connect: youtubeConnect, ledger: createYouTubeQuotaLedgerRepository(clients.supabase), context }),
instagramConnect: createInstagramConnectService({ accounts, audit, config, context }),
authEmail: createAuthEmailService({ quota: createEmailQuotaRepository(clients.rateLimitRedis), config, context }),
- automations: createAutomationService({ accounts, rules, comments, followups, publicReplies, automationAccounts, audit, automation, context }),
+ automations,
automationWebhook: createAutomationWebhookService({ rules, comments, followups, automation, context }),
automationProcessor: createAutomationProcessor({ comments, automation, context }),
automationFollowups: createAutomationFollowupProcessor({ followups, automation, context }),
automationPublicReplies: createAutomationPublicReplyProcessor({ publicReplies, automation, context }),
automationReconciler: createAutomationReconciler({ comments, publicReplies, context }),
+ postAutomation: createPostAutomationService({ posts, rules, automations, context }),
retention: createRetentionService({ comments, audit, context }),
health: createHealthService({ health: createHealthRepository(clients.supabase) }),
mcpAccess: createMcpAccessService({ tokens: mcpTokens, grants: mcpGrants, audit, context }),
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.ts
index afa0991..ad861df 100644
--- a/backend/jobs/scheduled.ts
+++ b/backend/jobs/scheduled.ts
@@ -68,6 +68,18 @@ async function dispatch(services: Services, context: RequestContext): Promise<vo
}
}
+// each post's rule costs about ten subrequests, so a run makes a few and leaves the rest of its budget to its own work
+const POST_AUTOMATIONS_PER_RUN = 3;
+
+// a newly published post gets its comment rule in the same run, or the reconcile run when another scheduler published it
+async function attachPostAutomations(services: Services, context: RequestContext): Promise<void> {
+ try {
+ await services.postAutomation.attachPublished(POST_AUTOMATIONS_PER_RUN);
+ } catch (err) {
+ context.log.error('post automation run failed', errorFields(err));
+ }
+}
+
// a failed daily step is logged and the next one still runs, so a token refresh problem never stops the retention purge
export async function dailyStep(context: RequestContext, step: string, work: () => Promise<unknown>): Promise<void> {
try {
@@ -96,11 +108,13 @@ export async function runScheduledJob(cron: string, env: Env, scheduledTime = Da
} else if (plan === 'publish') {
const run = await services.scheduledPublisher.publishDue();
context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });
+ await attachPostAutomations(services, context);
} else if (plan === 'youtube') {
const run = await services.youtubeRunner.run({ subrequests: FREE_PLAN_SUBREQUESTS, timeBudgetMs: YOUTUBE_RUN_MS });
if (run.jobId) context.log.info('youtube upload run', { jobId: run.jobId, state: run.state, chunks: run.chunks, subrequests: run.subrequests });
} else if (plan === 'reconcile') {
await services.automationReconciler.run();
+ await attachPostAutomations(services, context);
} else if (plan === 'daily') {
await dailyStep(context, 'token refresh', () => services.tokenRefresh.refreshExpiringInstagramTokens());
await dailyStep(context, 'retention purge', () => services.retention.purge(Date.now(), { commentBatches: RETENTION_BATCHES }));
diff --git a/backend/mcp/tools/scheduledPostTools.ts b/backend/mcp/tools/scheduledPostTools.ts
index 2fc9bde..45e6d66 100644
--- a/backend/mcp/tools/scheduledPostTools.ts
+++ b/backend/mcp/tools/scheduledPostTools.ts
@@ -20,6 +20,10 @@ function summary(post: ScheduledPost) {
caption: post.caption ?? '',
publishedAt: post.publishedAt ?? null,
error: post.error ?? null,
+ // the rule is made once the post is published; ruleCreated and automationError say how that went
+ automation: post.automation
+ ? { ...post.automation, ruleCreated: Boolean(post.automationRuleId), error: post.automationError ?? null }
+ : null,
};
}
@@ -42,6 +46,8 @@ function describeFields(fields: Partial<ScheduledPostRequest>): string {
fields.altText !== undefined && `Alt text: "${fields.altText}".`,
fields.locationId && `Location id: ${fields.locationId}.`,
fields.shareToFeed !== undefined && `Share to feed: ${fields.shareToFeed ? 'yes' : 'no'}.`,
+ fields.automation && `Once published, anyone who comments gets this private reply: "${fields.automation.replyText}".`,
+ fields.automation?.publicReplyTexts.length && `And one of these public replies under their comment: ${fields.automation.publicReplyTexts.map(text => `"${text}"`).join(', ')}.`,
];
return parts.filter(Boolean).join(' ');
}
@@ -89,19 +95,29 @@ export const getScheduledPost = defineTool<{ postId: string }>({
export const scheduleInstagramPost = defineTool<ScheduledPostRequest>({
name: 'schedule_instagram_post',
title: 'Schedule an Instagram post',
- description: 'Schedules an image, video, reel or story on a connected Instagram account. Twiligent publishes it at scheduledAt. The media must already be at a public https URL, such as one returned by the media tools. Asks for a confirmation first, because the post goes public. Scheduling the same media for the same account and time twice returns the existing post.',
+ description: 'Schedules an image, video, reel or story on a connected Instagram account. Twiligent publishes it at scheduledAt, and with automation it then answers every comment on the post. The media must already be at a public https URL, such as one returned by the media tools. Asks for a confirmation first, because the post goes public. Scheduling the same media for the same account and time twice returns the existing post.',
inputSchema: withConfirmation(objectSchema({
accountId: idProperty('Instagram account'),
mediaUrl: { type: 'string', format: 'uri', description: 'Public https URL of the image or video' },
mediaType: { type: 'string', enum: ['IMAGE', 'VIDEO', 'REELS', 'STORIES'], description: 'What kind of post; IMAGE when left out' },
...postFields,
+ automation: {
+ type: 'object',
+ description: 'Answer every comment on this post once it is published: a rule for this post is made and turned on then',
+ properties: {
+ replyText: { type: 'string', maxLength: 1000, description: 'The private reply sent to each person who comments, up to 1000 bytes' },
+ publicReplyTexts: { type: 'array', items: { type: 'string', maxLength: 300 }, maxItems: 5, description: 'Replies posted under the comment, one picked per comment; leave out for none' },
+ },
+ required: ['replyText'],
+ additionalProperties: false,
+ },
}, ['accountId', 'mediaUrl', 'scheduledAt'])),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
permission: 'write',
needsConfirmation: () => true,
describe: input => `Publish a ${input.mediaType ?? 'IMAGE'} post on Instagram account ${input.accountId}. ${describeFields(input)}`,
parse(args) {
- refuseUnlisted(args, ['accountId', 'mediaUrl', 'mediaType', ...Object.keys(postFields)]);
+ refuseUnlisted(args, ['accountId', 'mediaUrl', 'mediaType', 'automation', ...Object.keys(postFields)]);
const request = parseScheduledPost(args);
if (request.mediaType === 'CAROUSEL') throw new ValidationError('Carousels can be scheduled from the Instagram publishing page; this tool takes one image or video.');
return request;
diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.ts
index e128069..0463205 100644
--- a/backend/repositories/scheduledPostRepository.ts
+++ b/backend/repositories/scheduledPostRepository.ts
@@ -12,6 +12,12 @@ interface ScheduledPostRow {
data: Partial<ScheduledPost> | null;
}
+// a published post whose comment automation has no rule yet, with the person it belongs to
+export interface PostAwaitingAutomation {
+ post: ScheduledPost;
+ userId: string;
+}
+
export interface DeleteAllResult {
deleted: number;
kept: number;
@@ -31,12 +37,13 @@ function toPost(row: ScheduledPostRow): ScheduledPost {
};
}
-// methods named ...ForUser filter by the verified user id; listDue, listStale, claim and updateById serve the schedulers across all users
+// methods named ...ForUser filter by the verified user id; listDue, listStale, listAwaitingAutomation, claim and updateById serve the schedulers across all users
export interface ScheduledPostRepository {
listForUser(userId: string): Promise<ScheduledPost[]>;
findForUser(id: string, userId: string): Promise<ScheduledPost | null>;
listDue(): Promise<ScheduledPost[]>;
listStale(claimedBefore: string): Promise<ScheduledPost[]>;
+ listAwaitingAutomation(limit: number): Promise<PostAwaitingAutomation[]>;
claim(post: ScheduledPost): Promise<ScheduledPost | null>;
create(post: ScheduledPost, userId: string): Promise<void>;
updatePendingForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<boolean>;
@@ -98,6 +105,20 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPost
return found.map(toPost);
},
+ // oldest first, so a backlog clears in order; a post whose rule could not be made keeps its error and is not tried again
+ async listAwaitingAutomation(limit) {
+ const found = await rows<ScheduledPostRow & { user_id: string }>('scheduledPosts.listAwaitingAutomation', () => db
+ .from('scheduled_posts')
+ .select(`${COLUMNS}, user_id`)
+ .eq('status', 'published')
+ .not('data->automation', 'is', null)
+ .is('data->automationRuleId', null)
+ .is('data->automationError', null)
+ .order('scheduled_at', { ascending: true })
+ .limit(limit));
+ return found.map(row => ({ post: toPost(row), userId: row.user_id }));
+ },
+
// matches only the post as it was listed (pending, or the same expired claim) with the same attempts; null means another run won
async claim(post) {
const claimed = await rows<ScheduledPostRow>('scheduledPosts.claim', () => {
diff --git a/backend/services/postAutomationService.ts b/backend/services/postAutomationService.ts
new file mode 100644
index 0000000..163900f
--- /dev/null
+++ b/backend/services/postAutomationService.ts
@@ -0,0 +1,94 @@
+import { AppError, DatabaseError, UpstreamError } from '../lib/errors.ts';
+import { errorFields } from '../lib/logger.ts';
+import type { AutomationService } from './automationService.ts';
+import type { AutomationRuleRepository } from '../repositories/automationRuleRepository.ts';
+import type { PostAwaitingAutomation, ScheduledPostRepository } from '../repositories/scheduledPostRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { ScheduledPost } from '../../shared/types/domain.ts';
+
+export interface PostAutomationDeps {
+ posts: ScheduledPostRepository;
+ rules: AutomationRuleRepository;
+ automations: Pick<AutomationService, 'createRule'>;
+ context: RequestContext;
+}
+
+export interface PostAutomationRun {
+ created: number;
+ failed: number;
+}
+
+export interface PostAutomationService {
+ // turns the automation of each newly published post into a rule that answers any comment on that post
+ attachPublished(limit: number): Promise<PostAutomationRun>;
+}
+
+const MAX_RULE_NAME = 80;
+const NO_MEDIA_ID = 'The post was published without an Instagram post id, so no comment rule could be made for it.';
+
+// the rule's name says which post it answers, so the Instagram automation page lists it beside hand-made rules
+export function postRuleName(post: ScheduledPost): string {
+ const firstLine = (post.caption ?? '').split('\n').map(line => line.trim()).find(Boolean) ?? '';
+ const name = `Post ${post.scheduledAt.slice(0, 10)}${firstLine ? `: ${firstLine}` : ''}`;
+ return name.length > MAX_RULE_NAME ? `${name.slice(0, MAX_RULE_NAME - 3).trimEnd()}...` : name;
+}
+
+// a database or Instagram failure may pass, so the post is tried again next run; any other failure is kept on the post
+function passing(err: unknown): boolean {
+ return err instanceof DatabaseError || err instanceof UpstreamError || !(err instanceof AppError);
+}
+
+export function createPostAutomationService({ posts, rules, automations, context }: PostAutomationDeps): PostAutomationService {
+ const { log } = context;
+
+ // a rule saved by an earlier run whose post was not marked yet is reused, so a post never gets two rules
+ async function existingRule(userId: string, post: ScheduledPost, mediaId: string, name: string): Promise<string | null> {
+ const found = (await rules.listForUser(userId)).find(rule => rule.accountId === post.accountId && rule.name === name
+ && rule.mediaIds.length === 1 && rule.mediaIds[0] === mediaId);
+ return found?.id ?? null;
+ }
+
+ async function attach({ post, userId }: PostAwaitingAutomation): Promise<boolean> {
+ const automation = post.automation;
+ const mediaId = post.publishedMediaId;
+ if (!automation) return false;
+ if (!mediaId) {
+ await posts.updateById(post.id, { automationError: NO_MEDIA_ID });
+ return false;
+ }
+ const name = postRuleName(post);
+ const ruleId = await existingRule(userId, post, mediaId, name) ?? (await automations.createRule(userId, {
+ accountId: post.accountId,
+ name,
+ keywords: [],
+ matchMode: 'any',
+ mediaIds: [mediaId],
+ privateReplyEnabled: true,
+ replyText: automation.replyText,
+ publicReplyEnabled: automation.publicReplyTexts.length > 0,
+ publicReplyTexts: automation.publicReplyTexts,
+ enabled: true,
+ })).id;
+ await posts.updateById(post.id, { automationRuleId: ruleId });
+ return true;
+ }
+
+ return {
+ async attachPublished(limit) {
+ const waiting = await posts.listAwaitingAutomation(limit);
+ const run: PostAutomationRun = { created: 0, failed: 0 };
+ for (const item of waiting) {
+ try {
+ if (await attach(item)) run.created++;
+ else run.failed++;
+ } catch (err) {
+ run.failed++;
+ log.warn('post automation not attached', { postId: item.post.id, ...errorFields(err) });
+ if (!passing(err)) await posts.updateById(item.post.id, { automationError: (err as Error).message });
+ }
+ }
+ if (waiting.length > 0) log.info('post automation run', { ...run });
+ return run;
+ },
+ };
+}
diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.ts
index 003bf40..b43973f 100644
--- a/backend/services/scheduledPostService.ts
+++ b/backend/services/scheduledPostService.ts
@@ -60,6 +60,7 @@ export function createScheduledPostService({ accounts, posts }: ScheduledPostDep
createdAt: new Date().toISOString(),
publishedMediaId: null,
error: null,
+ ...(request.automation ? { automation: request.automation } : {}),
};
await posts.create(post, userId);
return post;
diff --git a/backend/tests/mcp/scheduledPostTools.test.ts b/backend/tests/mcp/scheduledPostTools.test.ts
index 17cd25a..6cb99b9 100644
--- a/backend/tests/mcp/scheduledPostTools.test.ts
+++ b/backend/tests/mcp/scheduledPostTools.test.ts
@@ -89,3 +89,17 @@ test('fields the tools do not publish are refused, so a client cannot set what i
const withMedia = scheduleInstagramPost.parse({ accountId: 'ig-1', mediaUrl: 'https://cdn.example/a.jpg', scheduledAt: LATER, confirmationToken: 'x' });
assert.match(scheduleInstagramPost.describe?.(withMedia) ?? '', /Media: https:\/\/cdn\.example\/a\.jpg\./);
});
+
+test('a post scheduled with an automation shows its private and public replies in the confirmation, and reports when its rule exists', async () => {
+ const input = scheduleInstagramPost.parse({
+ accountId: 'ig-1', mediaUrl: 'https://res.cloudinary.com/demo/reel.mp4', mediaType: 'REELS', scheduledAt: LATER,
+ automation: { replyText: 'Here is the link', publicReplyTexts: ['Sent you a DM', 'Check your messages'] },
+ });
+ const described = scheduleInstagramPost.describe?.(input) ?? '';
+ assert.match(described, /anyone who comments gets this private reply: "Here is the link"/);
+ assert.match(described, /"Sent you a DM", "Check your messages"/);
+ const ctx = context([post('live', 'published', { automation: { replyText: 'Hi', publicReplyTexts: [] }, automationRuleId: 'rule-1' })]);
+ const got = await getScheduledPost.run({ postId: 'live' }, ctx) as { post: { automation: { ruleCreated: boolean; error: string | null } } };
+ assert.deepEqual(got.post.automation, { replyText: 'Hi', publicReplyTexts: [], ruleCreated: true, error: null });
+ assert.throws(() => scheduleInstagramPost.parse({ accountId: 'ig-1', mediaUrl: 'https://x/y.mp4', scheduledAt: LATER, automation: { publicReplyTexts: ['Hi'] } }), ValidationError);
+});
diff --git a/backend/tests/repositories/scheduledPostRepository.test.ts b/backend/tests/repositories/scheduledPostRepository.test.ts
index 04cec7c..2c3726e 100644
--- a/backend/tests/repositories/scheduledPostRepository.test.ts
+++ b/backend/tests/repositories/scheduledPostRepository.test.ts
@@ -55,3 +55,16 @@ describe('scheduled post repository', () => {
assert.deepEqual(db.table.map(row => (row.data as Row).caption), ['Hi', 'Changed']);
});
});
+
+test('only published posts with an automation, no rule yet and no recorded failure wait for a rule, each with its owner', async () => {
+ const automation = { replyText: 'Here is the link', publicReplyTexts: [] };
+ const posts = createScheduledPostRepository(fakeSupabase([
+ postRow('waiting', { status: 'published', user_id: 'user-2', data: { automation, publishedMediaId: '1789' } }),
+ postRow('pending', { data: { automation } }),
+ postRow('plain', { status: 'published', data: { caption: 'No automation' } }),
+ postRow('done', { status: 'published', data: { automation, automationRuleId: 'rule-1' } }),
+ postRow('broken', { status: 'published', data: { automation, automationError: 'No access token' } }),
+ ]));
+ const waiting = await posts.listAwaitingAutomation(10);
+ assert.deepEqual(waiting.map(item => [item.post.id, item.userId, item.post.publishedMediaId]), [['waiting', 'user-2', '1789']]);
+});
diff --git a/backend/tests/services/postAutomationService.test.ts b/backend/tests/services/postAutomationService.test.ts
new file mode 100644
index 0000000..96d5b50
--- /dev/null
+++ b/backend/tests/services/postAutomationService.test.ts
@@ -0,0 +1,78 @@
+import { test, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createPostAutomationService, postRuleName } from '../../services/postAutomationService.ts';
+import { DatabaseError, ValidationError } from '../../lib/errors.ts';
+import { createLogger } from '../../lib/logger.ts';
+import type { AutomationService } from '../../services/automationService.ts';
+import type { AutomationRuleRepository } from '../../repositories/automationRuleRepository.ts';
+import type { PostAwaitingAutomation, ScheduledPostRepository } from '../../repositories/scheduledPostRepository.ts';
+import type { AutomationRule, AutomationRuleRequest } from '../../../shared/types/automation.ts';
+import type { ScheduledPost } from '../../../shared/types/domain.ts';
+
+const CONTEXT = { requestId: 'req', signal: new AbortController().signal, log: createLogger() };
+const AUTOMATION = { replyText: 'Here is the link: https://example.com', publicReplyTexts: ['Sent you a DM'] };
+
+function post(id: string, overrides: Partial<ScheduledPost> = {}): ScheduledPost {
+ return {
+ id, accountId: 'ig1', status: 'published', scheduledAt: '2026-11-05T14:30:00.000Z',
+ caption: 'Comment "AGENTS" and I will send the link\n\nMore text', publishedMediaId: '1789', automation: AUTOMATION, ...overrides,
+ };
+}
+
+function harness(waiting: PostAwaitingAutomation[], createRule: (userId: string, input: AutomationRuleRequest) => Promise<AutomationRule>, saved: AutomationRule[] = []) {
+ const updates: [string, Partial<ScheduledPost>][] = [];
+ const posts = {
+ listAwaitingAutomation: async () => waiting,
+ updateById: async (id: string, changes: Partial<ScheduledPost>) => { updates.push([id, changes]); },
+ } as unknown as ScheduledPostRepository;
+ const rules = { listForUser: async () => saved } as unknown as AutomationRuleRepository;
+ const service = createPostAutomationService({ posts, rules, automations: { createRule } as Pick<AutomationService, 'createRule'>, context: CONTEXT });
+ return { service, updates };
+}
+
+test('a published post gets one rule that answers any comment on that post, owned by the post\'s person, and is marked done', async () => {
+ const made: [string, AutomationRuleRequest][] = [];
+ const { service, updates } = harness([{ post: post('p1'), userId: 'user-2' }], async (userId, input) => {
+ made.push([userId, input]);
+ return { id: 'rule-9' } as AutomationRule;
+ });
+ assert.deepEqual(await service.attachPublished(3), { created: 1, failed: 0 });
+ assert.equal(made[0][0], 'user-2');
+ assert.deepEqual(made[0][1], {
+ accountId: 'ig1', name: 'Post 2026-11-05: Comment "AGENTS" and I will send the link', keywords: [], matchMode: 'any', mediaIds: ['1789'],
+ privateReplyEnabled: true, replyText: AUTOMATION.replyText, publicReplyEnabled: true, publicReplyTexts: ['Sent you a DM'], enabled: true,
+ });
+ assert.deepEqual(updates, [['p1', { automationRuleId: 'rule-9' }]]);
+});
+
+test('a rule an earlier run already saved is reused, so a post never gets two rules', async () => {
+ const existing = { id: 'rule-1', accountId: 'ig1', name: postRuleName(post('p1')), mediaIds: ['1789'] } as AutomationRule;
+ const createRule = mock.fn(async () => ({ id: 'rule-2' }) as AutomationRule);
+ const { service, updates } = harness([{ post: post('p1'), userId: 'user-1' }], createRule, [existing]);
+ await service.attachPublished(3);
+ assert.equal(createRule.mock.callCount(), 0);
+ assert.deepEqual(updates, [['p1', { automationRuleId: 'rule-1' }]]);
+});
+
+test('a post without an Instagram id or with a lasting failure keeps the reason; a passing failure is tried again next run', async t => {
+ const warn = mock.method(console, 'warn', () => undefined);
+ t.after(() => warn.mock.restore());
+ const waiting = [
+ { post: post('no-id', { publishedMediaId: null }), userId: 'user-1' },
+ { post: post('no-token'), userId: 'user-1' },
+ { post: post('db-down'), userId: 'user-1' },
+ ];
+ const { service, updates } = harness(waiting, async (_userId, input) => {
+ if (input.mediaIds?.[0] === '1789' && updates.some(([id]) => id === 'no-token')) throw new DatabaseError('automationRules.create', new Error('down'));
+ throw new ValidationError('This Instagram account has no access token. Reconnect it on the Accounts page.');
+ });
+ assert.deepEqual(await service.attachPublished(3), { created: 0, failed: 3 });
+ assert.deepEqual(updates.map(([id, changes]) => [id, Boolean(changes.automationError)]), [['no-id', true], ['no-token', true]]);
+});
+
+test('a long first line is cut to the 80 characters a rule name allows', () => {
+ const name = postRuleName(post('p1', { caption: 'x'.repeat(200) }));
+ assert.equal(name.length, 80);
+ assert.ok(name.endsWith('...'));
+ assert.equal(postRuleName(post('p2', { caption: '' })), 'Post 2026-11-05');
+});
diff --git a/backend/tests/validators/automationValidators.test.ts b/backend/tests/validators/automationValidators.test.ts
index 8b3e0d5..d02f1c8 100644
--- a/backend/tests/validators/automationValidators.test.ts
+++ b/backend/tests/validators/automationValidators.test.ts
@@ -2,7 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parseActivityQuery, parseAutomationAccount, parseAutomationRule, parseAutomationRuleUpdate, parseAutomationTest, parseStatsQuery,
- parseWebhookVerification,
+ parsePostAutomation, parseWebhookVerification,
} from '../../validators/automationValidators.ts';
const valid = { accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], replyText: 'Here it is' };
@@ -133,3 +133,14 @@ test('pausing needs a true or false, and the webhook check reads the hub paramet
mode: 'subscribe', verifyToken: 'tok', challenge: '123',
});
});
+
+test('a scheduled post automation needs its private reply within Instagram’s 1,000 bytes, and cleans its public replies', () => {
+ assert.equal(parsePostAutomation({}), undefined);
+ assert.equal(parsePostAutomation({ automation: null }), undefined);
+ assert.deepEqual(parsePostAutomation({ automation: { replyText: ' Here it is ', publicReplyTexts: [' Sent you a DM ', 'Sent you a DM', ''] } }), {
+ replyText: 'Here it is', publicReplyTexts: ['Sent you a DM'],
+ });
+ assert.throws(() => parsePostAutomation({ automation: 'Here it is' }), /must be an object/);
+ assert.throws(() => parsePostAutomation({ automation: { publicReplyTexts: ['Hi'] } }), /replyText is required/);
+ assert.throws(() => parsePostAutomation({ automation: { replyText: '\u{1F4E9}'.repeat(300) } }), /1200 bytes/);
+});
diff --git a/backend/validators/automationValidators.ts b/backend/validators/automationValidators.ts
index 4c4105d..a86545e 100644
--- a/backend/validators/automationValidators.ts
+++ b/backend/validators/automationValidators.ts
@@ -1,6 +1,7 @@
import { ValidationError } from '../lib/errors.ts';
import { followTextsProblem, keywordsProblem, replyActionsProblem } from '../lib/automationRules.ts';
import { MAX_PUBLIC_REPLY_TEXTS, publicReplyTextProblem } from '../lib/automationPublicReply.ts';
+import { MAX_MESSAGE_BYTES, messageBytes } from '../lib/automationDelivery.ts';
import { isString, optionalArray, optionalBoolean, optionalNumber, optionalString, presentField, requiredString } from './fields.ts';
import type { Fields } from './fields.ts';
import type { ActivityCursor } from '../repositories/automationCommentRepository.ts';
@@ -8,6 +9,7 @@ import type {
AutomationAccountRequest, AutomationCommentStatus, AutomationMatchMode, AutomationRuleRequest, AutomationRuleUpdateRequest,
AutomationTestRequest,
} from '../../shared/types/automation.ts';
+import type { ScheduledPostAutomation } from '../../shared/types/domain.ts';
const MATCH_MODES: AutomationMatchMode[] = ['contains', 'exact', 'any'];
const STATUSES: AutomationCommentStatus[] = ['ignored', 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'];
@@ -125,6 +127,21 @@ function publicReplyTexts(body: Fields): string[] | undefined {
return texts;
}
+// a scheduled post's comment automation, made into a rule for that post once it is published
+export function parsePostAutomation(body: Fields): ScheduledPostAutomation | undefined {
+ if (!presentField(body, 'automation') || body.automation === null) return undefined;
+ if (typeof body.automation !== 'object' || Array.isArray(body.automation)) {
+ throw new ValidationError('automation must be an object with replyText and, optionally, publicReplyTexts');
+ }
+ const fields = body.automation as Fields;
+ const reply = replyText(fields).trim();
+ if (!reply) throw new ValidationError('automation.replyText is required: the private reply sent to each person who comments');
+ // checked now, so a post never waits weeks only to fail when its rule is made
+ const bytes = messageBytes(reply);
+ if (bytes > MAX_MESSAGE_BYTES) throw new ValidationError(`automation.replyText is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}. Shorten it.`);
+ return { replyText: reply, publicReplyTexts: publicReplyTexts(fields) ?? [] };
+}
+
// only https links without a user name or password, since the link goes to strangers in a private message
function linkUrl(body: Fields): string | null | undefined {
if (!presentField(body, 'linkUrl')) return undefined;
diff --git a/backend/validators/scheduledPostValidators.ts b/backend/validators/scheduledPostValidators.ts
index 0fae8be..09c6b50 100644
--- a/backend/validators/scheduledPostValidators.ts
+++ b/backend/validators/scheduledPostValidators.ts
@@ -1,5 +1,6 @@
import { ValidationError } from '../lib/errors.ts';
import { mediaType, postDetails } from './publishingValidators.ts';
+import { parsePostAutomation } from './automationValidators.ts';
import { optionalString, presentField, requiredString } from './fields.ts';
import type { Fields } from './fields.ts';
import type { MediaType, Platform, ScheduledPostRequest, ScheduledPostUpdateRequest } from '../../shared/types/domain.ts';
@@ -26,6 +27,7 @@ export function parseScheduledPost(body: Fields): ScheduledPostRequest {
scheduledAt: requiredString(body, 'scheduledAt', required),
platform: platform(body),
mediaType: mediaType(body, SCHEDULED_MEDIA_TYPES),
+ automation: parsePostAutomation(body),
};
}
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index de26ab1..a673c8d 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -14,8 +14,8 @@ The Workers Free plan allows five cron triggers per Cloudflare account. This Wor
| Trigger | Plan (`cronPlan`) | Job | Responsibility |
|---|---|---|---|
| `* * * * *` | `dispatch` | `automationProcessor.run()`, then `automationFollowups.run()`, then `automationPublicReplies.run()` | Queue dispatch and recovery: due private replies, follow-ups and public replies, jobs whose run stopped |
-| `*/5 * * * *` at minutes 0, 15, 30, 45 | `publish` | `scheduledPublisher.publishDue()` | Scheduled processing: due Instagram posts |
-| `*/5 * * * *` at the other minutes | `reconcile` | `automationReconciler.run()` | Reconciliation: overdue jobs, replies whose answer was lost, queue health |
+| `*/5 * * * *` at minutes 0, 15, 30, 45 | `publish` | `scheduledPublisher.publishDue()`, then `postAutomation.attachPublished(3)` | Scheduled processing: due Instagram posts, then the comment rule of each newly published post that carries one |
+| `*/5 * * * *` at the other minutes | `reconcile` | `automationReconciler.run()`, then `postAutomation.attachPublished(3)` | Reconciliation: overdue jobs, replies whose answer was lost, queue health; and the comment rules of posts the GitHub Actions scheduler published |
| `*/5 * * * *` at minutes 5, 20, 35, 50 | `youtube` | `youtubeRunner.run()` | Moves one YouTube upload: session, chunks, processing check or thumbnail (`docs/platform-v2/YOUTUBE_INTEGRATION.md`); the reconcile plan keeps minutes 10, 25, 40 and 55 |
| `0 0 * * *` | `daily` | `tokenRefresh.refreshExpiringInstagramTokens()`, then `retention.purge()` | Maintenance: tokens and retention |
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index a732ba8..3e0c17a 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -135,7 +135,7 @@ Controllers call `ScheduledPostService` (`services/scheduledPostService.ts`).
| Method | Path | File | Purpose |
|---|---|---|---|
| GET | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.listScheduledPosts` | List all user's scheduled posts, ordered by `scheduled_at` ascending |
-| POST | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.createScheduledPost` | Create a new scheduled post with `status: 'pending'`; 400 unless `scheduledAt` is a future date; 404 `Instagram account not found` unless `accountId` is one of the user's Instagram accounts; 400 when that account has no token |
+| POST | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.createScheduledPost` | Create a new scheduled post with `status: 'pending'`. An optional `automation` (`{ replyText, publicReplyTexts }`, the reply within Instagram's 1,000 bytes) is kept with the post and becomes a rule answering any comment on it once it is published (`docs/architecture/data-flows/SCHEDULING.md`, Comment automation for a scheduled post); 400 unless `scheduledAt` is a future date; 404 `Instagram account not found` unless `accountId` is one of the user's Instagram accounts; 400 when that account has no token |
| PUT | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.updateScheduledPost` | Edit a pending post (caption, scheduled time, media, etc.); 400 for a post that is not pending |
| DELETE | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteScheduledPost` | Delete a single post; 400 while it is publishing |
| DELETE | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteAllScheduledPosts` | Delete all posts except those with `status: 'publishing'`; returns `{ deleted, kept }` |
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 9617403..eab5104 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -57,7 +57,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| `youtubeRunner` | `youtubeUploadRunner.ts` | YouTube uploads, YouTube connections, quota ledger | `run({ subrequests, timeBudgetMs })`: one job per run on the YouTube cron plan; session saved before bytes, resume from Google's count, 8 MiB chunks from Cloudinary, processing check, thumbnail, and an end state for every error class. Cross-user: `claim`, `saveLeased`, `releaseLeased`, `findById`, `updateTokensById`, `markNeedsReconnectById`, `parkForConnection` |
| `health` | `healthService.ts` | health | `readiness()` (`GET /api/health/ready`: one database read, timed; returns no data) |
-Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher`, `tokenRefresh`, `automationWebhook`, `automationProcessor`, `automationFollowups`, `automationPublicReplies`, `automationReconciler` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, follow-up, review, intake and retention methods).
+Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher`, `tokenRefresh`, `automationWebhook`, `automationProcessor`, `automationFollowups`, `automationPublicReplies`, `automationReconciler`, `postAutomation` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `listAwaitingAutomation`, `claim`, and the automation queue, follow-up, review, intake and retention methods).
`accounts.remove` and `instagramConnect.connect` also record `account.removed`, `account.connected` and `account.reconnected` in `audit_events`. Connecting an Instagram account that is already connected renews its token in place and answers `reconnected`, so a revoked token is fixed without removing the account and its rules.
@@ -291,4 +291,4 @@ For a new feature service:
rewrite the cache. The controllers pass it from `?fresh=1`, parsed by `parseFreshQuery` in
`validators/analyticsValidators.ts`. Both store `fetchedAt` with the cache entry, and
`overviewService` copies each cache entry's `fetchedAt` into its account summary.
-
+,### postAutomationService.ts,,`createPostAutomationService({ posts, rules, automations, context })` turns the `automation` of each newly published scheduled post into a rule: any comment on that post (`matchMode: 'any'`, `mediaIds: [publishedMediaId]`) gets the private reply and, when given, one of the public replies. The rule is made through `automations.createRule` for the post's owner, so it is checked, audited and switches on the account's comment events like a rule made on the page. `attachPublished(limit)` runs after each publish run and each reconcile run; a rule an earlier run saved is reused, a passing failure (database, Instagram) is tried again, and any other failure is kept on the post as `automationError`.,
\ No newline at end of file
diff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.md
index 03e464d..1612903 100644
--- a/docs/architecture/data-flows/AUTOMATION.md
+++ b/docs/architecture/data-flows/AUTOMATION.md
@@ -325,3 +325,7 @@ Everything runs on the existing Worker, Supabase project and Workers Free plan;
| Repositories | `repositories/automationRuleRepository.ts`, `automationCommentRepository.ts`, `automationFollowupRepository.ts`, `automationPublicReplyRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` |
| Database | `supabase/migrations/20261016100000` to `20261016103500`, `20261016120000` to `20261016122500` and `20261016130000` to `20261016132100`, one entity per file |
| App | `frontend/src/features/automations/` |
+
+## Rules made from scheduled posts
+
+A scheduled post can carry the reply for its own comments. Once it is published, `postAutomation.attachPublished` makes an ordinary enabled rule for that post (`matchMode: 'any'`, `mediaIds: [publishedMediaId]`) through `automations.createRule`, so everything above applies to it unchanged. The flow is in `SCHEDULING.md` (Comment automation for a scheduled post) and ADR-054.
diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.md
index 4ebfe8d..c48526c 100644
--- a/docs/architecture/data-flows/SCHEDULING.md
+++ b/docs/architecture/data-flows/SCHEDULING.md
@@ -166,3 +166,4 @@ Step-by-step instructions for a person setting this up: `docs/workflows/SCHEDULI
- The overdue alert on the Instagram publishing page counts `pending` posts more than 30 minutes late (a retried post counts from its last claim) and `publishing` posts whose claim is older than the lease plus 30 minutes, 50 minutes in all (`overduePostsOf()`). It reads `... more than 30 minutes late and not yet published, so the scheduler on this server is not running.` and names the administrator contact (`VITE_ADMIN_EMAIL`).
- Settings, Scheduled publishing says the GitHub fallback often starts hours late and is a backup, not a 15 minute guarantee.
- Note: These GitHub secrets are only required for System B - the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need them
+,## Comment automation for a scheduled post,,A scheduled post can carry an `automation` (`{ replyText, publicReplyTexts }` in `data`): the private reply for anyone who comments, and optional public replies. A rule needs the post's Instagram id, which only exists after publishing, so the rule is made then (#176):,,1. `POST /api/scheduled-posts` or the Claude tool `schedule_instagram_post` checks the reply against Instagram's 1,000 bytes and the public replies against the comment rules, and stores them with the post.,2. Either scheduler publishes the post and stores `publishedMediaId`.,3. The Worker's publish run, right after publishing, and its reconcile run call `postAutomation.attachPublished(3)`. It lists published posts with an automation and neither `automationRuleId` nor `automationError` (`listAwaitingAutomation`), oldest first, and creates an enabled rule answering any comment on that one post, named `Post <date>: <first caption line>`.,4. The post records `automationRuleId`; the rule then shows on the Instagram automation page like any other and can be edited or paused there.,,A post the Worker publishes gets its rule within the same run. A post the GitHub Actions scheduler publishes gets it at the next Worker publish or reconcile run, within about ten minutes; comments in that gap are recorded as ignored and are not answered.,
\ No newline at end of file
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index a08e78d..166cbee 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -216,6 +216,7 @@ A claim is one UPDATE that sets `status = 'publishing'`, `claimed_at = now()` an
```
- `containerId` is the Instagram media container, saved right after it is created and before the scheduler waits or publishes. A later run reads its `status_code` to find out whether the post already went out. It is cleared when the container expired and a retry needs a new one.
+- `automation` (`{ replyText, publicReplyTexts }`, optional) answers every comment on the post once it is published; `automationRuleId` is the rule made for it then, and `automationError` why it could not be made (`docs/architecture/data-flows/SCHEDULING.md`).
- `publishedMediaId` is `null` when a run found the post already published through the container status, because that status does not carry the media id.
- `error` is set on a `failed` post, and also on a `pending` post that is being retried, where it holds the reason the last attempt failed.
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 80f943e..26ec7e6 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -8,7 +8,7 @@ The backend uses the **service-role key** for all database operations. This key
2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish`, `release` and `returnUnstarted` on comments and follow-ups, `insertForMessages`, `expireDue`, `reviewCandidates`, `recordReview`, `health` and the retention `purgeCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply and follow-up processors. `healthRepository.ping` reads one `accounts` id for the public readiness check and returns nothing from it. Because ownership is a query filter, another user's record is simply not found (404).
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `listAwaitingAutomation`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish`, `release` and `returnUnstarted` on comments and follow-ups, `insertForMessages`, `expireDue`, `reviewCandidates`, `recordReview`, `health` and the retention `purgeCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply and follow-up processors. `healthRepository.ping` reads one `accounts` id for the public readiness check and returns nothing from it. Because ownership is a query filter, another user's record is simply not found (404).
The merge functions follow the same rule: the `...ForUser` repository methods pass the verified `userId` as `p_user_id`, and only `updateById` passes `null`, the cron form that reaches any user's row.
diff --git a/docs/platform-v2/MCP_DOCUMENTATION.md b/docs/platform-v2/MCP_DOCUMENTATION.md
index 46da728..e0b67a0 100644
--- a/docs/platform-v2/MCP_DOCUMENTATION.md
+++ b/docs/platform-v2/MCP_DOCUMENTATION.md
@@ -138,7 +138,7 @@ Every tool works only on the caller's own data. Read tools need no confirmation.
| `cancel_youtube_upload` | write, confirm | `uploadId` | `upload` |
| `list_scheduled_posts` | read | `status`, `limit` (1 to 50, default 20), `cursor` | `posts`, `nextCursor`, `total` |
| `get_scheduled_post` | read | `postId` | `post` |
-| `schedule_instagram_post` | write, confirm | `accountId`, `mediaUrl` (public https), `scheduledAt` (future ISO 8601), `mediaType` (IMAGE, VIDEO, REELS, STORIES), `caption`, `shareToFeed`, `collaborators`, `altText`, `locationId` | `post`, `alreadyScheduled` (true when the same media was already scheduled for that account and time) |
+| `schedule_instagram_post` | write, confirm | `accountId`, `mediaUrl` (public https), `scheduledAt` (future ISO 8601), `mediaType` (IMAGE, VIDEO, REELS, STORIES), `caption`, `shareToFeed`, `collaborators`, `altText`, `locationId`, `automation` (`replyText` up to 1,000 bytes, optional `publicReplyTexts`: once published, anyone who comments gets them; the confirmation shows both in full) | `post` (with `automation.ruleCreated` and `automation.error`), `alreadyScheduled` (true when the same media was already scheduled for that account and time) |
| `update_scheduled_post` | write | `postId` and the fields to change | `post` |
| `cancel_scheduled_post` | write, confirm | `postId` | `cancelled` |
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 2d9304a..1f77442 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -102,6 +102,8 @@ The MCP server has its own tests. `tests/lib/mcp/protocol.test.ts` covers parsin
YouTube publishing has its own tests: `tests/lib/youtubeUpload.test.ts` (chunk math, the Range header, Shorts, metadata limits, backoff, failure classes, the Pacific midnight), `tests/lib/tokenCrypto.test.ts` (sealing, wrong key, tampering), `tests/services/youtubeUploadRunner.test.ts` (every runner transition, the budget and a lost lease), `tests/services/youtubeConnectService.test.ts` (the sign-in bound to its starter and to one of their YouTube accounts, a different channel refused and its access revoked, sealed tokens, reconnect, a refused refresh, publishing turned off with its account), `tests/services/youtubeUploadService.test.ts`, `tests/routes/youtubeRoutes.test.ts` (the callback, and a verify link only for the caller's own YouTube account) and `tests/mcp/youtubeTools.test.ts`; on the frontend `tests/features/youtube/youtubeUploadData.test.ts` and `tests/features/accounts/youtubePublishingState.test.ts` (each YouTube card's publishing state and the Google return errors). `tests/lib/cloudinaryConfigState.test.ts` covers the upload settings' loading, ready and failed states.
+Comment automation for scheduled posts (#176) is covered by `tests/services/postAutomationService.test.ts` (one rule per published post, owned by its person, answering any comment on that post; a rule an earlier run saved is reused; lasting failures kept, passing ones retried), `tests/repositories/scheduledPostRepository.test.ts` (which posts wait for a rule), `tests/validators/automationValidators.test.ts` (the reply within 1,000 bytes) and `tests/mcp/scheduledPostTools.test.ts` (the confirmation shows both replies). `tests/fixtures/fakeSupabase.ts` reads `data->field` paths and `not(column, 'is', null)` the way PostgREST does.
+
The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option, and `tests/lib/signInPage.test.ts` when the sign-in page opens the dashboard for a stored session and when it leaves a sign-in on the page to finish.
The testing workflow documented here describes what should run before shipping any change.
diff --git a/shared/types/domain.ts b/shared/types/domain.ts
index d425c06..462ddfc 100644
--- a/shared/types/domain.ts
+++ b/shared/types/domain.ts
@@ -75,6 +75,14 @@ export interface CarouselItem {
mediaType?: MediaType;
}
+// a comment automation that waits for its post: once the post is published, a rule answers any comment on it
+export interface ScheduledPostAutomation {
+ // the private reply sent to each person who comments
+ replyText: string;
+ // replies posted under the comment, one picked per comment; empty for none
+ publicReplyTexts: string[];
+}
+
// one row of `scheduled_posts`: id, account_id, status and scheduled_at are columns, the rest is data jsonb
export interface ScheduledPost {
id: string;
@@ -104,6 +112,10 @@ export interface ScheduledPost {
attempts?: number;
// saved before the publish call, so a later run can ask Instagram whether the post went out
containerId?: string | null;
+ automation?: ScheduledPostAutomation | null;
+ // the rule made for the automation after publishing, or why it could not be made
+ automationRuleId?: string | null;
+ automationError?: string | null;
}
export interface ScheduledPublishFailure {
@@ -304,6 +316,7 @@ export interface ScheduledPostRequest {
locationId?: string;
userTags?: UserTag[];
altText?: string;
+ automation?: ScheduledPostAutomation;
}
// body of PUT /api/scheduled-posts/:id; any other field is ignored