Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
docs: describe public comment replies beside private replies
spacesdrive1b303b9fcd3f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 810e8cd..962fde7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,9 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- Followers-only rules, in testing and not yet tried with a real account: the first reply asks the person to follow and reply, and the link goes out only when Instagram confirms they follow; nothing is sent when Instagram cannot say (#103, #105, ADR-043)- A new every-minute cron trigger dispatches waiting replies and follow-ups, and the five minute runs off the quarter hour expire overdue replies, look for replies whose answer was lost in the conversation on Instagram, and log the queue's health (#99, #100, ADR-043)- New table `automation_followups` and new columns and functions for the reply queue; existing instances run `npm run db:push` before deploying (#99, #100, #102, #103)+- Public replies: a rule can also post a public reply under the comment, or only that, with up to five wordings that rotate per comment; the private and public replies have their own status, limits, cooldown and retry, and one failing never sends the other again (#107, ADR-044)+- A public reply whose answer was lost is looked for among the comment's replies and posted again once only when it is not there; `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT` (default 60) paces public replies, and each person gets at most one per post a day (#107)+- New table `automation_public_replies` and new columns and functions; existing instances run `npm run db:push` before deploying (#107)### Changeddiff --git a/DECISIONS.md b/DECISIONS.mdindex 1497a7a..0da66d6 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -943,3 +943,28 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts- Followers-only rules need the `messages` field selected in the Meta dashboard, which Meta applies to every connected account, and Advanced Access for `instagram_business_manage_messages`.- Any-comment rules message people who did not ask for it; the form warns, and the per-person daily limit still applies.- The changed SQL functions keep their old parameters with defaults so the deployed Worker keeps working once the migrations are applied, but the migrations must be applied before the new Worker is deployed.++## ADR-044: Public comment replies as their own jobs, beside private replies++**Date:** 2026-10-16+**Status:** Accepted++**Decision:** A rule can answer a matching comment with a private reply, a public reply under the comment, or both, each switched on its own (#107). A public reply is a row in a new table, `automation_public_replies`, one per comment, created with the comment in one transaction by `store_automation_comments`. It has its own claim, reservation, finish and review functions, its own attempts (kind `public_reply`), its own hourly limit (`AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT`, default 60, at most 200), its own cooldown (`automation_accounts.public_cooldown_until`), and a limit of one public reply per person and post a day. The every-minute dispatch posts public replies after private replies and follow-ups, keeping 11 of the run's 50 subrequests for them. A public reply whose answer was lost is looked for among the comment's replies; it is sent again once, by the dispatch, only when every reply was read on two checks minutes apart and it was in neither.++**Context:** Meta's documentation (checked 2026-10-16) supports `POST /<comment-id>/replies` with Instagram Login and `instagram_business_manage_comments`, which Twiligent already requests, so no account has to reconnect. A reply answers with the new comment's id; only top-level comments take replies, and hidden and live comments cannot. Meta publishes no hourly number for comment replies: they count against the Business Use Case limit shared with insights, and accounts that comment like a bot are blocked (code 368). The owner asked for independent delivery: a failure of one reply must never repeat the other, and an unknown outcome must never be resent blindly.++**Why a separate table:** Two state machines on `automation_comments` would make the two lanes lock each other's rows (`FOR UPDATE SKIP LOCKED` would skip a comment whose other reply is being sent) and double every queue column and index under prefixed names. One generic actions table for private replies, follow-ups and public replies would be cleaner in the long run, but it means rewriting the private reply path that is live; the new table follows the `automation_followups` pattern, so the three job kinds can be merged later if they keep converging.++**Why a public reply may be sent again when a private one may not:** A private reply whose answer was lost can only be searched for in the conversation, and Instagram refuses a second private reply anyway. A public reply can be read back directly from the comment's replies, so its absence can be checked. Reading twice, minutes apart, over every page, and allowing one resend, makes a second public reply unlikely without leaving most lost answers to a person.++**Alternatives considered:**+- Columns for the public reply on `automation_comments`. Rejected for the locking and duplication above.+- Waiting for the private reply before posting the public one, so "check your messages" is always true. It couples the two actions the owner asked to keep apart; private replies go first in every run instead, and the form says not to promise a message.+- The comments webhook for the account's own reply as confirmation. Meta does send it, but whether and when is not documented; Twiligent ignores the account's own comments, and the read of the comment's replies is the check.+- A per-rule hourly limit for public replies. The account limit and the one-per-person-and-post limit already bound them; the rule's limit stays a private reply limit.++**Trade-offs:**+- The 300 character, 4 hashtag and 1 link bounds are Twiligent's, from Instagram's older API; current documentation states none.+- The activity list's status filter follows the private reply; public replies count in the Needs attention and Waiting numbers, and each row shows both.+- Twenty-three migrations, one entity each, and three more SQL functions to keep in step with the fake queue in the tests.+- The migrations must be applied before the new Worker is deployed; the old Worker keeps working with them, since replaced functions only gain columns and keys.diff --git a/README.md b/README.mdindex 2ab5800..cebea4a 100644--- a/README.md+++ b/README.md@@ -65,7 +65,7 @@ The project's own public site and documentation are at [twiligent.ujjwal.fyi](ht| **Unified overview** | Cross-platform totals, audience comparison chart, audience share pie, leaderboards || **Content explorers** | Sortable and filterable grids for all YouTube Videos, all YouTube Shorts, and all Instagram Reels and posts || **Scheduled publishing** | Schedule Instagram photos, Reels, and Stories; a Cloudflare Worker cron publishes them every 15 minutes automatically |-| **Comment-to-DM automation** | When someone comments a keyword such as GUIDE, or any comment at all, on your Instagram posts or Reels, Twiligent sends them your private reply and link within seconds, through Meta's comments webhook and official private replies; optional followers-only rules send the link only after Instagram confirms the person follows you; per-account, per-rule and per-person limits, retries, a queue that sends waiting replies every minute and an activity log |+| **Comment automation** | When someone comments a keyword such as GUIDE, or any comment at all, on your Instagram posts or Reels, Twiligent sends them your private reply and link within seconds, posts a public reply under their comment, or both, through Meta's comments webhook, official private replies and comment replies; each reply has its own status and retry; optional followers-only rules send the link only after Instagram confirms the person follows you; per-account, per-rule and per-person limits, retries, a queue that sends waiting replies every minute and an activity log || **Bulk upload** | Upload multiple files at once, assign captions individually or apply a shared caption, schedule them with configurable intervals || **Cloudinary CDN** | Upload media directly from the dashboard; Instagram requires public URLs before publishing || **Token auto-refresh** | Instagram long-lived tokens renew automatically every 24 hours via a daily Worker cron so analytics never break |@@ -438,6 +438,7 @@ twiligent/│ │ ├── scheduledPublisher.ts # Publishes due scheduled posts (cron and manual trigger)│ │ ├── automationProcessor.ts # Sends comment-to-DM replies within limits (webhook, retry and every minute cron)│ │ ├── automationFollowupProcessor.ts # Checks the follow for followers-only replies and sends the link or a reminder+│ │ ├── automationPublicReplyProcessor.ts # Posts public replies under matched comments within their own limits│ │ ├── automationReconciler.ts # Expires overdue replies, checks lost replies on Instagram, logs queue health│ │ ├── youtube/ # YouTube Data API v3 client and analytics│ │ ├── instagram/ # Instagram Graph API client, OAuth, publishing and analyticsdiff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 3799033..b096e16 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -33,7 +33,8 @@│ ││ Cron handlers (wrangler.toml triggers, jobs/scheduled.ts): ││ ├── * * * * * -> automationProcessor.run(), then │-│ │ automationFollowups.run() (dispatch) │+│ │ automationFollowups.run(), then │+│ │ automationPublicReplies.run() (dispatch) ││ ├── */5 * * * * -> on :00 :15 :30 :45 publishDue(); on the ││ │ other minutes automationReconciler.run() ││ └── 0 0 * * * -> token refresh, retention purge │@@ -118,13 +119,19 @@ Cloudflare scheduler fires cron trigger-> claim due reply jobs (accounts take turns; paused, cooling down or limitedaccounts are left out), reserve within limits, send the private reply,record the outcome [see data-flows/AUTOMATION.md]- automationFollowups.run() [the subrequests the replies did not use]+ automationFollowups.run() [the subrequests the replies did not use, keeping 11]-> claim due follow-ups, check the follow, send the link or a reminder+ automationPublicReplies.run() [the rest, at least 11 subrequests]+ -> claim due public replies (accounts take turns; paused accounts and public+ cooldowns or limits are left out), reserve within limits, post the reply+ under the comment, record the outcome-> '*/5 * * * *' at the other minutes: reconcileautomationReconciler.run()- -> expire overdue replies (7 days) and follow-ups (24 hours)+ -> expire overdue replies (7 days), follow-ups (24 hours) and public replies (7 days)-> look for up to 4 Needs review replies in the Instagram conversation;a match is marked accepted, nothing is ever sent+ -> look for up to 5 public replies of unknown outcome among the comment's replies;+ found: accepted; missing on two full reads: back in the queue once for the dispatch-> log the queue's health, and a warning when replies wait too long-> '*/5 * * * *' at minutes 0, 15, 30, 45: publishscheduledPublisher.publishDue()diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex 448a449..234bd96 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -13,7 +13,7 @@ The Workers Free plan allows five cron triggers per Cloudflare account. This Wor| Trigger | Plan (`cronPlan`) | Job | Responsibility ||---|---|---|---|-| `* * * * *` | `dispatch` | `automationProcessor.run()`, then `automationFollowups.run()` | Queue dispatch and recovery: due replies and follow-ups, jobs whose run stopped |+| `* * * * *` | `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 || `0 0 * * *` | `daily` | `tokenRefresh.refreshExpiringInstagramTokens()`, then `retention.purge()` | Maintenance: tokens and retention |@@ -78,14 +78,14 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish### `* * * * *` - Reply Dispatch-**Functions:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`, then `automationFollowups.run()` in `backend/services/automationFollowupProcessor.ts`+**Functions:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`, then `automationFollowups.run()` in `backend/services/automationFollowupProcessor.ts`, then `automationPublicReplies.run()` in `backend/services/automationPublicReplyProcessor.ts`-Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The dispatch sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, follow-ups to people who answered a followers-only reply, and jobs whose run stopped.+Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The dispatch sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, follow-ups to people who answered a followers-only reply, public replies, and jobs whose run stopped.- It claims up to `AUTOMATION_BATCH_SIZE` due comments (10 by default, at most 15), with accounts taking turns, and settles each one before the next. Paused, cooling and limited accounts are not claimed at all.-- Private replies get the run's 50 subrequests; follow-ups get what the replies did not use (four each).+- Private replies go first, since Instagram allows them only for 7 days and a public reply often points to them; they get the run's 50 subrequests less 11 kept for public replies. Follow-ups get what the private replies did not use (four each), and public replies the rest, at least 11: three a run, 180 an hour, above their default limit of 60. The three share the run's 50 seconds in that order.- It stops starting sends after 50 seconds, handing any unstarted job back to the queue, so one minute's run rarely overlaps the next. When they do overlap, the claim's row locks keep them apart.-- With nothing due, a dispatch is two database calls (the two claims) and writes nothing.+- With nothing due, a dispatch is three database calls (the three claims) and writes nothing.A run that stops is recovered by a later one: a job left `processing` for more than 20 minutes is claimed again, and one left `sending` becomes `needs_review`, because its message may have reached Instagram. `AUTOMATION_PAUSED=true` makes every dispatch return without claiming anything.diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex f893ef0..1d1e10c 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -170,7 +170,8 @@ Controllers call `AutomationService` (`services/automationService.ts`). Every ro| POST | `/api/automations/rules/:id/duplicate` | `automationController.duplicateAutomationRule` | Copy a rule, turned off, named "(copy)" || POST | `/api/automations/test` | `automationController.testAutomationRule` | Match a sample `comment` against a rule draft (accepts `matchMode: 'any'`, `requireFollow` and `followPromptText`) and return `{ matched, keyword, message, messageBytes, maxMessageBytes }`; `keyword` is `null` for any comment, and `message` is the follow prompt for a followers-only draft. Stores and sends nothing || GET | `/api/automations/activity` | `automationController.listAutomationActivity` | Received comments, newest first; each item has `gateStatus` and `followup` (`{ status, kind, errorMessage, createdAt }` or `null`) for followers-only replies. Query: `accountId`, `ruleId`, `status` (one or comma-separated), `from`, `to`, `before` (the previous page's `nextBefore`, an opaque `<created_at>|<id>` cursor, so comments stored in the same instant are neither skipped nor repeated), `limit` (1 to 100, default 50) |-| POST | `/api/automations/activity/:id/retry` | `automationController.retryAutomationActivity` | Put a failed, skipped or review item inside its 7 days back in the queue and start sending it. For an accepted followers-only reply, requeue its latest failed, skipped or review follow-up inside its 24 hours and start the follow-up processor in the background; 409 for any other state |+| POST | `/api/automations/activity/:id/public-reply/retry` | `automationController.retryAutomationPublicReply` | Put the item's failed, skipped or review public reply inside the comment's 7 days back in the queue and start posting it in the background; the private reply is untouched. 404 for another user's item, 409 when there is no public reply or it cannot be retried |+| POST | `/api/automations/activity/:id/retry` | `automationController.retryAutomationActivity` | Put a failed, skipped or review item inside its 7 days back in the queue and start sending its private reply; the public reply is untouched, and an item whose rule sends no private reply answers 409. For an accepted followers-only reply, requeue its latest failed, skipped or review follow-up inside its 24 hours and start the follow-up processor in the background; 409 for any other state || GET | `/api/automations/stats` | `automationController.getAutomationStats` | Comment counts by status and request counts by outcome. Query: `accountId`, `ruleId`, `from`, `to` (default the last 7 days) || PUT | `/api/automations/accounts/:accountId` | `automationController.updateAutomationAccount` | `{ paused }`: hold or release the account's replies; resuming also clears a hold the Worker set and sends held replies on the next run || POST | `/api/automations/accounts/:accountId/subscribe` | `automationController.subscribeAutomationAccount` | Ask Instagram to send the account's comments to the webhook, plus its messages while a followers-only rule is on (`POST /<ig-id>/subscribed_apps` with `comments` or `comments,messages`); when Instagram refuses messages, comments only. 502 when Instagram refuses. Covered by the quota rate limit |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex ff33137..4c2d03f 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -42,27 +42,29 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `settings` | `settingsService.ts` | settings | `githubSettings`, `saveGithubSettings`, `serverKeyStatus` || `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` || `authEmail` | `authEmailService.ts` | email quota (Redis, the fail-fast client) | `send(hook, webhookId)` (Supabase Auth's Send Email hook; no user) |-| `automations` | `automationService.ts` | accounts, automation rules, comments, follow-ups, account controls, audit | `overview`, `createRule`, `updateRule`, `duplicateRule`, `deleteRule`, `test`, `activity`, `stats`, `retry`, `setPaused`, `subscribe` |-| `automationWebhook` | `automationWebhookService.ts` | automation rules, comments, follow-ups | `challengeAnswer` (Meta's verification), `ingest` (store a webhook's comments, and a follow-up for each message that answers a followers-only reply; no user) |+| `automations` | `automationService.ts` | accounts, automation rules, comments, follow-ups, public replies, account controls, audit | `overview`, `createRule`, `updateRule`, `duplicateRule`, `deleteRule`, `test`, `activity`, `stats`, `retry` (the private reply or its follow-up), `retryPublicReply` (the public reply alone), `setPaused`, `subscribe` |+| `automationWebhook` | `automationWebhookService.ts` | automation rules, comments, follow-ups | `challengeAnswer` (Meta's verification), `ingest` (store a webhook's comments with their public reply jobs, and a follow-up for each message that answers a followers-only reply; no user) || `automationProcessor` | `automationProcessor.ts` | comments | `run({ ids?, limit?, subrequests?, timeBudgetMs? })` (send due private replies; webhook, retry route and every minute cron) || `automationFollowups` | `automationFollowupProcessor.ts` | follow-ups | `run({ ids?, subrequests?, timeBudgetMs? })` (check the follow and send the link or a reminder for followers-only replies; webhook, retry route and every minute cron) |-| `automationReconciler` | `automationReconciler.ts` | comments | `run()` (expire overdue replies and follow-ups, look for lost replies on Instagram, log the queue's health; five minute cron, never sends) |+| `automationPublicReplies` | `automationPublicReplyProcessor.ts` | public replies | `run({ ids?, subrequests?, timeBudgetMs? })` (post due public replies under their comments; webhook, public reply retry route and every minute cron) |+| `automationReconciler` | `automationReconciler.ts` | comments, public replies | `run()` (expire overdue replies, follow-ups and public replies, look for lost replies on Instagram, log the queue's health; five minute cron, never sends or posts) || `retention` | `retentionService.ts` | comments, audit | `purge(now?, { commentBatches? })` (daily cron; comments in batches of 1,000) |-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`, `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` 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).`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.New rows get their id from `newRowId()` in `backend/lib/ids.ts`, a UUID from `crypto.randomUUID()`, so an id cannot be worked out from another one. Tests pin the ids with `mockRowIds()` from `backend/tests/fixtures/rowIds.ts`.-### Comment automation (`automationService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationReconciler.ts`)+### Comment automation (`automationService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationPublicReplyProcessor.ts`, `automationReconciler.ts`)The flow is in `docs/architecture/data-flows/AUTOMATION.md`. The rules the services apply are pure helpers in `backend/lib/`:| Helper | What it decides ||---|---|| `automationMatching.ts` | `matchedKeyword` (contains as whole words, or the exact comment; NFKC and case folding), `ruleMatch` (an any-comment rule answers every comment with text, keyword `null`), `coversMedia`, `pickRule` (rules for the post first, keyword rules before any-comment rules, then oldest) |-| `automationRules.ts` | `keywordsProblem` (no keywords for any comment, 1 to 10 for the other modes), `followTextsProblem` (both followers-only texts present, each at most 1,000 characters and bytes) |+| `automationPublicReply.ts` | `pickPublicReplyText` (one wording per comment, by an FNV-1a hash of its id), `publicReplyTextProblem` (300 characters, 4 hashtags, 1 link), `publicFinishPlan`, `publicReadinessPlan`, `publicReleasePlan` (what to record or hold for a public reply; code 100 subcode 33 is a deleted or hidden comment), `shouldResend` and `publicReviewNote` (a lost public reply goes out again once, only after two full reads of the comment's replies), and the review constants: first check 5 minutes after the attempt, then every 5 minutes, 3 checks, 5 replies a run |+| `automationRules.ts` | `replyActionsProblem` (at least one reply on, each one used has its text, followers-only needs the private reply), `keywordsProblem` (no keywords for any comment, 1 to 10 for the other modes), `followTextsProblem` (both followers-only texts present, each at most 1,000 characters and bytes) || `automationDelivery.ts` | `classifySendError` (Graph codes to rate limited, blocked, transient, already replied, not authorized, not eligible, refused), `finishPlan` (what to record for each answer), `readinessPlan` and `releasePlan` (jobs that cannot send now), `followupReadiness` and `followupMessage` (what a follow-up sends for each follow answer), `replyMessage` (the follow prompt, or the reply and link), `messageDigest`, `retryDelayMs`, `cooldownFromUsage`, `composeReply`, `messageBytes`, and the constants: 1,000 byte messages, the 7 day window, the 20 minute claim lease, 5 tries, a 5 second follow check, 2 reminders || `automationReview.ts` | `findSentReply` (a message from the account, sent after the attempt started with 2 minutes of slack, whose text has the attempt's digest), `reviewNote`, and the review constants: first check 5 minutes after the attempt, at most 3 checks 30 minutes apart, 4 replies a run || `automationHealth.ts` | `QueueHealth` and `healthWarning` (one line when the oldest due reply waited over 10 minutes or jobs are held by runs that stopped) |diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 1375d68..c7495c9 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -63,7 +63,8 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T| `AUTOMATION_USER_HOURLY_LIMIT` | Optional | Private replies an hour across one member's accounts; default `500` || `AUTOMATION_GLOBAL_HOURLY_LIMIT` | Optional | Private replies an hour across the instance; default `1000` || `AUTOMATION_RECIPIENT_DAILY_LIMIT` | Optional | Private replies a day one person can get from one account; default `3` |-| `AUTOMATION_BATCH_SIZE` | Optional | Replies sent by one webhook request or one dispatch run; default `10`, at most `15` (each costs three of the free plan's 50 subrequests) |+| `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT` | Optional | Public replies under comments an hour per Instagram account; default `60`, at most `200`. Meta publishes no limit for comment replies but blocks accounts that comment like a bot, so the pace stays human |+| `AUTOMATION_BATCH_SIZE` | Optional | Replies sent by one webhook request or one dispatch run, for each kind of reply; default `10`, at most `15` (each costs three of the free plan's 50 subrequests) |The automation values are plain settings, not secrets, but setting them with `wrangler secret put` keeps them across deploys like the rest. A missing or invalid value falls back to its default.diff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.mdindex 1bffe64..2dc07ff 100644--- a/docs/architecture/data-flows/AUTOMATION.md+++ b/docs/architecture/data-flows/AUTOMATION.md@@ -1,25 +1,29 @@-# Data Flow - Comment-to-DM Automation+# Data Flow - Comment Automation: Private and Public Replies## Overview-An account owner writes a rule: keywords or any comment, which posts it covers, and a reply with an optional link. When someone comments on a post or reel of a connected Instagram professional account and a rule answers the comment, Meta sends the comment to the Worker's webhook, and the Worker sends the commenter a private reply through Instagram's messages endpoint. A followers-only rule first asks the person to follow and reply, and sends the link once Instagram confirms the follow.+An account owner writes a rule: keywords or any comment, which posts it covers, and how to answer. A rule can send the commenter a private reply (a direct message, with an optional link), post a public reply under the comment, or both; each is switched on and off on its own. When someone comments on a post or reel of a connected Instagram professional account and a rule answers the comment, Meta sends the comment to the Worker's webhook, and the Worker sends the private reply through Instagram's messages endpoint and posts the public reply through the comment's replies endpoint. A followers-only rule first asks the person to follow and reply, and sends the link once Instagram confirms the follow.++The two replies are separate jobs with separate statuses, retries, limits, cooldowns and reviews (ADR-044). A failure of one never repeats the other.```Instagram comment Instagram message (followers-only rules only)-> Meta webhook POST /api/webhooks/instagram (signed with X-Hub-Signature-256)-> verifyMetaWebhook 1 MB limit, HMAC-SHA256 over the raw body with the app secret-> parseInstagramWebhook comments changes and messaging events; anything else is counted and dropped- -> automationWebhook.ingest rules for the account -> match -> store every comment (dedupe);- messages from people a followers-only reply waits for -> follow-up jobs+ -> automationWebhook.ingest rules for the account -> match -> store every comment with its public reply job+ in one transaction (dedupe); messages from people a followers-only reply waits+ for -> follow-up jobs-> 200 {"success":true} only after both are stored; a failure answers 5xx and Meta retries for 36 hours- -> waitUntil: send the new replies, then the new follow-ups, after the response- claim -> check -> reserve within limits -> POST /<ig-id>/messages -> finish- -> every minute (* * * * *): dispatch: due replies and follow-ups, recovery of stopped runs- -> every 5 minutes, off the quarter: reconcile: expire overdue jobs, look for lost replies, report queue health+ -> waitUntil: send the new private replies, then the new follow-ups, then the new public replies+ claim -> check -> reserve within limits -> POST /<ig-id>/messages or /<comment-id>/replies -> finish+ -> every minute (* * * * *): dispatch: due private replies, follow-ups and public replies, recovery of stopped runs+ -> every 5 minutes, off the quarter: reconcile: expire overdue jobs, look for lost replies (conversations for private+ ones, the comment's replies for public ones), report queue health-> daily (0 0 * * *): token refresh, then retention in batches```-The database is the queue: a matched comment's row in `automation_comments` is the job that sends its private reply, and a row in `automation_followups` is the job that answers a person's reply to a followers-only message. There is no Cloudflare Queue (ADR-040, ADR-043).+The database is the queue: a matched comment's row in `automation_comments` is the job that sends its private reply, a row in `automation_public_replies` is the job that posts its public reply, and a row in `automation_followups` is the job that answers a person's reply to a followers-only message. There is no Cloudflare Queue (ADR-040, ADR-043, ADR-044).## What Instagram Allows@@ -28,20 +32,23 @@ Checked against Meta's documentation on 2026-10-16:| Rule | Value | Source ||---|---|---|| API setup | Instagram API with Instagram Login (`graph.instagram.com`), the setup Twiligent already connects with | Instagram Platform overview |-| Permissions | `instagram_business_basic`, `instagram_business_manage_comments` (comments webhook and private replies), `instagram_business_manage_messages` (messages webhook, follow-ups, follow checks, conversations); Twiligent's OAuth already asks for all three | Private replies, webhook fields, User Profile API |+| Permissions | `instagram_business_basic`, `instagram_business_manage_comments` (comments webhook, private replies, public replies and reading a comment's replies), `instagram_business_manage_messages` (messages webhook, follow-ups, follow checks, conversations); Twiligent's OAuth already asks for all three | Private replies, webhook fields, User Profile API || Access level | Advanced Access for the `comments` and `messages` webhook fields; Business verification for production; the app must be Live | Webhooks setup || Accounts | Professional (Business or Creator) accounts only; the account must be public, since private accounts get no comment notifications | Webhooks setup || Replies per comment | One private reply, text only in the documented request; a follow-up only after the person replies, within 24 hours | Private replies || Reply window | 7 days after the comment (Live comments: only during the broadcast, not supported here) | Private replies || Follow status | `is_user_follow_business` from the User Profile API, only after the person has sent the account a message (or tapped an icebreaker or persistent menu); before that Instagram answers "User consent is required to access user profile" | User Profile API || Private reply rate | 750 an hour per professional account for posts and reels | Messenger Platform rate limits |+| Public replies | `POST /<comment-id>/replies` with `message` answers the new reply's `id`. Only top-level comments take replies; a reply to a reply lands in the top-level thread. Hidden comments and comments on live video cannot be replied to | IG Comment Replies, Comment Moderation |+| Reading replies | `GET /<comment-id>/replies` lists a comment's replies; a deleted comment's cannot be read | IG Comment Replies |+| Public reply rate | No separate number: comment calls count against the Business Use Case limit of 4,800 calls times the account's impressions in 24 hours, shared with insights. Instagram blocks accounts that comment like a bot (code 368) without publishing a threshold | Instagram Platform overview || Send API rate | 300 calls a second per account for text and links (follow-ups) | Messenger Platform rate limits || Conversations API rate | 2 calls a second per account | Messenger Platform rate limits || Message size | Text up to 1,000 bytes | Messaging API || Webhook retries | Retried with decreasing frequency for 36 hours until a 200; duplicates must be handled | Webhooks setup || Webhook fields | Every field selected for the app reaches every connected account; fields cannot be chosen per account | Webhooks setup |-The general Instagram Platform call quota is a different limit from the 750 private replies an hour, and neither is a daily DM allowance. Twiligent's own limits stay below them and are configurable.+The general Instagram Platform call quota is a different limit from the 750 private replies an hour, and neither is a daily DM allowance. Twiligent's own limits stay below them and are configurable. Because Meta publishes no safe pace for public replies, Twiligent keeps its own: 60 an hour per account by default, rotating wordings, and one public reply per person and post a day.## Setup: Getting Comments and Messages to the Worker@@ -61,13 +68,13 @@ Signatures: Instagram Login apps sign with the Instagram app secret (`INSTAGRAM_- other fields and malformed entries are counted as unsupported and dropped.3. `automationWebhook.ingest()` groups the comments by Instagram account id and calls `automation_rules_for_ig_user` once per account: the enabled rules of every connected Twiligent account with that `igUserId`, oldest account first. An account with no enabled rule stores nothing.4. Each comment is classified:- - the account's own comment: `ignored`, reason `own_comment`+ - the account's own comment: `ignored`, reason `own_comment`. This also keeps the account's public replies, which Meta delivers back as comments, from being answered- no text: `ignored`, `no_text`- no rule answers it: `ignored`, `no_match`, stored without its text or author- - a rule answers it: `queued`, with the rule, the author and the text (at most 2,200 characters)-5. `insertMany()` upserts all of them with `ignoreDuplicates` on the unique `(ig_user_id, comment_id)`, so a notification Meta delivers again inserts nothing; only the new rows come back.+ - a rule answers it: `queued` (or `skipped` with reason `private_reply_off` when the rule sends no private reply), with the rule, the author and the text (at most 2,200 characters). When the rule posts a public reply, one of its texts is picked by a hash of the comment id, so every copy of the notification and every check agree on the words+5. `store()` calls `store_automation_comments` once: in one transaction it inserts the comments with `on conflict do nothing` on the unique `(ig_user_id, comment_id)`, then a public reply job for each comment whose rule asks for one, joined to the comment as stored and only while the same rule answers it, with `on conflict do nothing` on the unique `automation_comment_id`. A notification Meta delivers again inserts nothing; only the new comment ids and public reply ids come back.6. Message events are grouped by account, and `automation_followups_for_messages` runs once per account. It makes a follow-up for a sender whose followers-only reply was accepted in the last 7 days and still waits for them (`gate_status = 'awaiting_reply'`, a minute of slack for the two clocks). A message Meta delivers again inserts nothing (`unique (ig_user_id, trigger_message_id)`), and a second message while a follow-up is open inserts nothing (one open follow-up per comment). Messages from anyone else are not kept.-7. The controller answers `200 {"success":true}` and hands the new reply ids, then the new follow-up ids, to `inBackground()`, which builds services with their own 25 second deadline (the request's signal ends with the response).+7. The controller answers `200 {"success":true}` and hands the new private reply ids, the new follow-up ids and the new public reply ids, in that order, to `inBackground()`, which builds services with their own 25 second deadline (the request's signal ends with the response). The three runs share the background work's subrequests and its 20 seconds.If storing fails, the request fails with 5xx, and Meta delivers the notification again later. Nothing is acknowledged that is not stored.@@ -81,7 +88,8 @@ If storing fails, the request fails with 5xx, and Meta delivers the notification- `any`: every comment with text answers, emoji included. Such a rule has no keywords (`keywordsProblem` in `lib/automationRules.ts`, and a check constraint).- A rule covers every post when `media_ids` is empty, or only the listed posts. A comment never triggers a rule meant for another post.- When several rules could answer, the most specific one does: rules for this post before rules for every post, and in each group keyword rules before any-comment rules; then the oldest. One rule answers a comment, and a comment is one row, so a comment never gets two private replies.-- `POST /api/automations/test` runs the same matching on a sample comment and returns the composed first message; it stores and sends nothing.+- One rule answers a comment, with its private reply, its public reply or both; a comment never gets two public replies.+- `POST /api/automations/test` runs the same matching on a sample comment and returns the composed first private message; it stores and sends nothing.## Delivery of Private Replies (`backend/services/automationProcessor.ts`)@@ -105,8 +113,8 @@ A database error on one job is logged and the run moves on; that job's claim or| Run | Subrequests | Time to start sends ||---|---|---|| Webhook, after the response | 50, less 10 for the request's own middleware, less the intake's queries | 20 seconds |-| Dispatch, every minute | 50 for replies; follow-ups get what replies did not use | 50 seconds |-| Retry from the activity list | 40 | 20 seconds |+| Dispatch, every minute | 39 for private replies, keeping 11 for public replies; follow-ups get what private replies did not use, public replies the rest | 50 seconds, shared in that order |+| Retry from the activity list (private or public) | 40 | 20 seconds |The claim takes only as many jobs as the budget pays for (one for the claim, one spare, three per reply). When time runs short or the run is cancelled, it hands every job it has not started back in one update (`returnUnstarted`: `processing` to `queued`, due at once), so they go out on the next run instead of waiting for the 20 minute lease.@@ -129,6 +137,33 @@ The claim takes only as many jobs as the budget pays for (one for the claim, oneA wait that would end after the 7 day window makes the comment `expired` instead.+## Public Replies (`backend/services/automationPublicReplyProcessor.ts`)++A public reply is its own job in `automation_public_replies`, created with its comment at intake. It follows the same claim, check, reserve, send and finish steps as a private reply, and never reads or changes the comment's private reply.++1. **Claim** (`claim_automation_public_replies`): the same loose index scan, turns between accounts and `FOR UPDATE SKIP LOCKED` as private replies. Accounts that are paused, or whose public replies are cooling down (`public_cooldown_until`) or at their hourly limit (`public_limited_until`), are left out; a private reply cooldown does not hold public replies. A `sending` reply older than 20 minutes becomes `needs_review` with reason `interrupted`.+2. **Check** (`publicReadinessPlan`): expired after the comment's 7 days, the rule or its public reply turned off (`skipped`), no token (`failed`).+3. **Reserve** (`reserve_automation_public_reply`): one transaction under its own advisory lock, so public and private reservations never wait on each other. A paused account holds it; a public cooldown waits for it; the same person already got a public reply on the same post in the last day (a reply sending, posted or for review) skips it with `recipient_limit`, which also ends a loop with another account's automation; then the account's hourly limit, counting public reply attempts only (`AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT`, default 60, at most 200). The attempt is recorded with kind `public_reply` and the digest of the text before the request leaves.+4. **Send** (`replyToComment`): `POST https://graph.instagram.com/v25.0/<comment-id>/replies` with `{ message }` and the token as a Bearer header, 10 second timeout, never repeated inside the call. It counts as posted only when Instagram answers with the new reply's `id`.+5. **Finish** (`finish_automation_public_reply`): the outcome on the attempt and the reply in one transaction, the reply's id, and a cooldown on the account's public replies, or a hold on the whole account when Instagram refused its token.++| Instagram's answer | Public reply | Attempt | Account |+|---|---|---|---|+| 200 with `id` | `accepted` (Posted), `reply_id` kept | `accepted` | |+| 200 without `id`, timeout, connection lost, unreadable 200 | `needs_review`, reason `no_answer` | `ambiguous` | |+| Code 100 with subcode 33 (the comment is deleted or cannot be seen) | `skipped` | `rejected` | |+| Rate limit codes or HTTP 429 | `retry_wait` until the cooldown ends | `rate_limited` | public cooldown from `X-Business-Use-Case-Usage`, else 15 minutes |+| Code 368 (temporarily blocked) | `retry_wait` | `rejected` | 24 hour public cooldown; private replies go on |+| Codes 1, 2 or HTTP 5xx | `retry_wait` with the same backoff; `failed` after 5 tries | `rejected` | |+| Token or permission refused | back to `queued`, held | `rejected` | paused with the reason |+| Any other error | `failed`, with Instagram's message | `rejected` | |++**Lost answers.** Unlike a private reply, a public reply can be looked for reliably: `GET /<comment-id>/replies?fields=id,text,timestamp,from`, up to two pages of 50. The reconcile runs check up to five a run, 5 minutes after the attempt and then every 5 minutes, three times at most:++- A reply from the account with the same sha-256 digest, at or after the attempt, marks it `accepted` with reason `confirmed` and its id.+- Missing on two checks, with every reply read each time: it goes back in the queue once (`resend_after_check`), and the dispatch posts it again. The reconciler itself never posts.+- A second lost answer, a page left unread, or a read Instagram refuses: it stays `needs_review` with a note, and a person decides.+## Followers-Only Replies (`backend/services/automationFollowupProcessor.ts`)**Status: in testing.** The flow is covered by tests with fakes and a local database, but it has not been tried with a real account. It depends on Meta sending the account's `messages` events, which may need Advanced Access for `instagram_business_manage_messages`; this instance runs on Standard Access. The app and the docs label it as testing, and it may or may not work.@@ -158,11 +193,12 @@ Nothing about the follow is stored except the follow-up's outcome; the person's## Duplicates, Ambiguity and Reconciliation-- A notification Meta delivers twice is stored once: `unique (ig_user_id, comment_id)` for comments, `unique (ig_user_id, trigger_message_id)` for messages.+- A notification Meta delivers twice is stored once: `unique (ig_user_id, comment_id)` for comments, `unique (automation_comment_id)` for public replies, `unique (ig_user_id, trigger_message_id)` for messages.+- A private reply and a public reply are separate rows with separate attempts. Retrying one requeues only that row; a failure, cooldown or review of one never sends the other again.- A comment repeated inside one notification is stored once, and several messages from one person make one open follow-up.- Two runs never send the same job: the claim locks rows, and the reservation only moves a job this run holds. The every-minute dispatch, the webhook's own runs and a retry can overlap safely.- A job a run claimed but did not start is handed back at once; one whose run died before the request left is claimed again after its 20 minute lease.-- A send that may have reached Instagram (timeout, lost connection, a run that stopped while `sending`) is never retried on its own. It shows as Needs review.+- A private send that may have reached Instagram (timeout, lost connection, a run that stopped while `sending`) is never retried on its own. It shows as Needs review. A public reply in the same state is retried only after the comment's replies were read twice and it was in neither (see Public Replies).- **Reconciliation.** The five minute runs that do not publish look for up to four Needs review replies in the conversation on Instagram (`automationReconciler`, Conversations API: the conversation with the commenter, then its latest messages). A message from the account with exactly the text that was sent (the same sha-256 digest), at or after the attempt (2 minutes of slack for the clocks), marks the reply `accepted` with reason `confirmed`, and a followers-only rule then starts waiting for the person. A reply not found stays Needs review with a note. Each is checked at most three times, 30 minutes apart, starting 5 minutes after the attempt. A conversation Instagram will not show counts as a check with its reason. Replies sent before digests were kept are not guessed at. The reconciler only reads from Instagram; it never sends.- A person decides the rest after checking the conversation. If they retry and the first reply did arrive, Instagram refuses a second private reply to the same comment (10900), and the comment is marked skipped.- Delivery is at least once into the queue and at most once to Instagram without a person's decision. Instagram reports acceptance, not delivery or reading, so the dashboard says "Accepted by Instagram" and never "Delivered".@@ -198,7 +234,17 @@ queued | retry_wait -> expired (the five minute expiry, without a claim)| `skipped` | Skipped | Rule off, recipient limit, or already answered || `expired` | Expired | The 7 days ran out first |-Follow-ups use the same statuses, without `ignored`. Retry on an accepted followers-only reply requeues its latest failed, skipped or review follow-up inside its 24 hours.+Follow-ups and public replies use the same statuses, without `ignored`. Retry on an accepted followers-only reply requeues its latest failed, skipped or review follow-up inside its 24 hours. A comment whose rule sends no private reply is `skipped` with reason `private_reply_off`, shown as Off, and its private reply cannot be retried.++| Public reply status | Shown as | Meaning |+|---|---|---|+| `queued`, `retry_wait` | Waiting, Held, Trying again | Waiting to post |+| `processing`, `sending` | Posting | A run holds it |+| `accepted` | Posted | Instagram answered with the reply's id |+| `needs_review` | Checking | It may have been posted; the reconcile runs look for it |+| `failed`, `skipped`, `expired` | Failed, Skipped, Expired | As for private replies; skipped also covers a deleted comment and the one-per-post limit |++`POST /api/automations/activity/:id/public-reply/retry` requeues a failed, skipped or review public reply inside the comment's 7 days and starts it at once; the private reply is untouched.## Limits and Controls@@ -209,16 +255,20 @@ Follow-ups use the same statuses, without `ignored`. Retry on an accepted follow| Instagram account, per hour | 200 private replies (Instagram allows 750) | `AUTOMATION_ACCOUNT_HOURLY_LIMIT`, at most 750 || Rule, per hour | none | the rule's hourly limit, 1 to 750 || Person, per day per account | 3 replies | `AUTOMATION_RECIPIENT_DAILY_LIMIT` |+| Instagram account, public replies per hour | 60 | `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT`, at most 200 |+| Person, public replies per post per day | 1 | fixed, in `reserve_automation_public_reply` |+| Public reply wordings per rule | 5, each at most 300 characters, 4 hashtags and 1 link | `lib/automationPublicReply.ts` || Replies per webhook request or dispatch | 10 | `AUTOMATION_BATCH_SIZE`, at most 15 || Reminders per followers-only reply | 2 | `MAX_FOLLOW_REMINDERS` in `lib/automationDelivery.ts` |-Follow-ups count toward none of the hourly reply limits; they respect account pauses and cooldowns.+Follow-ups count toward none of the hourly reply limits; they respect account pauses and cooldowns. Public replies count only toward their own hourly limit, and private replies never count toward it. The 300 character, 4 hashtag and 1 link bounds are Twiligent's own: Instagram's older API refused comments past them, and short, varied replies are less likely to look like spam.| Control | Effect ||---|---|| `AUTOMATION_PAUSED=true` | Nothing is sent on the instance; comments and answers are still stored and matched || Pause an account (Replies switch) | Its replies and follow-ups wait in place and go out when resumed, within Instagram's windows |-| Turn a rule off | New comments stop matching it; its waiting replies and follow-ups are skipped |+| Turn a rule off | New comments stop matching it; its waiting replies, follow-ups and public replies are skipped |+| Turn a rule's private or public reply off | That reply's waiting jobs are skipped; the other one goes on || Retry an item | Puts a failed, skipped or review item, or its failed follow-up, back in the queue and starts it at once |The batch cap of 15 comes from the Workers Free plan's 50 subrequests per invocation: each reply costs three (reserve, send, finish) and each follow-up four (the follow check too), plus the claim and the intake queries.@@ -229,12 +279,12 @@ The batch cap of 15 comes from the Workers Free plan's 50 subrequests per invoca| Signal | Where ||---|---|-| Each reply and follow-up settled: ids, status, outcome, error codes | `automation reply settled`, `automation follow-up settled` log lines |+| Each reply, follow-up and public reply settled: ids, status, outcome, error codes | `automation reply settled`, `automation follow-up settled`, `automation public reply settled` log lines || A dispatch that claimed something: counts by outcome | `automation dispatch` |-| Each reconcile run: expired counts, review results, queue health (due, oldest due, waiting, stale, needs review, follow-ups due, paused and limited accounts) | `automation reconcile` |-| The queue falling behind: the oldest due reply waited over 10 minutes, or jobs are held by stopped runs | one `automation queue behind: ...` warning per run, so an incident does not flood the logs |+| Each reconcile run: expired counts, review results for both kinds (public: found, not found, failed, sent again), queue health (due, oldest due, waiting, stale, needs review, follow-ups due, public replies due, stale and checking, paused and limited accounts) | `automation reconcile` |+| The queue falling behind: the oldest due reply or public reply waited over 10 minutes, or jobs are held by stopped runs | one `automation queue behind: ...` warning per run, so an incident does not flood the logs || Every non-dispatch cron run and its duration | `cron run finished` |-| Accounts at their limit, cooling down, held, or without message events | the Instagram accounts card on the Automations page |+| Accounts at their limit, cooling down, held, or without message events, and public replies cooling down or at their limit | the Instagram accounts card on the Automations page |Logs carry ids, statuses and error codes, never tokens, secrets, comment text or message text.@@ -252,12 +302,13 @@ Logs carry ids, statuses and error codes, never tokens, secrets, comment text or| Unmatched comments | 90 days, without text or author | Same || Reply attempts, with the digest of the text sent | With their comment | With their comment || Follow-ups: sender id, message id, outcome; never the message text | With their comment | With their comment |+| Public replies: the text posted, status, reply id, attempts | With their comment | With their comment || Rules, account controls | Until deleted | With the account || Audit events | 1 year | Daily retention; with the user |## Costs-Everything runs on the existing Worker, Supabase project and Workers Free plan; nothing new is billed. Each comment costs one webhook request and, when matched, about four database calls and one Instagram request. Each follow-up costs one more Instagram call for the follow check. The Workers Free plan allows 100,000 requests a day, and cron runs count as requests: the every-minute dispatch is 1,440 a day, the five minute trigger 288 and the daily one 1, about 1.7% together. With the `messages` field selected, every direct message to a connected account is also a request. Past the daily allowance the free plan refuses requests rather than billing them, and Meta retries a refused webhook for 36 hours. Cloudflare Queues, KV and D1 are not used. Recheck Cloudflare's and Supabase's pricing pages before relying on these numbers.+Everything runs on the existing Worker, Supabase project and Workers Free plan; nothing new is billed. Each comment costs one webhook request and, when matched, about four database calls and one Instagram request, plus three database calls and one Instagram request for a public reply. Each follow-up costs one more Instagram call for the follow check. The Workers Free plan allows 100,000 requests a day, and cron runs count as requests: the every-minute dispatch is 1,440 a day, the five minute trigger 288 and the daily one 1, about 1.7% together. With the `messages` field selected, every direct message to a connected account is also a request. Past the daily allowance the free plan refuses requests rather than billing them, and Meta retries a refused webhook for 36 hours. Cloudflare Queues, KV and D1 are not used. Recheck Cloudflare's and Supabase's pricing pages before relying on these numbers.## Files@@ -267,10 +318,10 @@ Everything runs on the existing Worker, Supabase project and Workers Free plan;| Middleware | `middleware/metaWebhook.ts` || Controllers | `controllers/instagramWebhookController.ts`, `controllers/automationController.ts`, `inBackground()` in `controllers/http.ts` || Validators | `validators/instagramWebhookValidators.ts`, `validators/automationValidators.ts` |-| Services | `services/automationWebhookService.ts`, `services/automationProcessor.ts`, `services/automationFollowupProcessor.ts`, `services/automationReconciler.ts`, `services/automationService.ts`, `services/retentionService.ts` |+| Services | `services/automationWebhookService.ts`, `services/automationProcessor.ts`, `services/automationFollowupProcessor.ts`, `services/automationPublicReplyProcessor.ts`, `services/automationReconciler.ts`, `services/automationService.ts`, `services/retentionService.ts` || Cron | `jobs/scheduled.ts` |-| Platform | `services/instagram/instagramMessaging.ts` |-| Rules | `lib/automationMatching.ts`, `lib/automationRules.ts`, `lib/automationDelivery.ts`, `lib/automationReview.ts`, `lib/automationHealth.ts`, `lib/metaWebhookSignature.ts` |-| Repositories | `repositories/automationRuleRepository.ts`, `automationCommentRepository.ts`, `automationFollowupRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` |-| Database | `supabase/migrations/20261016100000` to `20261016103500` and `20261016120000` to `20261016122500`, one entity per file |+| Platform | `services/instagram/instagramMessaging.ts`, `services/instagram/instagramComments.ts` |+| Rules | `lib/automationMatching.ts`, `lib/automationRules.ts`, `lib/automationDelivery.ts`, `lib/automationPublicReply.ts`, `lib/automationReview.ts`, `lib/automationHealth.ts`, `lib/metaWebhookSignature.ts` |+| 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/` |diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 916038c..deecdff 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -2,7 +2,7 @@## Overview-Supabase (PostgreSQL 17) with ten application tables: the four original ones, the five comment automation tables (`automation_accounts`, `automation_rules`, `automation_comments`, `automation_followups`, `automation_attempts`) and `audit_events`. Every table has `user_id` (uuid) referencing `auth.users`, so rows belong to one user, and `created_at` and `updated_at` timestamps.+Supabase (PostgreSQL 17) with eleven application tables: the four original ones, the six comment automation tables (`automation_accounts`, `automation_rules`, `automation_comments`, `automation_followups`, `automation_public_replies`, `automation_attempts`) and `audit_events`. Every table has `user_id` (uuid) referencing `auth.users`, so rows belong to one user, and `created_at` and `updated_at` timestamps.The backend uses the **service-role key** and enforces isolation by always appending `.eq('user_id', userId)` on user-scoped queries. The `userId` comes exclusively from the verified JWT - never from request input.@@ -293,7 +293,7 @@ Data is fetched on create and on manual refresh only. Not re-fetched on every GE## Comment Automation Tables-The data flow is in `docs/architecture/data-flows/AUTOMATION.md`. Every table references its account with the composite `(account_id, user_id)` foreign key to `accounts (id, user_id)` on delete cascade, so removing an Instagram account removes its rules, controls, comments, follow-ups and attempts.+The data flow is in `docs/architecture/data-flows/AUTOMATION.md`. Every table references its account with the composite `(account_id, user_id)` foreign key to `accounts (id, user_id)` on delete cascade, so removing an Instagram account removes its rules, controls, comments, follow-ups, public replies and attempts.### Table: `automation_accounts`@@ -310,6 +310,9 @@ One row per Instagram account whose automation was paused, subscribed or cooled| `subscribed_at` | timestamptz | | When Instagram confirmed it sends this account's comments to the webhook || `subscribed_fields` | text[] | | The webhook fields Instagram confirmed (`comments`, and `messages` for followers-only rules); null for a subscription made before fields were recorded, which asked for comments only || `limited_until` | timestamptz | | Set by `reserve_automation_send` when the account reached its hourly reply limit; the claim leaves the account's jobs alone until then |+| `public_cooldown_until` | timestamptz | | No public reply is posted before this time; set from Instagram rate limits and blocks on public replies, only ever moved later. Private replies ignore it |+| `public_cooldown_reason` | text | at most 200 characters | Shown on the page |+| `public_limited_until` | timestamptz | | Set by `reserve_automation_public_reply` when the account reached its hourly public reply limit || `created_at`, `updated_at` | timestamptz | not null, default now() | |### Table: `automation_rules`@@ -323,11 +326,14 @@ One row per Instagram account whose automation was paused, subscribed or cooled| `match_mode` | text | `contains`, `exact` or `any`, default `contains` | `any` answers every comment with text || `case_sensitive` | boolean | not null, default false | || `media_ids` | text[] | not null, default `{}`, at most 50 | Empty means every post and reel |-| `reply_text` | text | 1 to 1,000 characters | The service also checks text plus link against Instagram's 1,000 bytes |+| `private_reply_enabled` | boolean | not null, default true | The rule sends a private reply; at least one of the two replies is on (`automation_rules_actions_check`) |+| `reply_text` | text | 1 to 1,000 characters; may be empty while `private_reply_enabled` is false | The service also checks text plus link against Instagram's 1,000 bytes || `link_url` | text | null or `^https://` | Added on its own line after the text || `enabled` | boolean | not null, default false | |-| `hourly_limit` | integer | null or 1 to 750 | Replies an hour for this rule |-| `require_follow` | boolean | not null, default false | Followers-only: the private reply asks the person to follow and reply, and the reply and link go out once Instagram says they follow |+| `public_reply_enabled` | boolean | not null, default false | The rule posts a public reply under the comment |+| `public_reply_texts` | text[] | not null, default `{}`, at most 5; at least 1 while `public_reply_enabled` | The wordings; one is picked per comment. The Worker keeps each to 300 characters, 4 hashtags and 1 link |+| `hourly_limit` | integer | null or 1 to 750 | Private replies an hour for this rule |+| `require_follow` | boolean | not null, default false; needs `private_reply_enabled` | Followers-only: the private reply asks the person to follow and reply, and the reply and link go out once Instagram says they follow || `follow_prompt_text` | text | null or 1 to 1,000 characters; required when `require_follow` | The private reply of a followers-only rule || `not_following_text` | text | null or 1 to 1,000 characters; required when `require_follow` | The reminder for someone who replies but does not follow || `created_at`, `updated_at` | timestamptz | not null, default now() | |@@ -358,7 +364,7 @@ Every comment the webhook delivered for an account with an enabled rule. A match| `notified_at`, `expires_at` | timestamptz | not null | When Meta sent it, and 7 days later || `created_at`, `updated_at` | timestamptz | not null, default now() | |-`status` is one of `ignored`, `queued`, `processing`, `retry_wait`, `sending`, `accepted`, `failed`, `needs_review`, `skipped`, `expired`. The lifecycle is in `AUTOMATION.md`.+`status` is one of `ignored`, `queued`, `processing`, `retry_wait`, `sending`, `accepted`, `failed`, `needs_review`, `skipped`, `expired`. The status is the private reply's; a comment whose rule sends no private reply is `skipped` with reason `private_reply_off`. The lifecycle is in `AUTOMATION.md`.### Table: `automation_followups`@@ -381,9 +387,32 @@ The message sent after a person answered a followers-only private reply: the rep| `window_expires_at` | timestamptz | not null | The person's message time plus 24 hours, Instagram's standard messaging window || `created_at`, `updated_at` | timestamptz | not null, default now() | |+### Table: `automation_public_replies`++The public reply under a matched comment, one per comment, created with the comment in one transaction. Each row is a job like a comment row, tracked apart from the private reply.++| Column | Type | Constraints | Description |+|---|---|---|---|+| `id` | text | primary key | `newRowId()`, made by the Worker before the insert |+| `user_id`, `account_id` | uuid, text | not null, composite foreign key | |+| `automation_comment_id` | text | not null, references `automation_comments` on delete cascade; `unique` | The comment answered; refuses a second public reply job for it |+| `rule_id` | text | references `automation_rules` on delete set null | |+| `ig_user_id`, `comment_id` | text | not null | The professional account and the Instagram comment replied to |+| `media_id`, `from_id` | text | | The post and the commenter, for the limit of one public reply per person and post a day |+| `reply_text` | text | not null, 1 to 2,200 characters | The wording picked when the comment arrived |+| `status` | text | the comment statuses except `ignored` | |+| `status_reason`, `error_message` | text | `error_message` at most 500 characters | |+| `attempts` | integer | not null, default 0, at least 0 | |+| `next_attempt_at` | timestamptz | required while `queued` or `retry_wait` | |+| `claimed_at` | timestamptz | | The lease is 20 minutes |+| `reply_id`, `accepted_at` | text, timestamptz | | The id Instagram gave the reply, and when |+| `review_checks`, `review_checked_at` | integer, timestamptz | `review_checks` not null, default 0 | Looks at the comment's replies for a reply whose answer was lost |+| `expires_at` | timestamptz | not null | The comment's 7 days |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |+### Table: `automation_attempts`-One row per message request sent to Instagram. The hourly and daily limits count the private reply rows.+One row per message or public reply request sent to Instagram. The private reply limits count the `private_reply` rows, the public reply limit the `public_reply` rows.| Column | Type | Constraints | Description ||---|---|---|---|@@ -393,9 +422,10 @@ One row per message request sent to Instagram. The hourly and daily limits count| `rule_id` | text | references `automation_rules` on delete set null | || `recipient_id` | text | | The commenter || `outcome` | text | `sending`, `accepted`, `rejected`, `rate_limited`, `ambiguous` | `sending` while the request is out |-| `kind` | text | not null, default `private_reply`; `private_reply` or `followup` | Follow-ups use the Send API, so the private reply limits leave them out |+| `kind` | text | not null, default `private_reply`; `private_reply`, `followup` or `public_reply` | Follow-ups use the Send API and public replies the comment endpoint, so each kind's limits count only their own || `followup_id` | text | references `automation_followups` on delete cascade; set exactly when `kind` is `followup` | |-| `message_digest` | text | | sha-256 of the text sent, to recognise a lost reply in the conversation |+| `public_reply_id` | text | references `automation_public_replies` on delete cascade; set exactly when `kind` is `public_reply` | |+| `message_digest` | text | | sha-256 of the text sent, to recognise a lost reply in the conversation or among the comment's replies || `error_code`, `error_subcode`, `http_status` | integer | | Instagram's answer || `started_at`, `finished_at` | timestamptz | `started_at` not null, default now() | || `created_at`, `updated_at` | timestamptz | not null, default now() | |@@ -410,13 +440,13 @@ Who connected, reconnected or removed an account, changed a rule, paused or subs|---|---|---|---|| `id` | text | primary key | `newRowId()` || `user_id` | uuid | not null, references `auth.users` on delete cascade | |-| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried` |+| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried`, `automation_public_reply.retried` || `subject_type` | text | `account`, `automation_rule`, `automation_account`, `automation_comment` | || `subject_id` | text | | || `details` | jsonb | not null, default `{}`, an object | Small facts such as the platform or the changed field names; never tokens or comment text || `created_at`, `updated_at` | timestamptz | not null, default now() | |-Retention: the daily cron deletes comments (and their attempts) older than 90 days and audit events older than 365 days.+Retention: the daily cron deletes comments (and their attempts, follow-ups and public replies) older than 90 days and audit events older than 365 days.---@@ -448,6 +478,11 @@ An index exists because a frequent query filters or orders on its columns. Each| `automation_followups_due_idx`, `automation_followups_claimed_idx` | `(account_id, next_attempt_at)` and `(claimed_at)`, partial like the comment ones | `claim_automation_followups`, the expiry | || `automation_followups_open_comment_key` | unique `(automation_comment_id) where status in ('queued', 'processing', 'retry_wait', 'sending')` | One open follow-up per comment | Several messages from one person make one answer || `automation_followups_comment_id_idx` | `(automation_comment_id, created_at)` | The cascade from a comment; the latest follow-up in the activity list | |+| `automation_public_replies_due_account_idx`, `automation_public_replies_claimed_idx` | `(account_id, next_attempt_at)` and `(claimed_at)`, partial like the comment ones | `claim_automation_public_replies`, the expiry, the queue health | |+| `automation_public_replies_needs_review_idx` | `(review_checked_at nulls first, updated_at) where status = 'needs_review'` | `automation_public_review_candidates`, the queue health | Partial |+| `automation_public_replies_recipient_idx` | `(account_id, from_id, media_id, created_at) where status in ('sending', 'accepted', 'needs_review')` | `reserve_automation_public_reply`: one public reply per person and post a day | Partial: only replies that went out or may have |+| `automation_public_replies_user_created_idx` | `(user_id, created_at)` | `automation_stats` | |+| `automation_attempts_public_reply_idx` | `automation_attempts (public_reply_id) where public_reply_id is not null` | The cascade from a public reply; the review's attempt | || `automation_comments_user_id_created_at_idx` | `automation_comments (user_id, created_at desc)` | `automationComments.listForUser`, `automation_stats` | || `automation_comments_rule_id_idx` | `automation_comments (rule_id) where rule_id is not null` | Removing a rule (set null), stats by rule | || `automation_comments_created_at_idx` | `automation_comments (created_at)` | `purge_automation_comments`: the oldest comments first, a batch at a time | |@@ -480,8 +515,9 @@ Every function sets `search_path = ''` and names its tables with the schema. Fun| `merge_scheduled_post(p_id, p_user_id, p_patch, p_status, p_scheduled_at, p_only_status)` | sql | Merges `p_patch` into `data` and sets `status` and `scheduled_at` when given, in one UPDATE. `p_only_status` limits the update to a post still in that status || `merge_tracked_post_data(p_id, p_user_id, p_patch)` | sql | `data = coalesce(data, '{}') \|\| p_patch` on one tracked item |-| `automation_rules_for_ig_user(p_ig_user_id)` | sql, stable | The enabled rules of every connected account with that Instagram id, oldest account first |-| `claim_automation_comments(p_limit, p_per_account, p_lease_seconds, p_ids)` | plpgsql | Marks `sending` jobs past the lease `needs_review` (their attempts `ambiguous`), finds the accounts with waiting jobs, leaves out paused, cooling and limited ones, locks each account's oldest due jobs with `for update skip locked` as it reads them, and claims them with accounts taking turns. Returns each job with its rule's reply, its followers-only fields and the account's token |+| `automation_rules_for_ig_user(p_ig_user_id)` | sql, stable | The enabled rules of every connected account with that Instagram id, oldest account first, with their private and public reply settings |+| `store_automation_comments(p_comments)` | plpgsql | Inserts a webhook's comments (`on conflict do nothing`) and then a public reply job for each one whose rule asks for one, joined to the stored comment while the same rule answers it, in one transaction. Returns the new comment ids and statuses and the new public reply ids |+| `claim_automation_comments(p_limit, p_per_account, p_lease_seconds, p_ids)` | plpgsql | Marks `sending` jobs past the lease `needs_review` (their attempts `ambiguous`), finds the accounts with waiting jobs, leaves out paused, cooling and limited ones, locks each account's oldest due jobs with `for update skip locked` as it reads them, and claims them with accounts taking turns. Returns each job with its rule's reply, its followers-only fields and the account's token; `rule_enabled` is false once the rule or its private reply is off || `reserve_automation_send(p_id, p_attempt_id, p_global_limit, p_user_limit, p_account_limit, p_recipient_limit, p_message_digest)` | plpgsql | Under `pg_advisory_xact_lock`, checks pause, cooldown, the recipient's daily replies and the hourly limits per rule, account, user and instance, counting private replies only; a full account gets `limited_until`. On success moves the job to `sending` and inserts the attempt with the digest. Returns `outcome` and, for a full scope, `retry_at` || `finish_automation_send(p_id, p_attempt_id, p_status, p_outcome, ..., p_recipient_id, p_gate_status)` | plpgsql | Settles a `sending` job (or an interrupted one) and its attempt in one transaction, keeps the recipient and starts a followers-only wait, and sets the account's cooldown or hold when asked. Returns `false` and changes nothing when the job was already settled || `automation_followups_for_messages(p_ig_user_id, p_messages)` | sql | Inserts a follow-up for each message whose sender has a followers-only reply waiting for them (accepted in the last 7 days); returns the new ids. Duplicates and a second open follow-up insert nothing |@@ -490,10 +526,15 @@ Every function sets `search_path = ''` and names its tables with the schema. Fun| `finish_automation_followup(p_id, p_attempt_id, p_status, p_outcome, ..., p_gate_status, p_count_reminder)` | plpgsql | Settles a follow-up and its attempt, updates the comment's wait and reminder count, and the account's cooldown or hold || `automation_review_candidates(p_limit, p_settle_seconds, p_max_checks, p_recheck_seconds)` | sql, stable | Needs review replies ready to be looked for in their conversation, with the attempt's time and digest and the token || `record_automation_review(p_id, p_found, p_message_id, p_sent_at, p_note)` | plpgsql | Found: the comment and its ambiguous attempt become accepted. Not found: one more check with the note. Changes only a comment still waiting for review |-| `expire_automation_jobs(p_limit)` | sql | Expires up to `p_limit` overdue replies and up to `p_limit` overdue follow-ups, skipping rows a run holds; returns both counts |+| `claim_automation_public_replies(p_limit, p_per_account, p_lease_seconds, p_ids)` | plpgsql | The public reply claim: lease recovery (`sending` past the lease becomes `needs_review`, reason `interrupted`), paused accounts and public cooldowns and limits left out, `for update skip locked`, turns between accounts. Returns each reply with its text, whether the rule and its public reply are on, and the token |+| `reserve_automation_public_reply(p_id, p_attempt_id, p_account_limit, p_message_digest)` | plpgsql | Under its own advisory lock, checks pause, the public cooldown, one public reply per person and post a day, and the account's hourly public limit (marking `public_limited_until`); on success moves the reply to `sending` and inserts a `public_reply` attempt with the digest |+| `finish_automation_public_reply(p_id, p_attempt_id, p_status, p_outcome, ..., p_reply_id, ...)` | plpgsql | Settles a `sending` (or interrupted) public reply and its attempt, keeps the reply id, and sets the public cooldown or the account's hold |+| `automation_public_review_candidates(p_limit, p_settle_seconds, p_max_checks, p_recheck_seconds)` | sql, stable | Public replies of unknown outcome ready to be looked for, with the latest ambiguous attempt's time and digest, the token, and how many of its sends had no answer |+| `record_automation_public_review(p_id, p_found, p_reply_id, p_sent_at, p_note, p_resend)` | plpgsql | Found: the reply and its latest ambiguous attempt become accepted. `p_resend`: back to `queued` once, after the replies were read. Otherwise one more check with the note |+| `expire_automation_jobs(p_limit)` | sql | Expires up to `p_limit` overdue replies, follow-ups and public replies each, skipping rows a run holds; returns the three counts || `purge_automation_comments(p_before, p_limit)` | sql | Deletes up to `p_limit` comments created before `p_before`, oldest first; returns the count |-| `automation_queue_health(p_lease_seconds)` | sql, stable | Due and waiting jobs, the oldest due time, stale claims, replies needing review, follow-ups due, paused and limited accounts, each through its partial index |-| `automation_stats(p_user_id, p_from, p_to, p_account_id, p_rule_id)` | sql, stable | Comment counts by status and attempt counts by outcome for a period, as jsonb |+| `automation_queue_health(p_lease_seconds)` | sql, stable | Due and waiting jobs, the oldest due time, stale claims, replies needing review, follow-ups due, public replies due, stale and needing review, paused and limited accounts, each through its partial index |+| `automation_stats(p_user_id, p_from, p_to, p_account_id, p_rule_id)` | sql, stable | Comment counts by status, public reply counts by status and attempt counts by outcome for a period, as jsonb |The merge functions return `true` when a row matched and `null` when none did. A null `p_user_id` is the cron form, which reaches any user's row; `merge_tracked_post_data` always needs a user. The merge is one statement, so two writers at the same moment (a token refresh and an analytics refresh on one account) never put an old value back.@@ -553,11 +594,11 @@ listForUser(userId) / findForUser(id, userId) / create(rule, userId) / updateForlistEnabledForInstagramUser(igUserId): Promise<WebhookRule[]> // webhook only - automation_rules_for_ig_user, every user// Automation comments (automationCommentRepository.ts)-insertMany(comments): Promise<NewAutomationComment[]> // webhook only - upsert, ignoring duplicates; returns the new ones+store(comments): Promise<StoredComments> // webhook only - store_automation_comments: comments and their public replies in one transaction; returns the new onesclaim(options) / reserve(id, attemptId, limits, digest?) / finish(id, attemptId, plan) / release(id, plan) / returnUnstarted(ids) // processor only, every userlistForUser(userId, filter) / findForUser(id, userId) / requeueForUser(id, userId) / releaseHeldForAccount(accountId, userId)statsForUser(userId, filter): Promise<AutomationStats> // automation_stats-expireDue(limit) / reviewCandidates(options) / recordReview(id, result) / health(leaseSeconds) // reconciliation only, every user+expireDue(limit) / reviewCandidates(options) / recordReview(id, result) / health(leaseSeconds) // reconciliation only, every user; expireDue also expires public repliespurgeCreatedBefore(cutoff, limit): Promise<number> // daily retention only, one batch per call// Automation follow-ups (automationFollowupRepository.ts)@@ -565,6 +606,11 @@ insertForMessages(igUserId, messages): Promise<string[]> // webhookclaim(options) / reserve(id, attemptId, kind, digest) / finish(id, attemptId, plan) / release(id, plan) / returnUnstarted(ids) // follow-up processor only, every userrequeueLatestForUser(commentRowId, userId): Promise<string | null>+// Automation public replies (automationPublicReplyRepository.ts)+claim(options) / reserve(id, attemptId, accountLimit, digest) / finish(id, attemptId, plan) / release(id, plan) / returnUnstarted(ids) // public reply processor only, every user+reviewCandidates(options) / recordReview(id, result) // reconciliation only, every user+requeueForUser(commentRowId, userId): Promise<string | null> / releaseHeldForAccount(accountId, userId)+// Automation account controls (automationAccountRepository.ts)listForUser(userId) / findForUser(accountId, userId) / setPausedForUser(accountId, userId, paused) / markSubscribedForUser(accountId, userId, fields)diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 364b3ea..3bd9b9f 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -17,7 +17,7 @@ The merge functions follow the same rule: the `...ForUser` repository methods paA scheduled post names the account it publishes to, and a tracked Reddit item names the account whose cookie reads it. Both are checked twice:1. **In the service.** `scheduledPostService.create` loads the account with `accounts.findForUser(accountId, userId)` and passes it to `publishableAccount()`: another user's account, a missing one or one that is not Instagram answers 404 `Instagram account not found`, and one with no token answers 400 `No Instagram access token stored - reconnect this account`. `trackedContentService.update` refuses an account on a YouTube item (400) and answers 404 `Reddit account not found` for an account that is not one of the user's Reddit accounts.-2. **In the database.** `scheduled_posts`, `tracked_posts` and the five automation tables reference `accounts (id, user_id)` with a composite foreign key, so a row whose `account_id` belongs to another user cannot be written, whatever the code does. A follow-up is created only by `automation_followups_for_messages`, which takes its user and account from the waiting comment, never from the message, so a message cannot reach another account's rule.+2. **In the database.** `scheduled_posts`, `tracked_posts` and the six automation tables reference `accounts (id, user_id)` with a composite foreign key, so a row whose `account_id` belongs to another user cannot be written, whatever the code does. A follow-up is created only by `automation_followups_for_messages`, which takes its user and account from the waiting comment, never from the message, so a message cannot reach another account's rule. A public reply is created only by `store_automation_comments`, which takes its user, account and comment from the stored comment row.An automation rule is created only after `accounts.findForUser(accountId, userId)` returns one of the user's Instagram accounts (404 otherwise), and a rule never moves to another account. Pausing, subscribing and retrying load the account or the item with the user's id first.@@ -53,7 +53,7 @@ The migrations in `supabase/migrations/` enforce this on every instance:The service-role key used by the Worker and the GitHub Actions scheduler bypasses row level security and keeps its grants. The frontend never queries tables directly (it uses Supabase only for Auth). `backend/tests/database/migrations.test.ts` fails if a migration creates a function without the revoke.-To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all ten tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments` and `POST /rest/v1/rpc/claim_automation_followups`. The manual check is in `docs/workflows/TESTING.md`.+To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all eleven tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments`, `POST /rest/v1/rpc/claim_automation_followups` and `POST /rest/v1/rpc/claim_automation_public_replies`. The manual check is in `docs/workflows/TESTING.md`.### What was wrong before@@ -83,7 +83,7 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live- Graph API calls: `services/instagram/instagramApi.ts`, `instagramMedia.ts` and `instagramPublishing.ts` (the token is passed in as `access_token`)- Obtaining and storing tokens: `services/instagram/instagramTokens.ts` (long-lived exchange and refresh), `services/instagram/instagramOAuth.ts` (OAuth code exchange), `services/instagramConnectService.ts` (OAuth connect), `services/accountService.ts` and `services/accountFactory.ts` (pasted tokens and new account rows)- Reading the stored token: `services/publishingService.ts` and `services/scheduledPublisher.ts` (publishing), `services/instagramAnalyticsService.ts` (Instagram analytics and media), `services/accountService.ts` (profile and token refresh), `services/tokenRefreshService.ts` (daily refresh), `services/overviewService.ts` (overview cache warm-up), `services/automationService.ts` (webhook subscription) and `services/automationProcessor.ts` (private replies, through `services/instagram/instagramMessaging.ts`, which sends it as a Bearer header)- - `claim_automation_comments`, `claim_automation_followups` and `automation_review_candidates` return the token to the Worker with each job; the functions are granted only to the service role. The follow check and the conversation read send it as a Bearer header or a query parameter of a Graph API call, and error messages pass through `redactUrls` before they are stored or logged+ - `claim_automation_comments`, `claim_automation_followups`, `claim_automation_public_replies`, `automation_review_candidates` and `automation_public_review_candidates` return the token to the Worker with each job; the functions are granted only to the service role. The public reply, the follow check, the conversation read and the comment replies read send it as a Bearer header or a query parameter of a Graph API call, and error messages pass through `redactUrls` before they are stored or logged4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning**If you add a route that returns account data, you must call `safeAccount()`.** Repositories return full accounts and there is no automatic stripping - it is an explicit step in controllers (and in the services that embed an account in a larger result).@@ -104,7 +104,7 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-liveWhen reviewing security, check these files:- `backend/middleware/auth.ts` - JWT verification-- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationReconciler.ts` and `retentionService.ts`. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address+- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationPublicReplyProcessor.ts`, `automationReconciler.ts` and `retentionService.ts`. `automationPublicReplyRepository.ts` follows the same split: `requeueForUser` and `releaseHeldForAccount` take the verified user, the claim, reservation, finish and review methods serve the dispatch and the reconcile. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address- `backend/middleware/authHook.ts` and `backend/lib/webhookSignature.ts` - the only thing that authenticates the public Send Email hook- `backend/middleware/metaWebhook.ts` and `backend/lib/metaWebhookSignature.ts` - the only thing that authenticates the public Instagram webhook- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or querydiff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex 269e610..362dc9e 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -132,6 +132,7 @@ deleteAutomationRule: (id: string) => request<SuccessMessageResponse>(`/automatitestAutomationRule: (data: AutomationTestRequest) => request<AutomationTestResponse>('/automations/test', { method: 'POST', body: JSON.stringify(data) }),getAutomationActivity: (query: URLSearchParams) => request<AutomationActivityResponse>(`/automations/activity?${query}`),retryAutomationActivity: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/retry`, { method: 'POST' }),+retryAutomationPublicReply: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/public-reply/retry`, { method: 'POST' }),getAutomationStats: (query: URLSearchParams) => request<AutomationStatsResponse>(`/automations/stats?${query}`),setAutomationAccountPaused: (accountId: string, paused: boolean) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify({ paused }) }),subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}/subscribe`, { method: 'POST' }),diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex 402fa50..a940a2e 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -88,7 +88,7 @@ frontend/src/│ │ ├── Automations.tsx <- Page: server notices, counts, account controls, rules, activity, the rule dialog│ │ ├── AutomationNotices.tsx <- Webhook not set up, or replies paused on the server│ │ ├── AutomationMetrics.tsx, AutomationAccounts.tsx, AutomationRules.tsx, AutomationActivity.tsx-│ │ ├── RuleDialog.tsx, RuleMediaPicker.tsx, RulePreview.tsx <- Rule form, post picker, reply preview and keyword test+│ │ ├── RuleDialog.tsx, RuleMediaPicker.tsx, RulePublicReplies.tsx, RulePreview.tsx <- Rule form (private and public reply sections), post picker, public wordings, thread and message preview, keyword test│ │ ├── useAutomations.ts <- Overview and every rule and account action, with toasts│ │ ├── useAutomationActivity.ts <- Filters, counts, activity pages and retry│ │ ├── useRuleForm.ts <- Rule dialog state, the account's posts, the test call@@ -221,7 +221,7 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo| Tracked Category | `/tracked-content/category/:name` | Detailed per-category analytics; YouTube section (views, likes, comments, bar chart, table) and Reddit section (score, ratio, comments, bar chart, table) rendered separately || Video Explorer | `/videos/:id` | YouTube video library with search and sort || Publish | `/upload` | Publish or schedule to Instagram, bulk upload, and the scheduled post queue |-| Automations | `/automations` | Keyword rules that answer Instagram comments with a private reply, account pause and comment events, counts and the reply activity with retry (`docs/architecture/data-flows/AUTOMATION.md`) |+| Automations | `/automations` | Keyword rules that answer Instagram comments with a private reply, a public reply under the comment or both, account pause and comment events, counts and the activity of both replies with separate retries (`docs/architecture/data-flows/AUTOMATION.md`) || Settings | `/settings` | Theme, server key status, who sets up scheduling, the optional GitHub backup guide || Documentation | `/docs/*` | Not a page in the app: `DocsRedirect` sends the visitor to the same path on the public docs at `https://twiligent.ujjwal.fyi/docs`. The Documentation item in the sidebar user menu and Open documentation in the command palette open the docs in a new tab |diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 2bcbb0b..a884f9f 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -104,7 +104,7 @@ The caps also protect the free email quota. There are 100 emails a day by defaul2. The Worker recomputes the signature over the exact bytes it received and compares it in constant time (`crypto.subtle.verify`); without a secret the route answers 503.3. A comment is attached only to the accounts whose Instagram id the signed payload names, and only when such an account has an enabled rule; nothing in the payload can point a reply at another member's account.-Meta's notifications carry no timestamp, so a captured notification could be sent again; that is harmless, because each comment is stored once and Instagram allows one private reply per comment. The verification `GET` compares the Verify Token in constant time. Comment text is kept only for comments a rule answers, for 90 days, and never logged.+Meta's notifications carry no timestamp, so a captured notification could be sent again; that is harmless, because each comment is stored once with at most one public reply job, and Instagram allows one private reply per comment. The account's own comments, its public replies among them, are never answered. The verification `GET` compares the Verify Token in constant time. Comment text is kept only for comments a rule answers, for 90 days, and never logged.A message event (followers-only rules) is read for its sender and message id only; its text is never read, stored or logged. It becomes a follow-up only when the signed payload's account has a followers-only reply waiting for that sender, and the follow-up takes its member and account from that waiting comment, never from the message. A message delivered again is refused by `unique (ig_user_id, trigger_message_id)`. The link of a followers-only rule goes out only when Instagram's own profile read says the person follows the account; when Instagram cannot say, nothing is sent.diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex 473a6df..f760a4b 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -144,7 +144,7 @@ npx wrangler secret put META_APP_SECRET # optional; a second key fornpx wrangler secret put AUTOMATION_PAUSED # optional; "true" holds every automated reply```-The `AUTOMATION_*` limits (`ACCOUNT_HOURLY_LIMIT`, `USER_HOURLY_LIMIT`, `GLOBAL_HOURLY_LIMIT`, `RECIPIENT_DAILY_LIMIT`, `BATCH_SIZE`) are optional too; `WORKERS.md` lists their defaults.+The `AUTOMATION_*` limits (`ACCOUNT_HOURLY_LIMIT`, `USER_HOURLY_LIMIT`, `GLOBAL_HOURLY_LIMIT`, `RECIPIENT_DAILY_LIMIT`, `PUBLIC_ACCOUNT_HOURLY_LIMIT`, `BATCH_SIZE`) are optional too; `WORKERS.md` lists their defaults.Each command prompts for the value (no echo - the value is not shown).@@ -152,7 +152,7 @@ Each command prompts for the value (no echo - the value is not shown).The email secrets only matter once Supabase's Send Email hook points at `https://<worker>/api/auth/email-hook`. Set them before turning the hook on: while the hook is on and the secrets are missing, every sign-up and password reset fails with a 503. The full setup (Resend domain, hook, **Confirm email**, rate limit) is in the public docs at `https://twiligent.ujjwal.fyi/docs/self-host/email-codes` (source: `site/content/docs/self-host/email-codes.mdx`). To check the hook after a deploy, sign up with an address you own and watch `npx wrangler tail` for the `auth email sent` line. Keep Resend's click and open tracking off: its tracking record once took the name `twiligent` and replaced the Pages record for `twiligent.ujjwal.fyi`, which took the site offline until the record was pointed back at `twiligent.pages.dev` (proxied) and the Pages custom domain was reactivated (#37). That name now belongs to the public site; the same care applies to the `app.twiligent` record.-Comment-to-DM automation needs its migrations applied (`npm run db:push`), `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` set, and the webhook added in the Meta dashboard with the callback `https://<worker>/api/webhooks/instagram` and the `comments` field. The app must be Live with Advanced Access for `comments` before comments from accounts without a role on the app arrive. Followers-only rules also need the `messages` field selected (Instagram, API setup with Instagram login, Configure webhooks) and Advanced Access for `instagram_business_manage_messages`. Select it only when such a rule is used: Meta then sends every direct message to the connected accounts to the Worker, each one a Worker request and a database call. The full setup is in the public docs at `https://twiligent.ujjwal.fyi/docs/self-host/comment-automation` (source: `site/content/docs/self-host/comment-automation.mdx`). To check it after a deploy, comment a keyword on a post of a connected account from another Instagram account and watch `npx wrangler tail` for `instagram webhook stored` and `automation reply settled`. To stop every reply at once, set `AUTOMATION_PAUSED` to `true`.+Comment-to-DM automation needs its migrations applied (`npm run db:push`), `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` set, and the webhook added in the Meta dashboard with the callback `https://<worker>/api/webhooks/instagram` and the `comments` field. The app must be Live with Advanced Access for `comments` before comments from accounts without a role on the app arrive. Followers-only rules also need the `messages` field selected (Instagram, API setup with Instagram login, Configure webhooks) and Advanced Access for `instagram_business_manage_messages`. Select it only when such a rule is used: Meta then sends every direct message to the connected accounts to the Worker, each one a Worker request and a database call. The full setup is in the public docs at `https://twiligent.ujjwal.fyi/docs/self-host/comment-automation` (source: `site/content/docs/self-host/comment-automation.mdx`). To check it after a deploy, comment a keyword on a post of a connected account from another Instagram account and watch `npx wrangler tail` for `instagram webhook stored` and `automation reply settled`, and `automation public reply settled` for a rule with a public reply. Public replies need no new permission or webhook field: they use `instagram_business_manage_comments`, which the comments webhook already needs. To stop every reply at once, set `AUTOMATION_PAUSED` to `true`.## Setting GitHub Actions Secretsdiff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 7161998..8b72c9d 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -42,10 +42,12 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `backend/services/automationProcessor.ts` | `backend/tests/services/automationProcessor.test.ts` || `backend/services/automationWebhookService.ts` | `backend/tests/services/automationWebhookService.test.ts` || `backend/services/automationFollowupProcessor.ts` | `backend/tests/services/automationFollowupProcessor.test.ts` |+| `backend/services/automationPublicReplyProcessor.ts` | `backend/tests/services/automationPublicReplyProcessor.test.ts` || `backend/services/automationReconciler.ts` | `backend/tests/services/automationReconciler.test.ts` || `backend/services/instagram/instagramMessaging.ts` | `backend/tests/services/instagram/instagramMessaging.test.ts` |+| `backend/services/instagram/instagramComments.ts` | `backend/tests/services/instagram/instagramComments.test.ts` || `backend/services/retentionService.ts` | `backend/tests/services/retentionService.test.ts` |-| `backend/lib/automationMatching.ts`, `automationDelivery.ts`, `automationRules.ts`, `automationReview.ts`, `automationHealth.ts`, `metaWebhookSignature.ts` | `backend/tests/lib/` with the same names |+| `backend/lib/automationMatching.ts`, `automationDelivery.ts`, `automationPublicReply.ts`, `automationRules.ts`, `automationReview.ts`, `automationHealth.ts`, `metaWebhookSignature.ts` | `backend/tests/lib/` with the same names || `backend/repositories/automationCommentRepository.ts` | `backend/tests/repositories/automationCommentRepository.test.ts` || `backend/repositories/automationFollowupRepository.ts` | `backend/tests/repositories/automationFollowupRepository.test.ts` || `backend/repositories/automationRuleRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` | `backend/tests/repositories/automationRuleRepository.test.ts` |@@ -85,7 +87,7 @@ Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.The database migrations have their own test. `tests/database/migrations.test.ts` reads `supabase/migrations/` and `supabase/rollbacks/` and checks that every file is named `<14 digit version>_<lowercase name>.sql` with a unique version, that the baseline files come before every change, that every change has a rollback with the same name and every rollback has its migration, that the baselines use only `if not exists` for tables, indexes and columns so they can run again, that every function a migration creates revokes execute from `public, anon, authenticated`, that every migration from version 20261016100000 on creates at most one entity (a table, its access, a trigger, an index or a function) and has a rollback that is not empty, and that no file uses an em or en dash. It does not run the SQL; CI has no database. The migrations themselves were checked once on a local Postgres before the first push (ADR-038). The reply queue migrations (20261016120000 to 20261016122500) were checked the same way on a local Postgres with stub Supabase roles: every migration applies, 60 SQL scenario checks pass (among them eight sessions claiming at once, each job claimed by one), and the rollbacks apply in reverse with data present before the migrations apply again.-Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, a cancelled run and one without time for a whole send handing their jobs back unstarted, and a run claiming only what its subrequests pay for. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/repositories/automationCommentRepository.test.ts` pages through comments stored in the same instant without skipping or repeating one, and checks the hand-back of unstarted jobs. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. `fakeAutomationQueue.ts` also mirrors the turn-taking claim, follow-ups, expiry and review. `tests/services/automationFollowupProcessor.test.ts` covers followers-only replies: a follower gets the link, someone not following gets a reminder and the second ends the wait, nothing is sent when Instagram cannot say, a lost answer needs review and is never sent again, and two runs at once send each follow-up once. `tests/services/automationReconciler.test.ts` covers a lost reply found in the conversation (accepted, nothing sent) or not found (left for a person), and the expiry and health warning. `tests/lib/automationRules.test.ts`, `automationReview.test.ts` and `automationHealth.test.ts` cover the rule checks, matching a lost reply by its digest and time, and the warning line; `tests/services/instagram/instagramMessaging.test.ts` the send, follow check, conversation read and subscription requests; `tests/repositories/automationFollowupRepository.test.ts` the follow-up database calls. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.+Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, a cancelled run and one without time for a whole send handing their jobs back unstarted, and a run claiming only what its subrequests pay for. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/repositories/automationCommentRepository.test.ts` pages through comments stored in the same instant without skipping or repeating one, and checks the hand-back of unstarted jobs. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. `fakeAutomationQueue.ts` also mirrors the turn-taking claim, follow-ups, expiry and review. `tests/services/automationFollowupProcessor.test.ts` covers followers-only replies: a follower gets the link, someone not following gets a reminder and the second ends the wait, nothing is sent when Instagram cannot say, a lost answer needs review and is never sent again, and two runs at once send each follow-up once. `tests/services/automationReconciler.test.ts` covers a lost reply found in the conversation (accepted, nothing sent) or not found (left for a person), and the expiry and health warning. `tests/lib/automationRules.test.ts`, `automationReview.test.ts` and `automationHealth.test.ts` cover the rule checks, matching a lost reply by its digest and time, and the warning line; `tests/services/instagram/instagramMessaging.test.ts` the send, follow check, conversation read and subscription requests; `tests/repositories/automationFollowupRepository.test.ts` the follow-up database calls. Public replies (ADR-044): `tests/lib/automationPublicReply.test.ts` covers the stable wording per comment, the text bounds, what is recorded for each answer (posted only with an id, a lost answer for review, a deleted comment skipped, a public-only cooldown and a day-long block, retries, a held account, expiry) and when a lost reply goes out again. `tests/services/automationPublicReplyProcessor.test.ts` runs the public processor against the fake queue: posting with the stored text while the private reply is left alone, a failed private reply never repeating the public one and a public retry never repeating the private one, a lost answer never posted again by the dispatch, two runs at once posting each reply once, a rate limit cooling public replies only, one public reply per person and post, the account's hourly limit, a public reply turned off, an interrupted run and the instance pause. `tests/services/automationReconciler.test.ts` also covers a lost public reply found on the second page of replies, sent again once after two full reads, never sent again with a page unread or after a second lost answer, and a read Instagram refuses. `tests/services/instagram/instagramComments.test.ts` covers the reply request, answers without an id, refusals and paging; `tests/routes/instagramWebhookRoutes.test.ts` a rule with both replies end to end, where the private reply fails, the public one is posted and a redelivery sends neither again; `tests/routes/automationRoutes.test.ts` the public reply retry, the refused private retry of a public-only comment, and public-only rules. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite, and Postgres 18 for the public reply functions, including eight claims at once on 10,000 waiting replies with no reply claimed twice) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.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.@@ -236,6 +238,10 @@ Open the app in a browser. For each changed area, test:- [ ] Turn on an any-comment rule: any comment with text on a covered post gets the reply, and a keyword rule for the same posts still answers its keyword first- [ ] Turn on a followers-only rule (with the `messages` field selected in the Meta dashboard): the comment gets the follow prompt without the link; reply to it from the tester account while not following and the not-following message arrives; follow the account, reply again and the link arrives- [ ] Let a reply hit the account's hourly limit: it waits in place, and goes out within a minute after the limit frees+- [ ] Turn on a rule's public reply with two wordings: a matching comment gets the private reply and one of the wordings under it, Activity shows Accepted by Instagram and Posted on separate lines, and `npx wrangler tail` shows `automation public reply settled`; the account's own reply is recorded as ignored (`own_comment`) and gets no answer+- [ ] Comment twice on the same post from the tester account: the second comment gets no second public reply (Skipped)+- [ ] Turn off the rule's private reply: the next comment gets only the public reply, its private reply shows Off and offers no retry+- [ ] Retry a failed public reply from Activity: only the public reply goes out again, and the private reply's status does not change- [ ] At 375 px and 1280 px in both themes, the page, the rule dialog and the activity table fit, and the table scrolls inside its box**Scheduling (if changed):**diff --git a/site/content/docs/self-host/comment-automation.mdx b/site/content/docs/self-host/comment-automation.mdxindex debca3c..43a0be7 100644--- a/site/content/docs/self-host/comment-automation.mdx+++ b/site/content/docs/self-host/comment-automation.mdx@@ -1,8 +1,8 @@-export const meta = { title: 'Comment automation (optional)', description: 'Let Instagram send comments to your backend so automation rules can answer them with a private reply.' }+export const meta = { title: 'Comment automation (optional)', description: 'Let Instagram send comments to your backend so automation rules can answer them with a private reply, a public reply, or both.' }<Callout type="note" title="How it works">-When someone comments on a post or reel of a connected Instagram account, Meta sends the comment to your backend's webhook. The backend checks Meta's signature, stores the comment, and if a rule answers it, sends the commenter one private reply through Instagram's official messaging API. Instagram allows one private reply per comment, within 7 days of it, and up to 750 an hour per account. Nothing else is needed on Cloudflare: the webhook and the reply queue run on the Worker and the Supabase database you already have, and the Worker's cron triggers send what waits.+When someone comments on a post or reel of a connected Instagram account, Meta sends the comment to your backend's webhook. The backend checks Meta's signature, stores the comment, and if a rule answers it, sends the commenter one private reply through Instagram's official messaging API, posts a public reply under the comment through the official comment replies API, or both. Instagram allows one private reply per comment, within 7 days of it, and up to 750 an hour per account; public replies need the same `instagram_business_manage_comments` permission and no other webhook field. Nothing else is needed on Cloudflare: the webhook and the reply queue run on the Worker and the Supabase database you already have, and the Worker's cron triggers send what waits.</Callout>@@ -55,7 +55,7 @@ In Twiligent, open **Automations**, create a rule and turn it on. The first rule</Step><Step title="Test it">-From another Instagram account, comment a rule's keyword on one of the account's posts. The private reply should arrive within a few seconds. To follow it, run `npx wrangler tail` in `backend/` and look for `instagram webhook stored` and `automation reply settled`. The comment and its status also appear under **Activity** on the Automations page.+From another Instagram account, comment a rule's keyword on one of the account's posts. The private reply should arrive within a few seconds, and a public reply appear under the comment if the rule has one. To follow it, run `npx wrangler tail` in `backend/` and look for `instagram webhook stored`, `automation reply settled` and `automation public reply settled`. Meta also sends the account's own public reply back as a comment; it is recorded as the account's own and never answered. The comment and its status also appear under **Activity** on the Automations page.For a followers-only rule, reply to the first message from the commenting account. If that account follows yours, the reply and link arrive; if not, the reminder does. Look for `automation follow-up settled` in the log.@@ -72,14 +72,15 @@ These Worker settings are optional; each falls back to its default when unset or| `AUTOMATION_USER_HOURLY_LIMIT` | 500 | Replies an hour across one member's accounts || `AUTOMATION_GLOBAL_HOURLY_LIMIT` | 1000 | Replies an hour across your whole instance || `AUTOMATION_RECIPIENT_DAILY_LIMIT` | 3 | Replies a day one person can get from one account |+| `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT` | 60 | Public replies an hour from one Instagram account; at most 200. Meta publishes no limit for comment replies but blocks accounts that comment like a bot || `AUTOMATION_BATCH_SIZE` | 10 | Replies sent by one webhook request or one run of the every-minute schedule; at most 15 on the Workers Free plan || `AUTOMATION_PAUSED` | not set | `true` holds every reply; comments are still recorded and go out when you remove it, within the 7 days |-A reply that misses its first chance goes out on the backend's every-minute schedule, which also retries temporary Instagram errors and waits out Instagram's rate limits. Accounts take turns, so one busy reel cannot hold back another account's replies. A reply whose outcome is unknown, for example after a timeout, is never sent again on its own; it shows as **Needs review**. Every five minutes the backend looks for such replies in the conversation on Instagram and marks the ones it finds as accepted. It never sends from that check, so check the rest on Instagram before you retry.+A reply that misses its first chance goes out on the backend's every-minute schedule, which also retries temporary Instagram errors and waits out Instagram's rate limits. Accounts take turns, so one busy reel cannot hold back another account's replies. A reply whose outcome is unknown, for example after a timeout, is never sent again on its own; it shows as **Needs review**. Every five minutes the backend looks for such replies in the conversation on Instagram and marks the ones it finds as accepted. It never sends from that check, so check the rest on Instagram before you retry. A public reply whose outcome is unknown is looked for among the comment's replies instead; when every reply was read twice, minutes apart, and it is not there, it is posted again once.## Cron triggers-Deploying the backend registers three cron triggers: every minute (replies and follow-ups that wait), every five minutes (scheduled posts on the quarter hour, the reply queue checks otherwise) and daily (token refresh and retention). The Workers Free plan allows five cron triggers per Cloudflare account, across all your Workers. If the deploy fails because the account has no trigger left, remove a trigger you do not need from another Worker. Each cron run counts as one Worker request: about 1,700 a day of the free plan's 100,000.+Deploying the backend registers three cron triggers: every minute (private replies, follow-ups and public replies that wait), every five minutes (scheduled posts on the quarter hour, the reply queue checks otherwise) and daily (token refresh and retention). The Workers Free plan allows five cron triggers per Cloudflare account, across all your Workers. If the deploy fails because the account has no trigger left, remove a trigger you do not need from another Worker. Each cron run counts as one Worker request: about 1,700 a day of the free plan's 100,000.## Costs@@ -93,6 +94,8 @@ Everything runs on the services you already use, and nothing new is billed on Cl| `wrangler tail` shows 401 for webhook calls | The signature does not match: set `META_APP_SECRET` as well, then check that `INSTAGRAM_APP_SECRET` is the Instagram app secret || No webhook calls at all | The app is not Live, the account has no role on the app during testing, the account is private, or comment events are not turned on for it || A reply failed with "does not allow a private reply" | The comment was deleted, is older than 7 days, or its author does not accept messages |+| An account shows **Public replies cooling down** | Instagram limited or blocked comments from the account. Public replies wait (a day after a block) while private replies continue. Lower `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT`, add more wordings, and check the account in the Instagram app |+| A public reply was skipped as deleted or hidden | Instagram cannot reply under a deleted or hidden comment, or a comment on a live video || An account shows **Held** | Instagram refused its token. Connect the account again on the Accounts page, check that the account allows access to messages in the Instagram app, then turn its replies back on || An account shows **Follow checks off** | A followers-only rule is on, but Instagram does not send the account's messages. Select the messages field in the Meta dashboard webhook settings, check the app has Advanced Access for `instagram_business_manage_messages`, then choose **Turn on message events** || A follow-up failed with "Instagram did not say whether this person follows" | Instagram refused the follow check, so the link was not sent. Check the reason in the details; a later reply from the person is checked again |diff --git a/site/content/docs/use/automations.mdx b/site/content/docs/use/automations.mdxindex 43b1ac3..ffe230b 100644--- a/site/content/docs/use/automations.mdx+++ b/site/content/docs/use/automations.mdx@@ -1,6 +1,6 @@-export const meta = { title: 'Reply to comments automatically', description: 'Send a private message to anyone who comments a keyword on your Instagram posts and reels.' }+export const meta = { title: 'Reply to comments automatically', description: 'Answer people who comment a keyword on your Instagram posts and reels with a private message, a public reply under their comment, or both.' }-Automations send a private reply on Instagram when someone comments a keyword, such as GUIDE, on one of your posts or reels, or any comment at all on the posts you choose. A typical rule sends a link: "Here is your guide" and the address of the guide.+Automations answer people who comment a keyword, such as GUIDE, on one of your posts or reels, or any comment at all on the posts you choose. A rule can send them a private reply, post a public reply under their comment, or both. A typical rule sends a link in private ("Here is your guide" and the address of the guide) and thanks them in public.<Callout type="note" title="Before you start">@@ -14,11 +14,12 @@ You need an Instagram Business or Creator account connected with Instagram sign-2. Choose the Instagram account, give the rule a name, and type its keywords, separated by commas.3. Choose how comments match. **Anywhere in the comment, as a whole word** answers "send me the guide please" for GUIDE but not "guidelines". **The whole comment, nothing else** answers only a comment that is the keyword. **Any comment, no keyword needed** answers everyone who comments.4. Choose **Every post and reel**, or **Only the posts I choose** and pick them.-5. Write the reply and, if you like, a link. The preview shows the message as it will arrive, and how much of Instagram's 1,000 byte limit it uses.-6. Type a sample comment under **Test a comment** and choose **Test** to see whether it would match. Nothing is sent.-7. Leave **Turn the rule on when saved** on, and choose **Create rule**.+5. Under **Send a private reply**, write the reply and, if you like, a link. Turn the switch off if the rule should answer only in public.+6. Under **Reply publicly under the comment**, turn the switch on to post a public reply as well, and write one to five wordings. Each comment gets one of them.+7. The preview shows the public reply under a comment and the private message as it will arrive, with how much of Instagram's 1,000 byte limit the message uses. Type a sample comment under **Test a comment** and choose **Test** to see whether it would match. Nothing is sent or posted.+8. Leave **Turn the rule on when saved** on, and choose **Create rule**.-A comment gets one reply, from the most specific rule that answers it: rules for chosen posts come before rules for every post, and keyword rules before any-comment rules. Among equals, the oldest rule answers. You can copy a rule (the copy starts off), change it, turn it off, or delete it.+A comment is answered by one rule, the most specific one that answers it, with that rule's private reply, public reply or both: rules for chosen posts come before rules for every post, and keyword rules before any-comment rules. Among equals, the oldest rule answers. You can copy a rule (the copy starts off), change it, turn it off, or delete it.<Callout type="warning" title="Any comment means everyone">@@ -26,6 +27,18 @@ An any-comment rule messages everyone who comments, including people who did not</Callout>+## Reply publicly under the comment++A public reply appears under the person's comment, where everyone can see it. Twiligent sends it apart from the private reply: each has its own status and retry, and one failing never sends the other again.++- Keep it short: at most 300 characters, 4 hashtags and 1 link. Put the link in the private reply.+- Write a few wordings. Instagram may treat many identical replies as spam, so each comment gets one of your wordings, always the same one for the same comment.+- Avoid promising a message, such as "check your messages". The private reply can fail on its own, for example when the person does not accept messages.+- A person gets at most one public reply on a post a day, however often they comment, and each account posts at most 60 public replies an hour unless your administrator changes it.+- Instagram cannot reply under a hidden comment or a comment on a live video, and a reply to a reply goes into the original comment's thread.++If Instagram limits or blocks comments from your account for a while, public replies wait and private replies keep going out. The account shows **Public replies cooling down**.+## Send the link only to followers (testing)<Callout type="warning" title="In testing">@@ -34,7 +47,7 @@ This option is still being tested and may or may not work. It needs Instagram to</Callout>-Turn on **Send the link only to followers** to keep the link for people who follow you. Instagram lets Twiligent check whether someone follows you only after that person has messaged you, so the rule works in two steps:+Turn on **Send the link only to followers**, inside the private reply section, to keep the link for people who follow you. Instagram lets Twiligent check whether someone follows you only after that person has messaged you, so the rule works in two steps:1. Everyone who comments gets the **First reply**, which asks them to follow you and reply. It has no link.2. When they reply, Twiligent asks Instagram whether they follow you. A follower gets your reply and link. Anyone else gets the **Reminder**, at most twice.@@ -47,10 +60,11 @@ If Instagram cannot say whether the person follows you, nothing is sent, and the- The person can only get more messages from you after they reply.- Up to 750 private replies an hour per account. Your administrator sets lower limits, and each rule can have its own.- A person gets at most a few replies a day from one account, however many keywords they comment.+- Public replies have no published hourly number, but Instagram blocks accounts that comment like a bot, so Twiligent keeps them slow and varied.## Follow what happened-The counts at the top cover the chosen period. **Activity** lists every comment received on an account with an active rule, newest first, with its status:+The counts at the top cover the chosen period. **Activity** lists every comment received on an account with an active rule, newest first, with the status of its private reply and of its public reply on separate lines. The status filter follows the private reply. Private replies:| Status | Meaning || --- | --- |@@ -65,10 +79,21 @@ The counts at the top cover the chosen period. **Activity** lists every comment| Link sent | Instagram confirmed the person follows you and accepted the reply with the link || Not following | The person replied without following, and every reminder was sent || Follow-up failed | The message after their reply did not go out; the details say why |+| Off | The rule sends no private reply |++Public replies:++| Status | Meaning |+| --- | --- |+| Posted | Instagram posted the reply and gave it an id |+| Waiting, Posting, Trying again, Held | The reply is queued, going out, waiting for a retry or a limit, or the account is paused |+| Checking | Instagram did not answer, so the reply may or may not be there. Twiligent looks for it under the comment and posts it again once only if it is not there |+| Failed | Instagram refused it; the details say why |+| Skipped, Expired | The rule or its public reply was turned off, the comment was deleted or hidden, the person already got a public reply on that post today, or 7 days passed |-Choose the retry button on a failed, skipped or review item to send it again. Instagram refuses a second private reply to the same comment, so a retry never messages someone twice. On a followers-only reply, the retry sends the failed follow-up again, within 24 hours of the person's reply.+Each reply has its own retry button. Retrying one never sends the other again. Choose the private reply's retry button on a failed, skipped or review item to send it again. Instagram refuses a second private reply to the same comment, so a retry never messages someone twice. On a followers-only reply, the retry sends the failed follow-up again, within 24 hours of the person's reply.-Twiligent also looks for **Needs review** replies in the conversation on Instagram a few times, and marks the ones it finds as accepted. It never sends anything while it looks.+Twiligent also looks for **Needs review** replies in the conversation on Instagram a few times, and marks the ones it finds as accepted. It never sends anything while it looks. The public reply's retry button posts it again; use it on a **Checking** reply only after you looked under the comment.## Pause an account