Skip to content

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

docs: describe the reply dispatch, reconciliation and followers-only rules

spacesdrive86772121a3f7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e2ac01..098107c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,16 +16,23 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- New tables `automation_accounts`, `automation_rules`, `automation_comments`, `automation_attempts` and `audit_events`, and their functions; existing instances run `npm run db:push` before deploying (#88)
- An audit record of connecting, reconnecting and removing accounts and of every automation change, kept a year (#89)
- Every migration now holds one database entity (a table, its access, a trigger, an index or a function) with a rollback of the same size, and the migration test enforces it for new migrations (#93, ADR-041)
+- Automation rules can answer any comment, with no keyword; the most specific rule answers, so a comment still gets one reply (#102)
+- Followers-only rules: 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, 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)
### Changed
- Connecting an Instagram account that is already connected renews its token instead of answering that it is already added, so a revoked token can be fixed without removing the account (#89)
-- The Worker's publishing cron runs every 5 minutes instead of 15; posts still publish on the quarter hour, and the other runs send waiting comment replies (#89)
+- The Worker's publishing cron runs every 5 minutes instead of 15; posts still publish on the quarter hour, and the other runs check the reply queue (#89, #100)
+- The reply queue sends up to 10 replies a minute instead of 10 every five minutes, accounts take turns so one busy reel cannot hold back another account, and paused, cooling or limited accounts are no longer claimed and put back on every run (#99)
+- The daily retention deletes old comments in batches of 1,000 instead of one statement (#101)
### Fixed
- The sign-in page opens the dashboard when you are already signed in, so the public site's Sign in and Get started buttons no longer ask you to sign in again (#94)
- The public site's home page opens the dashboard when you are signed in to the app; the docs stay readable (#96)
+- Runs claiming replies at the same moment no longer leave each other with nothing to send while jobs wait (#99)
---
diff --git a/DECISIONS.md b/DECISIONS.md
index 1b592e8..1497a7a 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -914,3 +914,32 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
- The cookie is a hint, not proof: after a session ends in a way the app has not yet seen (a refresh token revoked elsewhere), the home page sends the visitor to the app once, which finds no session, clears the cookie and shows the sign-in page.
- A signed-in visitor cannot see the marketing home page without signing out; the docs and other site pages are not redirected.
- Self-hosted instances on other domains write no cookie, so their behaviour is unchanged; the domain is a constant, like the docs address in `frontend/src/lib/docs.ts`.
+
+## ADR-043: An every-minute reply dispatch, reconciliation without resending, and followers-only replies through the person's answer
+
+**Date:** 2026-10-16
+**Status:** Accepted
+
+**Decision:** The Worker gets a third cron trigger, `* * * * *`, that dispatches waiting private replies and follow-ups. The five minute trigger keeps publishing on the quarter hour and reconciles the reply queue on its other runs: it expires overdue jobs in one call, looks for replies whose answer was lost in the conversation on Instagram, and logs the queue's health. The daily trigger keeps the token refresh and deletes old comments in batches of 1,000. The reply claim finds accounts with a loose index scan, locks each account's oldest due jobs with `FOR UPDATE SKIP LOCKED` as it reads them, lets accounts take turns, and leaves out paused, cooling and limited accounts. Rules gain an any-comment mode and a followers-only option: the private reply asks the person to follow and reply, their reply arrives through the `messages` webhook, and only then does Twiligent read `is_user_follow_business` and send the link to a follower or a reminder to anyone else. The database stays the queue (ADR-040).
+
+**Context:** The owner asked for a production-grade review of the comment-to-DM automation: high volume, fairness across accounts, rate limits, no duplicate or missing messages, the remaining cron capacity, any-comment rules and a "followers only" option (#98). Measured on 2026-10-16 with the Cloudflare API, the account used three of the five cron triggers the Workers Free plan allows (one on another Worker, two here), not five as ADR-040 recorded. The old design drained leftovers at 10 replies every five minutes (120 an hour), at most 5 per account; its claim looked only at the oldest 100 due rows, so one busy account hid the others; held and limited accounts were claimed and put back on every run; and eight claims at the same moment on a local Postgres left three of them with nothing while 9,925 jobs waited. Meta's User Profile API (checked 2026-10-16) returns the follow status only after the person has messaged the account, and private replies are documented with a text message only.
+
+**Why one new trigger and not three:** Each responsibility (dispatch and recovery, reconciliation, maintenance) maps to a trigger, but reconciliation fits the five minute runs that do not publish, each its own invocation with its own 50 subrequests, so it needs no trigger of its own. One trigger raises the drain rate to 600 to 900 replies an hour and the wait for a leftover reply to a minute, and leaves one of the account's five slots free.
+
+**Why not Cloudflare Queues now:** ADR-040's reasons hold. The free plan's 10,000 operations a day (a write, a read and an ack per message) cover about 3,300 messages, fewer than one viral reel can produce; its 24 hour retention is shorter than the 7 day reply window; the comment row is needed anyway for deduplication, limits and history; and a queue would still need the database sweep for publishes that failed. With the row as the job, acceptance is one insert and there is no dual write to reconcile.
+
+**Followers-only:** Inferring a follow from anything else (likes, usernames, earlier comments) or from undocumented endpoints was ruled out, and so was claiming a check that cannot happen. The person's reply is what gives Instagram's consent and opens the 24 hour window in which Twiligent may message them again, so the follow check waits for it. Only a confirmed follow sends the link; an answer Instagram cannot give sends nothing and says why. Subscribing to the `messages` field sends every direct message of the connected accounts to the Worker, so the account-level subscription asks for it only while an enabled followers-only rule needs it, and the person's message text is never read or stored.
+
+**Reconciliation:** Each attempt stores the sha-256 digest of the text sent. A reply whose answer was lost is marked accepted only when the conversation shows a message from the account with that exact digest after the attempt started; otherwise it stays for a person with a note. The reconciler only reads from Instagram, so the rule that an unknown outcome is never resent without a person's decision still holds.
+
+**Alternatives considered:**
+- Using all free cron slots, one per responsibility. Rejected as above; it would leave the account with none.
+- Automatic resending of ambiguous replies, relying on Instagram refusing a second private reply (10900). Rejected: the project rule is that a person decides, and a quick resend could race the first request on Meta's side.
+- A quick reply or button in the private reply to collect the person's answer. Not documented for private replies; a plain reply works the same and is documented.
+- Counting follow-ups against the private reply limits. They use the Send API (300 calls a second per account), so counting them would only slow private replies.
+
+**Trade-offs:**
+- 1,440 more Worker requests a day for the dispatch, about 1.4% of the free plan's 100,000, and two database calls a minute with nothing due.
+- 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.
diff --git a/README.md b/README.md
index 274359e..2ab5800 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 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; per-account, per-rule and per-person limits, retries and an activity log |
+| **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 |
| **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 |
@@ -314,7 +314,7 @@ npx wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN # optional; comment-to-D
npx wrangler secret put META_APP_SECRET # optional; a second key for webhook signatures
```
-Comment-to-DM automation needs `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, the webhook added in the Meta dashboard (`https://<worker>/api/webhooks/instagram`, field `comments`) and, for comments from people without a role on your app, a Live app with Advanced Access. Optional `AUTOMATION_*` settings change the reply limits or pause every reply. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/comment-automation).
+Comment-to-DM automation needs `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, the webhook added in the Meta dashboard (`https://<worker>/api/webhooks/instagram`, field `comments`, plus `messages` only for followers-only rules) and, for comments from people without a role on your app, a Live app with Advanced Access. Optional `AUTOMATION_*` settings change the reply limits or pause every reply. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/comment-automation).
The four email secrets turn on the 6-digit codes that sign people in and confirm password sign-ups, sent free through Resend (100 a day). Supabase Auth hands each email to the Worker through its Send Email hook (`POST /api/auth/email-hook`); every code sign-in is one email. Past the daily limit, the sign-in page pauses email codes and points people to Google or their password. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes).
@@ -390,7 +390,7 @@ flowchart TD
B -->|YouTube Data API v3| F[Google APIs]
B -->|Instagram Graph API v25| G[Meta APIs]
B -->|Upload preset config| H[Cloudinary CDN]
- B -->|Worker cron every 15 min| B
+ B -->|Worker crons: replies every minute, posts every 15 min| B
B -->|Publish scheduled posts| G
I[GitHub Actions - best effort] -->|Read pending posts| D
I -->|Publish fallback| G
@@ -406,10 +406,10 @@ flowchart TD
**Cron lifecycle:**
-1. The Cloudflare scheduler fires the Worker every 5 minutes (`*/5 * * * *`); the runs on the quarter hour publish, the others send waiting comment replies
-2. The Worker queries `scheduled_posts` for rows with `status = 'pending'` and `scheduled_at <= now()`, and for `publishing` rows whose claim is older than 20 minutes
+1. The Worker has three cron triggers. Every minute (`* * * * *`) it sends the comment replies and follow-up messages that are waiting. Every 5 minutes (`*/5 * * * *`) it publishes due posts on the quarter hour (minutes 0, 15, 30 and 45); the other runs check the reply queue: they expire overdue replies, look for replies whose answer was lost and log the queue's health
+2. On a publishing run the Worker queries `scheduled_posts` for rows with `status = 'pending'` and `scheduled_at <= now()`, and for `publishing` rows whose claim is older than 20 minutes
3. Each post is claimed (`publishing`, with `claimed_at` and `attempts`), published to Instagram, then set to `published`, back to `pending` for a retry, or `failed`
-4. A separate `0 0 * * *` cron refreshes expiring Instagram access tokens across all users and deletes comment automation records past their retention
+4. A daily `0 0 * * *` cron refreshes expiring Instagram access tokens across all users and deletes comment automation records past their retention, in batches
---
@@ -436,14 +436,16 @@ twiligent/
│ ├── services/
│ │ ├── *Service.ts # Feature services: business rules, no Hono types
│ │ ├── scheduledPublisher.ts # Publishes due scheduled posts (cron and manual trigger)
-│ │ ├── automationProcessor.ts # Sends comment-to-DM replies within limits (webhook, retry and 5 minute cron)
+│ │ ├── 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
+│ │ ├── 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 analytics
│ │ └── reddit/ # Reddit public JSON API client and analytics
│ ├── repositories/ # All Supabase queries and the Redis analytics cache
│ ├── database/ # Supabase and Upstash Redis client factories
│ ├── jobs/
-│ │ └── scheduled.ts # Cron entry point: due posts and the reply sweep every 5 minutes, token refresh and retention daily
+│ │ └── scheduled.ts # Cron entry point: reply dispatch every minute, due posts on the quarter hour, queue checks every 5 minutes, token refresh and retention daily
│ ├── lib/
│ │ ├── errors.ts # Typed errors; the error handler maps each code to a status
│ │ ├── ids.ts # newRowId(): random UUIDs for new rows
@@ -453,8 +455,11 @@ twiligent/
│ │ ├── oauthState.ts # HMAC-signed Instagram OAuth state
│ │ ├── analyticsMath.ts # Shared analytics formulas
│ │ ├── scheduledPublishing.ts # Lease, retry and container rules shared with the GitHub Actions script
-│ │ ├── automationMatching.ts # Keyword matching for comment automation rules
+│ │ ├── automationMatching.ts # Keyword and any-comment matching for comment automation rules
+│ │ ├── automationRules.ts # Rule checks: keywords for each mode, followers-only texts
│ │ ├── automationDelivery.ts # What each Instagram answer means for a reply: retry, wait, stop or review
+│ │ ├── automationReview.ts # Finds a lost reply in the Instagram conversation
+│ │ ├── automationHealth.ts # Reply queue health and when it warrants a warning
│ │ ├── metaWebhookSignature.ts # X-Hub-Signature-256 check for Meta's webhooks
│ │ └── rateLimit/ # Rate limit rules, algorithms and Lua scripts
│ ├── types/
diff --git a/backend/tests/lib/automationMatching.test.ts b/backend/tests/lib/automationMatching.test.ts
index d67c6b3..69e15fb 100644
--- a/backend/tests/lib/automationMatching.test.ts
+++ b/backend/tests/lib/automationMatching.test.ts
@@ -10,7 +10,8 @@ function rule(overrides: Partial<MatchableRule> = {}): MatchableRule {
test('an any-comment rule answers every comment with something in it, emoji included, and names no keyword', () => {
const any = rule({ matchMode: 'any', keywords: [] });
assert.deepEqual(ruleMatch('love this', any), { rule: any, keyword: null });
- assert.deepEqual(ruleMatch('🔥', any), { rule: any, keyword: null });
+ // a comment of one emoji, written as its code point
+ assert.deepEqual(ruleMatch('\u{1F525}', any), { rule: any, keyword: null });
assert.equal(ruleMatch(' ', any), null);
});
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 9786d88..3799033 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -32,8 +32,10 @@
│ └── Errors: errorHandler -> { success, code, message, ... } │
│ │
│ Cron handlers (wrangler.toml triggers, jobs/scheduled.ts): │
-│ ├── */5 * * * * -> on :00 :15 :30 :45 publishDue(), then │
-│ │ automationProcessor.run() (reply sweep) │
+│ ├── * * * * * -> automationProcessor.run(), then │
+│ │ automationFollowups.run() (dispatch) │
+│ ├── */5 * * * * -> on :00 :15 :30 :45 publishDue(); on the │
+│ │ other minutes automationReconciler.run() │
│ └── 0 0 * * * -> token refresh, retention purge │
└──────┬──────────┬──────────────┬────────────────────────────────┘
│ │ │
@@ -111,11 +113,20 @@ Cloudflare scheduler fires cron trigger
-> ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime)) [jobs/scheduled.ts]
-> createServices(service-role Supabase, Redis, config, cron context)
-> cronPlan(cron, scheduledTime)
- -> '*/5 * * * *' at minutes 0, 15, 30, 45: publish, then sweep 3 replies if nothing was due
- -> '*/5 * * * *' at the other minutes: automationProcessor.run()
- -> claim due reply jobs (at most half the batch per account), reserve within limits,
- send the private reply, record the outcome [see data-flows/AUTOMATION.md]
- -> publishing:
+ -> '* * * * *': dispatch
+ automationProcessor.run() [50 subrequests, stops starting sends after 50 seconds]
+ -> claim due reply jobs (accounts take turns; paused, cooling down or limited
+ accounts 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]
+ -> claim due follow-ups, check the follow, send the link or a reminder
+ -> '*/5 * * * *' at the other minutes: reconcile
+ automationReconciler.run()
+ -> expire overdue replies (7 days) and follow-ups (24 hours)
+ -> look for up to 4 Needs review replies in the Instagram conversation;
+ a match is marked accepted, nothing is ever sent
+ -> log the queue's health, and a warning when replies wait too long
+ -> '*/5 * * * *' at minutes 0, 15, 30, 45: publish
scheduledPublisher.publishDue()
-> posts.listDue(), posts.listStale(cutoff) [no userId filter - scans all users;
stale = publishing, claim older than 20 minutes]
@@ -131,7 +142,8 @@ Cloudflare scheduler fires cron trigger
-> for each expiring token: refreshLongLivedToken()
-> accounts.updateById(id, { accessToken, tokenExpiresAt })
retention.purge()
- -> delete automation comments older than 90 days, audit events older than a year
+ -> delete automation comments older than 90 days in batches of 1,000 (up to 20,000 a day),
+ audit events older than a year
```
## Webhook Lifecycle (Instagram Comments)
@@ -140,9 +152,10 @@ Cloudflare scheduler fires cron trigger
Meta -> POST /api/webhooks/instagram
-> CORS, request id, security headers, clients, per-IP rate limit (no requireAuth)
-> verifyMetaWebhook: 1 MB limit, X-Hub-Signature-256 over the raw body [401 when wrong]
- -> automationWebhook.ingest(): rules for the Instagram account, match, store every comment once
+ -> automationWebhook.ingest(): rules for the Instagram account, match, store every comment once;
+ a message answering a followers-only reply creates a follow-up job
-> 200 { success: true } [5xx when storing fails; Meta retries]
- -> ctx.waitUntil(automationProcessor.run({ ids })) the new matched comments, after the response
+ -> ctx.waitUntil(automationProcessor.run({ ids }), then automationFollowups.run({ ids })) after the response
```
The full flow, limits and failure handling are in `docs/architecture/data-flows/AUTOMATION.md`.
@@ -155,7 +168,7 @@ The full flow, limits and failure handling are in `docs/architecture/data-flows/
| YouTube/Instagram accounts | `accounts` table, `data` jsonb | Flexible schema across platforms |
| User settings (GitHub repository) | `settings` table, `value` jsonb | Generic key-value per user |
| Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at |
-| Comment automation rules, received comments, reply attempts, account controls | `automation_rules`, `automation_comments`, `automation_attempts`, `automation_accounts` tables | The comment rows are also the reply queue, so dedupe, claims and limits are enforced in one database |
+| Comment automation rules, received comments, reply attempts, follow-up messages, account controls | `automation_rules`, `automation_comments`, `automation_attempts`, `automation_followups`, `automation_accounts` tables | The comment rows are also the reply queue, so dedupe, claims and limits are enforced in one database |
| Audit events | `audit_events` table | Who connected, removed or changed what; kept a year |
| Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls |
| Auth email counts | Upstash Redis (`email:day:` / `email:to:` keys, addresses hashed) | Caps verification emails at the provider's free daily quota |
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index 4f811fd..448a449 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -4,12 +4,21 @@
```toml
[triggers]
-crons = ["*/5 * * * *", "0 0 * * *"]
+crons = ["* * * * *", "*/5 * * * *", "0 0 * * *"]
```
-Both cron triggers invoke the `scheduled` export from `backend/server.ts`, which hands the cron expression and the run's scheduled time to `runScheduledJob(cron, env, scheduledTime)` in `backend/jobs/scheduled.ts`. The expressions are constants there (`EVERY_FIVE_MINUTES_CRON`, `DAILY_CRON`) and must match `wrangler.toml` character for character; `backend/tests/jobs/scheduled.test.ts` checks both.
+Every cron trigger invokes the `scheduled` export from `backend/server.ts`, which hands the cron expression and the run's scheduled time to `runScheduledJob(cron, env, scheduledTime)` in `backend/jobs/scheduled.ts`. The expressions are constants there (`EVERY_MINUTE_CRON`, `EVERY_FIVE_MINUTES_CRON`, `DAILY_CRON`) and must match `wrangler.toml` character for character; `backend/tests/jobs/scheduled.test.ts` checks all three. Cron Triggers run on UTC.
-The Cloudflare account has used all five cron triggers the Workers Free plan allows (two here, three on other Workers), so the Worker cannot add a trigger. One five minute trigger carries two jobs instead: `cronPlan(cron, scheduledTime)` sends the runs at minutes 0, 15, 30 and 45 to scheduled publishing, as before, and every other run to the comment reply queue. Each run is its own invocation with its own 50 subrequests, so the jobs never share a budget except on the quarter-hour runs (see ADR-040).
+The Workers Free plan allows five cron triggers per Cloudflare account. This Worker uses three; on 2026-10-16 the project's account had one more on another Worker, which leaves one free (ADR-043). Each trigger firing is its own invocation with its own 50 subrequests and counts as one Worker request: 1,440 a day for the dispatch, 288 for the five minute trigger and 1 for the daily one.
+
+| Trigger | Plan (`cronPlan`) | Job | Responsibility |
+|---|---|---|---|
+| `* * * * *` | `dispatch` | `automationProcessor.run()`, then `automationFollowups.run()` | Queue dispatch and recovery: due replies and follow-ups, 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 |
+
+Cron jobs coordinate and recover; they are not a second delivery pipeline. The dispatch sends through the same claim, reservation and finish as the webhook, so its runs, the webhook's runs and a retry can overlap without sending anything twice, and the reconciler only reads from Instagram.
## The Cron Entry Point (`backend/jobs/scheduled.ts`)
@@ -17,27 +26,29 @@ A cron run uses the same services as the API, built from the Worker env instead
```ts
export function cronPlan(cron: string, scheduledTime: number): CronPlan {
+ if (cron === EVERY_MINUTE_CRON) return 'dispatch';
if (cron === DAILY_CRON) return 'daily';
if (cron !== EVERY_FIVE_MINUTES_CRON) return 'none';
- return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish_then_sweep' : 'sweep';
+ return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish' : 'reconcile';
}
export async function runScheduledJob(cron: string, env: Env, scheduledTime = Date.now()): Promise<void> {
// ...
const plan = cronPlan(cron, scheduledTime);
- if (plan === 'sweep') {
- await sweepReplies(services, context);
- } else if (plan === 'publish_then_sweep') {
- const run = await services.scheduledPublisher.publishDue();
- if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH);
+ if (plan === 'dispatch') {
+ await dispatch(services, context);
+ } else if (plan === 'publish') {
+ await services.scheduledPublisher.publishDue();
+ } else if (plan === 'reconcile') {
+ await services.automationReconciler.run();
} else if (plan === 'daily') {
await services.tokenRefresh.refreshExpiringInstagramTokens();
- await services.retention.purge();
+ await services.retention.purge(Date.now(), { commentBatches: RETENTION_BATCHES });
}
}
```
-`cronContext(cron)` builds the `RequestContext` a request would have: a `cron-<uuid>` request id, a 14 minute deadline signal (under the Worker's 15 minute limit for scheduled events) and a logger bound to the request id and the cron expression. Every log line of the run carries that id.
+`cronContext(cron)` builds the `RequestContext` a request would have: a `cron-<uuid>` request id, a 14 minute deadline signal (under the Worker's 15 minute limit for scheduled events) and a logger bound to the request id and the cron expression. Every log line of the run carries that id, and every run but the dispatch ends with `cron run finished` and its duration.
## Cron Handlers
@@ -65,13 +76,26 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish
**Concurrency safety:** The claim is one conditional UPDATE, so when the Worker cron and GitHub Actions overlap, the second run to claim a post gets no row back and skips it. The 20 minute lease is longer than the 14 minute deadline of both schedulers, so a run that is still working is never taken over.
-### `*/5 * * * *` - Comment Reply Sweep
+### `* * * * *` - Reply Dispatch
+
+**Functions:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`, then `automationFollowups.run()` in `backend/services/automationFollowupProcessor.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.
+
+- 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).
+- 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.
+
+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.
-**Function:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`
+### `*/5 * * * *` off the quarter hour - Reply Queue Reconciliation
-Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The sweep sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, and jobs whose run stopped. It claims up to `AUTOMATION_BATCH_SIZE` due comments (10 by default), at most half of them from one account, and settles each one before the next. It has the run's 50 subrequests (48 after a publishing run with nothing due) and stops starting sends after 10 minutes, handing any unstarted job back to the queue. On the quarter-hour runs it sweeps only when publishing had nothing to do, and then only 3, because publishing spends part of the run's 50 subrequests. With nothing due, a sweep is one database call.
+**Function:** `automationReconciler.run()` in `backend/services/automationReconciler.ts`
-A run that stops is recovered by the next one: a comment left `processing` for more than 20 minutes is claimed again, and one left `sending` becomes `needs_review`, because its reply may have reached Instagram. `AUTOMATION_PAUSED=true` makes every sweep return without claiming anything.
+1. `expire_automation_jobs(500)`: replies whose 7 days ran out and follow-ups whose 24 hours ran out become `expired` in one call, without a run claiming each one. Rows a run holds are skipped and settled by that run.
+2. Looks for up to four Needs review replies in their conversation on Instagram (three subrequests each) and marks the ones found as accepted; the rest keep a note for the person. It never sends. The rules are in `docs/architecture/data-flows/AUTOMATION.md` (Duplicates, Ambiguity and Reconciliation).
+3. `automation_queue_health()` reads the queue through its partial indexes and the run logs it as `automation reconcile`. When the oldest due reply has waited over 10 minutes, or jobs are held by stopped runs, it logs one `automation queue behind` warning.
### `0 0 * * *` - Instagram Token Auto-Refresh and Retention
@@ -85,7 +109,7 @@ A run that stops is recovered by the next one: a comment left `processing` for m
One failed account is logged and skipped; it never stops the others. `backend/tests/services/tokenRefreshService.test.ts` covers the selection and the updates.
-After the refresh, `retention.purge()` in `backend/services/retentionService.ts` deletes received comments older than 90 days (their reply attempts go with them) and audit events older than a year, across all users.
+After the refresh, `retention.purge()` in `backend/services/retentionService.ts` deletes received comments older than 90 days (their reply attempts and follow-ups go with them) and audit events older than a year, across all users. Comments are deleted by `purge_automation_comments` in batches of 1,000, oldest first, at most 20 batches a run; a larger backlog is left for the next day and the log says so (`commentsLeft`).
**Token lifecycle:**
- Instagram issues long-lived tokens valid for 60 days
@@ -113,7 +137,7 @@ The same publishing logic also runs via `scripts/publish-scheduled.ts` in GitHub
## Adding a New Cron Job
-The account has no cron trigger to spare on the Workers Free plan, so a new job is a new plan in `cronPlan()` on one of the existing triggers, chosen by the scheduled time, rather than a new trigger. Check the account's count first (Workers and Pages, each Worker's Triggers) if you run your own instance on a paid plan or an account with free slots.
+The Workers Free plan allows five cron triggers per account, and this Worker uses three. A new job is usually a new plan in `cronPlan()` on one of the existing triggers, chosen by the scheduled time, rather than a new trigger. Count the triggers on the account first (each Worker's Triggers in the Cloudflare dashboard, or the Workers schedules API); deploying a Worker with more triggers than the account has left fails.
1. Add a plan and its time rule to `cronPlan()` in `backend/jobs/scheduled.ts`, for example a weekly report on the daily trigger:
```ts
diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.md
index 7a0ccd4..1d7d573 100644
--- a/docs/architecture/backend/HONO.md
+++ b/docs/architecture/backend/HONO.md
@@ -8,8 +8,11 @@ The backend is a single Hono application exported as a Cloudflare Workers module
// the Worker's two entry points: HTTP requests go through the pipeline in app.ts, cron triggers to jobs/
export default {
fetch: app.fetch,
+
+ // wrangler.toml schedules: the reply dispatch every minute, due posts on the quarter hour with queue checks on the
+ // other five minute runs, and daily upkeep
async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
- ctx.waitUntil(runScheduledJob(event.cron, env));
+ ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime));
},
} satisfies ExportedHandler<Env>;
```
@@ -32,7 +35,7 @@ The backend is split into layers, each with one job. `REQUEST_PIPELINE.md` is th
| `services/` | Feature services (`<feature>Service.ts`, `scheduledPublisher.ts`) the platform modules in `youtube/`, `instagram/` and `reddit/`, and the auth email modules in `email/` (see `SERVICES.md`) |
| `repositories/` | Data access, one repository per table or cache (`<table>Repository.ts`), and the query helpers in `query.ts` |
| `database/` | `supabase.ts` (`getSupabase`, `getSupabaseAuth`) and `redis.ts` (`getRedis`, `getRateLimitRedis`) |
-| `jobs/` | `scheduled.ts`: the cron entry point, `runScheduledJob(cron, env)` |
+| `jobs/` | `scheduled.ts`: the cron entry point, `runScheduledJob(cron, env, scheduledTime)` |
| `lib/` | Helpers with no HTTP or database code: `errors.ts`, `logger.ts`, `config.ts`, `redact.ts`, `safeAccount.ts`, `oauthState.ts`, `webhookSignature.ts`, `analyticsMath.ts`, `rateLimit/` |
| `types/` | `env.ts` (`Env`), `app.ts` (`AppEnv`, `AppVariables`, `AppContext`), `context.ts` (`RequestContext`), `authHook.ts` (the Send Email hook payload and error body) |
@@ -174,7 +177,8 @@ Worker variables are declared in `Env` and reach the code through `lib/config.ts
if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);
// in the cron entry point, jobs/scheduled.ts
-const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);
+const clients = { supabase: getSupabase(env), redis: getRedis(env), rateLimitRedis: getRateLimitRedis(env) };
+const services = createServices(clients, readConfig(env), context);
```
The Supabase and Redis credentials are read by `database/supabase.ts` and `database/redis.ts`.
diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.md
index 3a67557..a1bff6a 100644
--- a/docs/architecture/backend/REQUEST_PIPELINE.md
+++ b/docs/architecture/backend/REQUEST_PIPELINE.md
@@ -54,7 +54,7 @@ Services never see the Hono context. A controller hands them a `RequestContext`
The user id is passed to service methods explicitly (`accounts.refresh(userId, accountId)`), never read from the request body.
-Cron jobs build the same context in `jobs/scheduled.ts`, with a `cron-` request id and a 14 minute deadline. The Overview's background warming outlives the response, so it uses its own 25 second deadline instead of the request signal. `inBackground(c, label, work)` in `controllers/http.ts` does the same for any work after a response: it builds services with a fresh context (the request id, a 25 second deadline, a logger tagged with the label) and runs the work under `ctx.waitUntil()`, logging a failure because nobody is waiting for it. The Instagram webhook and the automation retry route use it to send replies.
+Cron jobs build the same context in `jobs/scheduled.ts`, with a `cron-` request id and a 14 minute deadline. The Overview's background warming outlives the response, so it uses its own 25 second deadline instead of the request signal. `inBackground(c, label, work)` in `controllers/http.ts` does the same for any work after a response: it builds services with a fresh context (the request id, a 25 second deadline, a logger tagged with the label) and runs the work under `ctx.waitUntil()`, logging a failure because nobody is waiting for it. The Instagram webhook and the automation retry route use it to send replies and follow-ups.
## Composition
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 70c4a70..f893ef0 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -38,15 +38,16 @@ Registered on `publicRoutes` in `routes/index.ts`.
| GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | OAuth code exchange; always redirects the browser back to the accounts page with `ig_connected=true`, `ig_connected=reconnected` (the account was already connected and its token was renewed) or `ig_error=<reason>`, never a JSON error |
| POST | `/api/auth/email-hook` | `authHookController.sendAuthEmail` (`routes/authHookRoutes.ts`) | Supabase Auth's Send Email hook: sends sign-up, password reset and other auth emails through Resend. Answers `{}` |
| GET | `/api/webhooks/instagram` | `instagramWebhookController.verifyInstagramWebhook` (`routes/instagramWebhookRoutes.ts`) | Meta's webhook check: answers the bare `hub.challenge` as text when `hub.mode=subscribe` and `hub.verify_token` matches `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`; 403 otherwise, 503 when the token is not set |
-| POST | `/api/webhooks/instagram` | `instagramWebhookController.receiveInstagramWebhook` | Instagram comment notifications, signed by Meta. Stores them, answers `{ success: true }`, then sends the matched replies |
+| POST | `/api/webhooks/instagram` | `instagramWebhookController.receiveInstagramWebhook` | Instagram comment notifications and message events (messages and postbacks), signed by Meta. Stores the comments and a follow-up for each message that answers a followers-only reply, answers `{ success: true }`, then sends the matched replies and the follow-ups |
### Instagram webhook
Meta calls this route, not a browser:
- **Authentication.** `middleware/metaWebhook.ts` (`verifyMetaWebhook`) checks `X-Hub-Signature-256` (HMAC-SHA256 of the raw body) against `INSTAGRAM_APP_SECRET`, or `META_APP_SECRET` when set. No JWT.
-- **Statuses.** `200` once every comment is stored (duplicates included). `400` for a body over 1 MB, malformed JSON, or an `object` other than `instagram`. `401` for a missing or wrong signature. `503` when no app secret is set. `500` when storing fails; Meta delivers the notification again for up to 36 hours.
-- **After the response.** The new matched comments are sent with `ctx.waitUntil()` and their own 25 second deadline; anything left is sent by the 5 minute cron.
+- **Statuses.** `200` once every comment and follow-up is stored (duplicates included). `400` for a body over 1 MB, malformed JSON, or an `object` other than `instagram`. `401` for a missing or wrong signature. `503` when no app secret is set. `500` when storing fails; Meta delivers the notification again for up to 36 hours.
+- **Message events.** Echoes, the account's own messages and deleted messages are skipped, and message text is never read or stored. One database call per account turns the senders into follow-up jobs, and a redelivered message is dropped.
+- **After the response.** The new matched comments and follow-ups are sent with `ctx.waitUntil()` and their own 25 second deadline; anything left is sent by the every minute cron.
See `docs/architecture/data-flows/AUTOMATION.md`.
@@ -162,17 +163,17 @@ Controllers call `AutomationService` (`services/automationService.ts`). Every ro
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/automations` | `automationRoutes.ts`, `automationController.getAutomations` | The user's rules, each Instagram account's automation state (`paused`, `cooldownUntil`, `cooldownReason`, `subscribedAt`) and the server settings (`webhookConfigured`, `paused`, `limits`) |
-| POST | `/api/automations/rules` | `automationController.createAutomationRule` | Create a rule (`accountId`, `name`, `keywords`, `replyText`, optional `matchMode`, `caseSensitive`, `mediaIds`, `linkUrl`, `enabled`, `hourlyLimit`). 404 unless the account is one of the user's Instagram accounts; 400 when the reply and link pass 1,000 bytes. An enabled rule also subscribes the account to comment events |
+| GET | `/api/automations` | `automationRoutes.ts`, `automationController.getAutomations` | The user's rules, each Instagram account's automation state (`paused`, `cooldownUntil`, `cooldownReason`, `subscribedAt`, `limitedUntil`, `messagesSubscribed`) and the server settings (`webhookConfigured`, `paused`, `limits`) |
+| POST | `/api/automations/rules` | `automationController.createAutomationRule` | Create a rule (`accountId`, `name`, `keywords`, `replyText`, optional `matchMode` (`contains`, `exact` or `any`), `caseSensitive`, `mediaIds`, `linkUrl`, `enabled`, `hourlyLimit`, `requireFollow`, `followPromptText`, `notFollowingText`). 404 unless the account is one of the user's Instagram accounts; 400 when the reply and link pass 1,000 bytes, when `any` has keywords or another mode has none, or when a followers-only rule lacks either text. An enabled rule also subscribes the account to comment events, and to message events while a followers-only rule is on |
| PUT | `/api/automations/rules/:id` | `automationController.updateAutomationRule` | Change any of the fields sent; the account stays. Turning it on subscribes the account if needed |
| DELETE | `/api/automations/rules/:id` | `automationController.deleteAutomationRule` | Delete a rule; its past comments keep their status |
| 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 and return `{ matched, keyword, message, messageBytes, maxMessageBytes }`. Stores and sends nothing |
-| GET | `/api/automations/activity` | `automationController.listAutomationActivity` | Received comments, newest first. 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; 409 for any other state |
+| 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 |
| 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 (`POST /<ig-id>/subscribed_apps?subscribed_fields=comments`); 502 when Instagram refuses. Covered by the quota rate limit |
+| 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 |
### Settings
| Method | Path | File | Purpose |
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 58d22a4..ff33137 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -42,28 +42,33 @@ 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, account controls, audit | `overview`, `createRule`, `updateRule`, `duplicateRule`, `deleteRule`, `test`, `activity`, `stats`, `retry`, `setPaused`, `subscribe` |
-| `automationWebhook` | `automationWebhookService.ts` | automation rules, comments | `challengeAnswer` (Meta's verification), `ingest` (store a webhook's comments; no user) |
-| `automationProcessor` | `automationProcessor.ts` | comments | `run({ ids?, limit? })` (send due private replies; webhook, retry route and 5 minute cron) |
-| `retention` | `retentionService.ts` | comments, audit | `purge` (daily cron) |
+| `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) |
+| `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) |
+| `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` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, 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`, `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`)
+### Comment automation (`automationService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.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), `coversMedia`, `pickRule` (rules for the post first, then oldest) |
-| `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), `retryDelayMs`, `cooldownFromUsage`, `composeReply`, `messageBytes`, and the constants: 1,000 byte messages, the 7 day window, the 20 minute claim lease, 5 tries |
+| `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) |
+| `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) |
| `metaWebhookSignature.ts` | `verifyMetaSignature` and the constant-time `verifyTokenMatches` |
-`automationService` checks every account and item against the user before acting, refuses a reply and link over 1,000 bytes, records each change in `audit_events`, and subscribes an account to comment events when one of its rules is first turned on (a refusal is logged and the rule is still saved). `automationProcessor` returns at once when `AUTOMATION_PAUSED` is set, settles one job at a time, and logs a job's database failure and moves on, leaving the job to its lease.
+`automationService` checks every account and item against the user before acting, refuses a reply and link over 1,000 bytes, records each change in `audit_events`, and subscribes an account to comment events when one of its rules is first turned on, adding message events while an enabled followers-only rule exists (a refusal is logged and the rule is still saved; when Instagram refuses messages it subscribes to comments only). `automationProcessor` and `automationFollowups` return at once when `AUTOMATION_PAUSED` is set, settle one job at a time, and log a job's database failure and move on, leaving the job to its lease. `automationFollowups` asks Instagram whether the person follows the account before each follow-up, and never sends the link when Instagram cannot say. `automationReconciler` never sends anything: it marks a lost reply accepted only when it finds the reply in the conversation.
### Accounts (`accountService.ts`, `accountFactory.ts`)
@@ -145,7 +150,7 @@ There is no barrel: services and tests import each module directly, and each mod
| `instagramCaptions.ts` | Hashtag analysis and caption length correlation |
| `instagramAnalytics.ts` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers |
| `instagramPublishing.ts` | `buildMediaParams` (one helper per media type) and the Graph publishing calls: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer`, `fetchPublishingLimit` |
-| `instagramMessaging.ts` | `sendPrivateReply(igUserId, token, commentId, text, signal)`: `POST /<ig-id>/messages` with the token as a Bearer header and a 10 second timeout. It answers a `SendResult` instead of throwing, because each Graph error code leads somewhere different, and never repeats the request; a timeout or lost connection is `ambiguous`, a fetch the runtime refused at the subrequest cap is `not_sent`. `subscribeToComments` calls `POST /<ig-id>/subscribed_apps?subscribed_fields=comments` and throws `UpstreamError` unless Instagram answers `success: true` |
+| `instagramMessaging.ts` | `sendMessage(igUserId, token, recipient, text)`: `POST /<ig-id>/messages` to a comment (`comment_id`) or a person (`id`) with the token as a Bearer header and a 10 second timeout. It answers a `SendResult` instead of throwing, because each Graph error code leads somewhere different, and never repeats the request; a timeout or lost connection is `ambiguous`, a fetch the runtime refused at the subrequest cap is `not_sent`. `sendPrivateReply(igUserId, token, commentId, text)` sends to a comment. `readFollowStatus(igsid, token)` reads `is_user_follow_business` with a 5 second timeout and answers following, not following, retry, not authorized or unverifiable. `listConversationMessages(igUserId, token, igsid, signal)` reads the account's latest messages with one person through the Conversations API. `subscribeToWebhooks(igUserId, token, fields, signal)` calls `POST /<ig-id>/subscribed_apps` with `comments` or `comments,messages` and throws `UpstreamError` unless Instagram answers `success: true` |
A Graph API error becomes an `UpstreamError` (502) with Instagram's message; a cancelled or timed out call becomes an `UpstreamTimeoutError` (504).
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index def0e66..1375d68 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -8,13 +8,13 @@ main = "server.ts"
compatibility_date = "2025-01-01"
[triggers]
-crons = ["*/5 * * * *", "0 0 * * *"]
+crons = ["* * * * *", "*/5 * * * *", "0 0 * * *"]
```
- `name` - the Worker name as deployed on Cloudflare; also determines the default URL
- `main` - entry point file (`backend/server.ts`). Wrangler bundles it with esbuild, which strips the TypeScript types without checking them; `npm run typecheck` is the check
- `compatibility_date` - pins the Workers runtime API version
-- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`). The five minute trigger carries both scheduled publishing (on the quarter hour) and the comment reply sweep, because the account already uses the five cron triggers the Workers Free plan allows
+- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`). The every minute trigger sends waiting comment replies and follow-ups; the five minute trigger publishes due posts on the quarter hour and checks the reply queue on its other runs; the daily trigger refreshes tokens and deletes old records. The Workers Free plan allows five cron triggers per account and this Worker uses three, so a self-hoster with other Workers should count the triggers on their account first. Each cron run counts as a Worker request: the every minute trigger adds 1,440 a day (about 1.4% of the Free plan's 100,000), the five minute one 288 and the daily one 1
## Worker Export Format
@@ -63,7 +63,7 @@ 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 sweep; default `10`, at most `15` (each costs three of the free plan's 50 subrequests) |
+| `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) |
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.
@@ -121,7 +121,7 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating
4. **CPU time limit.** On the Workers Free plan each invocation gets 10 ms of CPU time (Workers Paid: 30 seconds by default, up to 5 minutes). Time waiting on `fetch` does not count, so I/O-bound work fits; long synchronous work is killed. Use async/await for all I/O.
-5. **Subrequests.** On the Workers Free plan an invocation can make 50 subrequests (each `fetch`, including Supabase and Redis calls); Workers Paid allows 10,000. A webhook request, a sweep and a publishing run each count separately. `AUTOMATION_BATCH_SIZE` is capped at 15 for this reason, and a fetch the runtime refuses at the cap is recorded as not sent rather than as an unknown outcome.
+5. **Subrequests.** On the Workers Free plan an invocation can make 50 subrequests (each `fetch`, including Supabase and Redis calls); Workers Paid allows 10,000. A webhook request, a dispatch run, a reconcile run and a publishing run each count separately. `AUTOMATION_BATCH_SIZE` is capped at 15 for this reason, and a fetch the runtime refuses at the cap is recorded as not sent rather than as an unknown outcome.
6. **`ctx.waitUntil()` in cron handlers and after responses.** Cron handlers must use `ctx.waitUntil(promise)` for async work. Without it, the Worker may terminate before the work completes. After an HTTP response, `waitUntil` keeps the Worker running for at most 30 seconds; `inBackground()` in `controllers/http.ts` gives such work its own 25 second deadline.
diff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.md
index 58c199a..1d8c879 100644
--- a/docs/architecture/data-flows/AUTOMATION.md
+++ b/docs/architecture/data-flows/AUTOMATION.md
@@ -2,21 +2,24 @@
## Overview
-An account owner writes a rule: keywords, which posts it covers, and a reply with an optional link. When someone comments one of the keywords on a post or reel of a connected Instagram professional account, Meta sends the comment to the Worker's webhook, and the Worker sends the commenter a private reply through Instagram's messages endpoint.
+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.
```
-Instagram comment
- -> Meta comments 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 only; anything else is counted and dropped
- -> automationWebhook.ingest rules for the Instagram account -> match -> store every comment (dedupe)
- -> 200 {"success":true} only after the comments are stored; a failure answers 5xx and Meta retries for 36 hours
- -> waitUntil: automationProcessor.run({ ids }) the new matched comments, after the response
+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
+ -> 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 5 minutes: automationProcessor.run() retries, waits, recovery
+ -> 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
+ -> 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 reply. There is no Cloudflare Queue (ADR-040).
+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).
## What Instagram Allows
@@ -25,36 +28,46 @@ 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`; Twiligent's OAuth already asks for all three | Private replies, webhook fields |
-| Access level | Advanced Access for the `comments` webhook field; Business verification for production; the app must be Live | Webhooks setup |
+| 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 |
+| 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; a follow-up only after the person replies, within 24 hours | Private replies |
+| 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 |
-| Rate limit | 750 private replies an hour per professional account for posts and reels | Graph API rate limiting, Business Use Case limits |
+| 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 |
+| 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.
-## Setup: Getting Comments to the Worker
+## Setup: Getting Comments and Messages to the Worker
-1. **The app-level webhook** (Meta dashboard, Instagram, API setup with Instagram login, Configure webhooks): callback URL `https://<worker>/api/webhooks/instagram`, the Verify Token from `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, and the `comments` field. Meta checks the URL with `GET ?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...`; `automationWebhook.challengeAnswer()` compares the token in constant time and answers the bare challenge.
-2. **The account-level subscription**: Instagram sends an account's comments only after `POST /<ig-id>/subscribed_apps?subscribed_fields=comments` with that account's token. Twiligent calls it when a rule is first turned on for the account, and from the "Turn on comment events" button (`POST /api/automations/accounts/:accountId/subscribe`). The time is kept in `automation_accounts.subscribed_at`. If Instagram refuses, the rule is still saved and the page shows the account as not receiving comments.
+1. **The app-level webhook** (Meta dashboard, Instagram, API setup with Instagram login, Configure webhooks): callback URL `https://<worker>/api/webhooks/instagram`, the Verify Token from `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, and the `comments` field. Followers-only rules also need the `messages` field. Meta checks the URL with `GET ?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...`; `automationWebhook.challengeAnswer()` compares the token in constant time and answers the bare challenge.
+2. **The account-level subscription**: Instagram sends an account's events only after `POST /<ig-id>/subscribed_apps?subscribed_fields=...` with that account's token. Twiligent asks for `comments`, and for `comments,messages` while an enabled followers-only rule of the account exists. It subscribes when a rule is turned on or the followers-only option changes, and from the "Turn on comment events" or "Turn on message events" button (`POST /api/automations/accounts/:accountId/subscribe`). The time and the fields Instagram confirmed are kept in `automation_accounts.subscribed_at` and `subscribed_fields`. If Instagram refuses `messages`, Twiligent subscribes to `comments` alone and the account shows "Follow checks off". If Instagram refuses entirely, the rule is still saved and the page shows the account as not receiving comments.
+
+Selecting `messages` in the Meta dashboard sends every direct message to every connected account to the Worker. Each one is a Worker request and one database call, so select it only when a followers-only rule is used.
Signatures: Instagram Login apps sign with the Instagram app secret (`INSTAGRAM_APP_SECRET`). `META_APP_SECRET`, the Meta app's own secret, is accepted as a second key because the dashboard shows both and developers report each in use.
## Intake: `POST /api/webhooks/instagram`
1. `verifyMetaWebhook` refuses a body over 1 MB, reads the raw bytes, and checks `X-Hub-Signature-256` against each configured secret with `crypto.subtle.verify` (constant time). No secret configured answers 503; a bad signature 401, before any database work.
-2. `parseInstagramWebhook` refuses a body whose `object` is not `instagram` (400). Inside it, each `comments` change becomes an event (comment id from `id` or `comment_id`, author, text, media, the entry's account id and `time`); other fields and malformed changes are counted as unsupported and dropped.
-3. `automationWebhook.ingest()` groups the events 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.
+2. `parseInstagramWebhook` refuses a body whose `object` is not `instagram` (400). Inside it:
+ - each `comments` change becomes an event (comment id from `id` or `comment_id`, author, text, media, the entry's account id and `time`);
+ - each `messaging` event with a `message` or a `postback` becomes a message event (sender, message id, the event's timestamp). Its text is never read. The account's own echoes, `is_self` test messages and deleted messages are skipped;
+ - 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`
- no text: `ignored`, `no_text`
- - no rule matches: `ignored`, `no_match`, stored without its text or author
- - a match: `queued`, with the rule, the author and the text (at most 2,200 characters)
+ - 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.
-6. The controller answers `200 {"success":true}` and hands the new queued ids to `inBackground()`, which builds services with their own 25 second deadline (the request's signal ends with the response) and runs `automationProcessor.run({ ids })` under `ctx.waitUntil()`.
+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).
If storing fails, the request fails with 5xx, and Meta delivers the notification again later. Nothing is acknowledged that is not stored.
@@ -65,22 +78,37 @@ If storing fails, the request fails with 5xx, and Meta delivers the notification
- Text is normalised with NFKC (full-width letters fold to plain ones) and runs of spaces collapse; matching ignores case unless the rule says otherwise.
- `contains`: the keyword appears as whole words (a letter or digit on either side breaks the match, so GUIDE never matches GUIDELINES). Phrases work across spaces; regular expression characters are literal.
- `exact`: the whole comment equals the keyword once spaces, punctuation and emoji at its edges are removed.
-- A rule covers every post when `media_ids` is empty, or only the listed posts. Rules for the comment's post are tried before rules for every post, then oldest first; the first match wins. A comment never triggers a rule meant for another post.
-- `POST /api/automations/test` runs the same matching on a sample comment and returns the composed reply; it stores and sends nothing.
+- `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.
-## Delivery (`backend/services/automationProcessor.ts`)
+## Delivery of Private Replies (`backend/services/automationProcessor.ts`)
-`run({ ids?, limit? })` returns at once when `AUTOMATION_PAUSED` is true. Otherwise it claims up to the batch size and settles each job in turn, so each account's replies keep their order and the run never opens more than one connection to Instagram at a time:
+`run({ ids?, limit?, subrequests?, timeBudgetMs? })` returns at once when `AUTOMATION_PAUSED` is true. Otherwise it claims up to the batch size and settles each job in turn, so each account's replies keep their order and the run never opens more than one connection to Instagram at a time. It reports the subrequests it used, so the dispatch can give the rest to follow-ups.
-1. **Claim** (`claim_automation_comments`): due jobs (`queued` or `retry_wait` with `next_attempt_at <= now`) and jobs whose run stopped (`processing` for more than 20 minutes), oldest first, at most `perAccount` per account, locked with `FOR UPDATE SKIP LOCKED` so two runs never take the same job. The same call turns any `sending` job older than 20 minutes into `needs_review`. It returns the rule's reply and the account's token with each job.
+1. **Claim** (`claim_automation_comments`): due jobs (`queued` or `retry_wait` with `next_attempt_at <= now`) and jobs whose run stopped (`processing` for more than 20 minutes).
+ - Accounts with waiting jobs are found with a loose index scan, one probe per account, however long one account's queue is.
+ - Accounts that are paused, cooling down or at their hourly limit are left out, so their jobs wait in place instead of being claimed and handed back on every run.
+ - Each account's oldest due jobs are locked as they are read (`FOR UPDATE SKIP LOCKED`), so runs at the same moment take different jobs.
+ - Accounts take turns: each account's oldest job first, then each one's second, until the batch is full. An account alone can fill the batch; a busy one cannot hold back another.
+ - The same call turns any `sending` job older than 20 minutes into `needs_review`. It returns the rule's reply, its followers-only fields and the account's token with each job.
2. **Check** (`readinessPlan`): an expired comment becomes `expired`, a rule that was turned off or removed `skipped`, an account without a token `failed`. No limit is spent on these.
-3. **Reserve** (`reserve_automation_send`): one transaction under an advisory lock, so every Worker sees the same counts and two jobs cannot both take the last free send. In order: a paused account holds the job; an account cooldown waits for it; the commenter already got the daily number of replies from this account (counting other comments, not retries of this one) skips it; then the rule's, account's, user's and instance's hourly limits. When a scope is full, the job waits until the oldest send in that hour is an hour old. On success the job becomes `sending`, its attempts count goes up, and an `automation_attempts` row records the request before it leaves.
-4. **Send** (`sendPrivateReply`): `POST https://graph.instagram.com/v25.0/<ig-id>/messages` with `{ recipient: { comment_id }, message: { text } }` and the account's token as a Bearer header, 10 second timeout, never repeated inside the call. Only that timeout can cut it off: a run starts a send only with the whole timeout and 2 seconds to spare, so the run's own deadline never turns a send into an unknown outcome.
-5. **Finish** (`finish_automation_send`): records the outcome on the attempt and the comment in one transaction, and sets a cooldown or a hold on the account when the answer calls for one.
+3. **Reserve** (`reserve_automation_send`): one transaction under an advisory lock, so every Worker sees the same counts and two jobs cannot both take the last free send. In order: a paused account holds the job; an account cooldown waits for it; the commenter already got the daily number of replies from this account (counting other comments, not retries of this one) skips it; then the rule's, account's, user's and instance's hourly limits, counting private replies only. When a scope is full, the job waits until the oldest send in that hour is an hour old; a full account is also marked (`automation_accounts.limited_until`) so later claims leave its jobs alone. On success the job becomes `sending`, its attempts count goes up, and an `automation_attempts` row records the request, with the sha-256 digest of the exact text, before it leaves.
+4. **Send** (`sendPrivateReply`): `POST https://graph.instagram.com/v25.0/<ig-id>/messages` with `{ recipient: { comment_id }, message: { text } }` and the account's token as a Bearer header, 10 second timeout, never repeated inside the call. The text is the reply and link, or for a followers-only rule its request to follow and reply. Only the timeout can cut it off: a run starts a send only with the whole timeout and 2 seconds to spare, so the run's own deadline never turns a send into an unknown outcome.
+5. **Finish** (`finish_automation_send`): records the outcome on the attempt and the comment in one transaction, keeps who Instagram says received an accepted reply (`recipient_id`, else the commenter's id), starts the followers-only wait (`gate_status = 'awaiting_reply'`), and sets a cooldown or a hold on the account when the answer calls for one.
A database error on one job is logged and the run moves on; that job's claim or reservation expires and the recovery above picks it up.
-**Budgets.** Each run knows how many subrequests it may still make (the Workers Free plan allows 50 per invocation) and how long it may keep starting sends: a webhook's run gets what the request did not use (50, less 10 for the request's own middleware, less the intake's queries) and 20 seconds; a sweep gets 50 and 10 minutes. 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.
+**Budgets.** Each run knows how many subrequests it may still make (the Workers Free plan allows 50 per invocation) and how long it may keep starting sends:
+
+| 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 |
+
+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.
**Clocks.** New and retried jobs are due 30 seconds in the past, so a database clock slightly behind the Worker's still finds them due on the immediate run.
@@ -88,7 +116,7 @@ A database error on one job is logged and the run moves on; that job's claim or
| Instagram's answer | Comment | Attempt | Account |
|---|---|---|---|
-| 200 with `message_id` | `accepted`, `message_id` kept | `accepted` | |
+| 200 with `message_id` | `accepted`, `message_id` and recipient kept | `accepted` | |
| Codes 4, 17, 32, 613, 80002, 80006 or HTTP 429 | `retry_wait` until the cooldown ends | `rate_limited` | cooldown from `X-Business-Use-Case-Usage` (`estimated_time_to_regain_access`), else 15 minutes |
| Code 368 (temporarily blocked) | `retry_wait` | `rejected` | 24 hour cooldown |
| Codes 1, 2 or HTTP 5xx | `retry_wait` after 1, 2, 4, 8 minutes (at most an hour) plus up to 30 seconds; `failed` after 5 tries | `rejected` | |
@@ -101,26 +129,55 @@ A database error on one job is logged and the run moves on; that job's claim or
A wait that would end after the 7 day window makes the comment `expired` instead.
-## Duplicates and Ambiguity
+## Followers-Only Replies (`backend/services/automationFollowupProcessor.ts`)
+
+Instagram does not let an app check whether a commenter follows the account until that person messages it, so the check cannot happen before the first private reply. A followers-only rule therefore works in two steps, and Twiligent never says a follow was checked when it was not.
+
+1. **The private reply** sends the rule's first message (`follow_prompt_text`), with no link: for example "Follow this account, then reply to this message and the link is on its way." Once Instagram accepts it, the comment waits for the person's answer.
+2. **Their answer** arrives as a `messages` webhook event and becomes a follow-up job (see Intake). Their message gives Instagram's consent for the profile read and opens Instagram's 24 hour window.
+3. **The follow-up** is claimed like a reply (accounts take turns, paused and cooling accounts left out, `FOR UPDATE SKIP LOCKED`), then:
+ - **Check** (`followupReadiness`): the 24 hours ran out: `expired`; the rule was turned off or is no longer followers-only: `skipped`; the comment no longer waits (link sent or reminders used): `skipped`; no token: `failed`.
+ - **Follow check** (`readFollowStatus`): `GET /<igsid>?fields=is_user_follow_business` with the account's token as a Bearer header and a 5 second timeout. A read, so asking again is always safe.
+ - **Decide** (`followupMessage`):
+
+| Instagram says | Sent | Follow-up | Comment |
+|---|---|---|---|
+| Follows | The reply and link | `accepted`, kind `link` | `gate_status` `completed` |
+| Does not follow | The reminder (`not_following_text`) | `accepted`, kind `reminder` | one reminder counted; the second closes the wait (`closed`) |
+| Cannot say: consent error, no follow field, any other refusal | Nothing | `failed`, `follow_unverifiable`, with Instagram's reason | still waiting; a later message is checked again |
+| Token or permission refused | Nothing | `failed`, `not_authorized` | still waiting |
+| Rate limit, temporary error, no answer | Nothing | `retry_wait` 5 minutes, or `expired` past the window | still waiting |
+
+ - **Reserve** (`reserve_automation_followup`): a paused account holds it and a cooldown waits for it. Follow-ups use the Send API, not the private reply allowance, so the hourly reply limits do not count them (`automation_attempts.kind = 'followup'`).
+ - **Send** (`sendMessage`): `POST /<ig-id>/messages` with `{ recipient: { id: <igsid> }, message: { text } }`, 10 second timeout, never repeated. A slow follow check that leaves less than the send's whole timeout hands the job back unsent.
+ - **Finish** (`finish_automation_followup`): the same answer table as private replies, plus the comment's wait. A lost answer is `needs_review` and is never sent again without a person.
+
+Nothing about the follow is stored except the follow-up's outcome; the person's message text is never read or kept.
-- A notification Meta delivers twice is stored once: `unique (ig_user_id, comment_id)`.
-- A comment repeated inside one notification is stored once.
-- Two runs never send the same job: the claim locks rows, and the reservation only moves a job this run holds.
+## 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 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, and the owner decides after checking the conversation on Instagram. 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.
+- 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.
+- **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".
## Comment Status Lifecycle
```
ignored (no rule matched; final)
-queued -> processing -> sending -> accepted
- ^ | |-> retry_wait -> processing ...
- | | |-> failed | skipped | expired
- | | '-> needs_review (no answer, or the run stopped)
- | |-> queued (held: account paused) | retry_wait (limit, cooldown)
+queued -> processing -> sending -> accepted ----------------------------------------------.
+ ^ | |-> retry_wait -> processing ... |
+ | | |-> failed | skipped | expired followers-only:
+ | | '-> needs_review (no answer, or the run stopped) awaiting_reply
+ | | '-> accepted (found in the conversation) |-> completed (link sent)
+ | |-> queued (held: account paused) | retry_wait (limit, cooldown) '-> closed (reminders used)
| '-> skipped (rule off, recipient limit) | expired | failed (no token)
'-- retry by the owner (failed, skipped, needs_review, within 7 days)
+queued | retry_wait -> expired (the five minute expiry, without a claim)
```
| Status | Shown as | Meaning |
@@ -130,52 +187,75 @@ queued -> processing -> sending -> accepted
| `processing`, `sending` | Sending | A run holds it |
| `retry_wait` | Trying again | Waiting for a retry, a cooldown or an hourly limit |
| `accepted` | Accepted by Instagram | Instagram took the reply |
+| `accepted`, waiting for the person | Asked to follow | A followers-only reply; the link goes out when they reply and follow |
+| `accepted`, follow-up failed or for review | Follow-up failed, Needs review | The message after their answer did not go out, or may have |
+| `accepted`, `completed` | Link sent | Instagram confirmed the follow and accepted the link |
+| `accepted`, `closed` | Not following | Every reminder was used; the link was not sent |
| `failed` | Failed | Instagram refused it, or it failed 5 times |
| `needs_review` | Needs review | It may have been sent; check before retrying |
| `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.
+
## Limits and Controls
| Scope | Default | Set with |
|---|---|---|
-| Instance, per hour | 1,000 | `AUTOMATION_GLOBAL_HOURLY_LIMIT` |
-| User, per hour | 500 | `AUTOMATION_USER_HOURLY_LIMIT` |
-| Instagram account, per hour | 200 (Instagram allows 750) | `AUTOMATION_ACCOUNT_HOURLY_LIMIT`, at most 750 |
+| Instance, per hour | 1,000 private replies | `AUTOMATION_GLOBAL_HOURLY_LIMIT` |
+| User, per hour | 500 private replies | `AUTOMATION_USER_HOURLY_LIMIT` |
+| 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` |
-| Replies per webhook request or sweep | 10 | `AUTOMATION_BATCH_SIZE`, at most 15 |
+| 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.
| Control | Effect |
|---|---|
-| `AUTOMATION_PAUSED=true` | Nothing is sent on the instance; comments are still stored and matched |
-| Pause an account (Replies switch) | Its replies are held and go out when resumed, within the 7 days |
-| Turn a rule off | New comments stop matching it; its waiting replies are skipped |
-| Retry an item | Puts a failed, skipped or review item back in the queue and starts it at once |
+| `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 |
+| 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.
+
+**Throughput.** One dispatch sends up to the batch size, so the queue drains at up to 600 replies an hour with the default batch and 900 at the cap, on top of the replies the webhooks send at once. Before the every-minute dispatch, leftovers drained at 120 an hour.
-The batch cap of 15 comes from the Workers Free plan's 50 subrequests per invocation: each reply costs three (reserve, send, finish), plus the claim and the intake queries.
+## Observability
+
+| Signal | Where |
+|---|---|
+| Each reply and follow-up settled: ids, status, outcome, error codes | `automation reply settled`, `automation follow-up 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 |
+| 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 |
+
+Logs carry ids, statuses and error codes, never tokens, secrets, comment text or message text.
## Response Time
-- Normally a few seconds: Meta delivers the webhook, the Worker stores it and sends the reply right after answering.
-- Up to 5 minutes for a reply that waits for the sweep (more than the batch in one notification, or a webhook that stopped early), and up to 10 when a quarter-hour run also published posts.
+- Normally a few seconds: Meta delivers the webhook, the Worker stores it and sends the reply right after answering. A follow-up goes out the same way when the person replies.
+- Up to a minute for a reply that waits for the dispatch: more than the batch in one notification, a webhook that stopped early, or a reply whose limit or cooldown just ended.
- Longer only while a limit, a cooldown, a pause or Meta's own delivery delay holds it.
## Data Kept and Removed
| Data | Kept | Removed |
|---|---|---|
-| Matched comments: text, author, status, reply id | 90 days | Daily retention; also when the account or user is removed |
+| Matched comments: text, author, status, reply id, recipient id | 90 days | Daily retention, 1,000 a batch, up to 20,000 a day; also when the account or user is removed |
| Unmatched comments | 90 days, without text or author | Same |
-| Reply attempts | With their comment | With their comment |
+| 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 |
| Rules, account controls | Until deleted | With the account |
| Audit events | 1 year | Daily retention; with the user |
-Logs carry ids, statuses and error codes, never tokens, secrets or comment text.
-
## 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. The Workers Free plan allows 100,000 requests a day; webhook deliveries count against it, and the 288 five minute cron runs a day are a small share even counted as requests. 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. 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
@@ -185,9 +265,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/automationService.ts`, `services/retentionService.ts` |
+| Services | `services/automationWebhookService.ts`, `services/automationProcessor.ts`, `services/automationFollowupProcessor.ts`, `services/automationReconciler.ts`, `services/automationService.ts`, `services/retentionService.ts` |
+| Cron | `jobs/scheduled.ts` |
| Platform | `services/instagram/instagramMessaging.ts` |
-| Rules | `lib/automationMatching.ts`, `lib/automationDelivery.ts`, `lib/metaWebhookSignature.ts` |
-| Repositories | `repositories/automationRuleRepository.ts`, `automationCommentRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` |
-| Database | `supabase/migrations/20261016100000` to `20261016103500`, one entity per file |
+| 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 |
| App | `frontend/src/features/automations/` |
diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.md
index 586bdd1..b4891be 100644
--- a/docs/architecture/data-flows/SCHEDULING.md
+++ b/docs/architecture/data-flows/SCHEDULING.md
@@ -8,7 +8,7 @@ Both schedulers follow the same rules from `backend/lib/scheduledPublishing.ts`:
## System A: Cloudflare Worker Cron
-**Trigger:** the `*/5 * * * *` cron in `wrangler.toml`, on its runs at minutes 0, 15, 30 and 45 (`cronPlan()`; the other runs send comment replies)
+**Trigger:** the `*/5 * * * *` cron in `wrangler.toml`, on its runs at minutes 0, 15, 30 and 45 (`cronPlan()`; the other five minute runs reconcile the comment reply queue)
**Handler:** `backend/jobs/scheduled.ts` -> `runScheduledJob()` -> `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`
**Deadline:** 14 minutes (the cron context's signal, under the Worker's 15 minute limit for scheduled events)
**Supabase client:** service-role (created from Worker env)
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 377b2d9..916038c 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -2,11 +2,11 @@
## Overview
-Supabase (PostgreSQL 17) with nine application tables: the four original ones, the four comment automation tables (`automation_accounts`, `automation_rules`, `automation_comments`, `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 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.
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.
-The cron jobs (`scheduledPublisher.publishDue()`, `tokenRefresh.refreshExpiringInstagramTokens()`, the automation sweep and the retention purge) and the Instagram webhook intentionally use the repository methods without a `userId` filter to operate across all users.
+The cron jobs (`scheduledPublisher.publishDue()`, `tokenRefresh.refreshExpiringInstagramTokens()`, the reply dispatch, the reply queue reconciliation and the retention purge) and the Instagram webhook intentionally use the repository methods without a `userId` filter to operate across all users.
The browser roles (`anon`, `authenticated`) have no access to any table or function: row level security is on with no policies, and their grants are revoked. See `SECURITY.md`.
@@ -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 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 and attempts.
### Table: `automation_accounts`
@@ -308,6 +308,8 @@ One row per Instagram account whose automation was paused, subscribed or cooled
| `cooldown_until` | timestamptz | | No reply is sent before this time; set from Instagram rate limits and blocks, and only ever moved later |
| `cooldown_reason` | text | at most 200 characters | Shown on the page |
| `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 |
| `created_at`, `updated_at` | timestamptz | not null, default now() | |
### Table: `automation_rules`
@@ -317,14 +319,17 @@ One row per Instagram account whose automation was paused, subscribed or cooled
| `id` | text | primary key | `newRowId()` |
| `user_id`, `account_id` | uuid, text | not null, composite foreign key | Owner and Instagram account |
| `name` | text | 1 to 80 characters | |
-| `keywords` | text[] | 1 to 10 items | Matched as whole words or as the whole comment |
-| `match_mode` | text | `contains` or `exact`, default `contains` | |
+| `keywords` | text[] | 1 to 10 items; none when `match_mode` is `any` | Matched as whole words or as the whole comment |
+| `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 |
| `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 |
+| `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() | |
### Table: `automation_comments`
@@ -346,14 +351,39 @@ Every comment the webhook delivered for an account with an enabled rule. A match
| `next_attempt_at` | timestamptz | required while `queued` or `retry_wait` | When it is due |
| `claimed_at` | timestamptz | | When a run took it; the lease is 20 minutes |
| `message_id`, `accepted_at` | text, timestamptz | | Instagram's message id and when it accepted the reply |
+| `recipient_id` | text | | Who Instagram says received the reply, else the commenter; a followers-only answer is matched to the comment by it |
+| `gate_status` | text | null, `awaiting_reply`, `completed` or `closed` | Followers-only: waiting for the person's answer, link sent, or every reminder used |
+| `gate_prompts` | integer | not null, default 0, at least 0 | Reminders sent |
+| `review_checks`, `review_checked_at` | integer, timestamptz | `review_checks` not null, default 0 | Looks at the conversation for a reply whose answer was lost |
| `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`.
+### Table: `automation_followups`
+
+The message sent after a person answered a followers-only private reply: the reply and link once Instagram says they follow, a reminder otherwise. Each row is a job like a comment row. The person's message text is never stored.
+
+| 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 | The followers-only reply it answers |
+| `ig_user_id`, `recipient_id` | text | not null | The professional account and the person |
+| `trigger_message_id` | text | not null; `unique (ig_user_id, trigger_message_id)` | The person's message; refuses a message Meta delivered again |
+| `status` | text | the comment statuses except `ignored` | |
+| `status_reason`, `error_message` | text | `error_message` at most 500 characters | |
+| `kind` | text | null, `link` or `reminder` | Set when the follow check answers |
+| `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 |
+| `message_id`, `accepted_at` | text, timestamptz | | |
+| `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_attempts`
-One row per private reply request sent to Instagram. The hourly and daily limits count these rows.
+One row per message request sent to Instagram. The hourly and daily limits count the private reply rows.
| Column | Type | Constraints | Description |
|---|---|---|---|
@@ -363,6 +393,9 @@ One row per private reply request sent to Instagram. The hourly and daily limits
| `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 |
+| `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 |
| `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() | |
@@ -407,11 +440,17 @@ An index exists because a frequent query filters or orders on its columns. Each
| `accounts_instagram_user_idx` | `accounts ((data ->> 'igUserId')) where platform = 'instagram'` | `automation_rules_for_ig_user`: the accounts a webhook names | An expression index, since the id lives in `data` |
| `automation_rules_user_id_created_at_idx` | `automation_rules (user_id, created_at, id)` | `automationRules.listForUser` | |
| `automation_rules_enabled_account_idx` | `automation_rules (account_id) where enabled` | The webhook's rule lookup | Partial: only enabled rules are read |
-| `automation_comments_due_idx` | `automation_comments (next_attempt_at) where status in ('queued', 'retry_wait')` | `claim_automation_comments`: due jobs | Partial, so the growing history is left out |
+| `automation_comments_due_idx` | `automation_comments (next_attempt_at) where status in ('queued', 'retry_wait')` | Due jobs by time; the queue health | Partial, so the growing history is left out |
+| `automation_comments_due_account_idx` | `automation_comments (account_id, next_attempt_at) where status in ('queued', 'retry_wait')` | `claim_automation_comments`: the accounts with waiting jobs (a loose index scan, one probe per account) and each account's oldest due jobs | Partial; turn-taking reads a few rows per account however long one queue is |
| `automation_comments_claimed_idx` | `automation_comments (claimed_at) where status in ('processing', 'sending')` | The claim's lease recovery | Partial |
+| `automation_comments_awaiting_reply_idx` | `automation_comments (ig_user_id, recipient_id, accepted_at) where gate_status = 'awaiting_reply'` | `automation_followups_for_messages`: a sender's waiting followers-only reply | Partial: only replies that wait |
+| `automation_comments_needs_review_idx` | `automation_comments (review_checked_at nulls first, updated_at) where status = 'needs_review'` | `automation_review_candidates`, the queue health | Partial |
+| `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_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)` | The daily retention delete | |
+| `automation_comments_created_at_idx` | `automation_comments (created_at)` | `purge_automation_comments`: the oldest comments first, a batch at a time | |
| `automation_attempts_*_started_at_idx` | `(started_at)`, `(user_id, started_at)`, `(account_id, started_at)`, `(rule_id, started_at)`, `(account_id, recipient_id, started_at)` | `reserve_automation_send`: sends in the last hour per scope, and per recipient in the last day | One per limit the reservation counts |
| `automation_attempts_comment_idx` | `automation_attempts (automation_comment_id)` | Finishing and recovering one comment's attempt; the cascade | |
| `audit_events_user_id_created_at_idx`, `audit_events_created_at_idx` | `(user_id, created_at desc)`, `(created_at)` | Listing a user's events; the retention delete | |
@@ -442,9 +481,18 @@ Every function sets `search_path = ''` and names its tables with the schema. Fun
| `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`), then claims due jobs with `for update skip locked`, at most `p_per_account` per account, rechecking the status on each locked row. Returns each job with its rule's reply and the account's token |
-| `reserve_automation_send(p_id, p_attempt_id, p_global_limit, p_user_limit, p_account_limit, p_recipient_limit)` | plpgsql | Under `pg_advisory_xact_lock`, checks pause, cooldown, the recipient's daily replies and the hourly limits per rule, account, user and instance; on success moves the job to `sending` and inserts the attempt. Returns `outcome` and, for a full scope, `retry_at` |
-| `finish_automation_send(p_id, p_attempt_id, p_status, p_outcome, ...)` | plpgsql | Settles a `sending` job (or an interrupted one) and its attempt in one transaction, and sets the account's cooldown or hold when asked. Returns `false` and changes nothing when the job was already settled |
+| `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 |
+| `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 |
+| `claim_automation_followups(p_limit, p_lease_seconds, p_ids)` | plpgsql | The follow-up claim: lease recovery, paused and cooling accounts left out, turns between accounts. Returns each follow-up with the rule's texts, the comment's wait and the token |
+| `reserve_automation_followup(p_id, p_attempt_id, p_kind, p_message_digest)` | plpgsql | Checks pause and cooldown, moves the follow-up to `sending` and inserts a `followup` attempt |
+| `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 |
+| `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 |
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.
@@ -506,13 +554,19 @@ listEnabledForInstagramUser(igUserId): Promise<WebhookRule[]> // webhook
// Automation comments (automationCommentRepository.ts)
insertMany(comments): Promise<NewAutomationComment[]> // webhook only - upsert, ignoring duplicates; returns the new ones
-claim(options) / reserve(id, attemptId, limits) / finish(id, attemptId, plan) / release(id, plan) // processor only, every user
+claim(options) / reserve(id, attemptId, limits, digest?) / finish(id, attemptId, plan) / release(id, plan) / returnUnstarted(ids) // processor only, every user
listForUser(userId, filter) / findForUser(id, userId) / requeueForUser(id, userId) / releaseHeldForAccount(accountId, userId)
statsForUser(userId, filter): Promise<AutomationStats> // automation_stats
-deleteCreatedBefore(cutoff): Promise<number> // daily retention only
+expireDue(limit) / reviewCandidates(options) / recordReview(id, result) / health(leaseSeconds) // reconciliation only, every user
+purgeCreatedBefore(cutoff, limit): Promise<number> // daily retention only, one batch per call
+
+// Automation follow-ups (automationFollowupRepository.ts)
+insertForMessages(igUserId, messages): Promise<string[]> // webhook only - automation_followups_for_messages
+claim(options) / reserve(id, attemptId, kind, digest) / finish(id, attemptId, plan) / release(id, plan) / returnUnstarted(ids) // follow-up processor only, every user
+requeueLatestForUser(commentRowId, userId): Promise<string | null>
// Automation account controls (automationAccountRepository.ts)
-listForUser(userId) / findForUser(accountId, userId) / setPausedForUser(accountId, userId, paused) / markSubscribedForUser(accountId, userId)
+listForUser(userId) / findForUser(accountId, userId) / setPausedForUser(accountId, userId, paused) / markSubscribedForUser(accountId, userId, fields)
// Audit events (auditRepository.ts)
recordForUser(userId, event): Promise<void>
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index a5e53ee..364b3ea 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -8,7 +8,7 @@ The backend uses the **service-role key** for all database operations. This key
2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish` and `release`, and the retention `deleteCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply processor. Because ownership is a query filter, another user's record is simply not found (404).
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish`, `release` and `returnUnstarted` on comments and follow-ups, `insertForMessages`, `expireDue`, `reviewCandidates`, `recordReview`, `health` and the retention `purgeCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply and follow-up processors. Because ownership is a query filter, another user's record is simply not found (404).
The merge functions follow the same rule: the `...ForUser` repository methods pass the verified `userId` as `p_user_id`, and only `updateById` passes `null`, the cron form that reaches any user's row.
@@ -17,7 +17,7 @@ The merge functions follow the same rule: the `...ForUser` repository methods pa
A 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 four 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.
+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.
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 nine tables and for `POST /rest/v1/rpc/merge_account_data` and `POST /rest/v1/rpc/claim_automation_comments`. 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 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`.
### 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` returns the token to the Worker with each claimed job; the function is granted only to the service role
+ - `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
4. 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-live
When 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` 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`, `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/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 query
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 9cbfbdb..269e610 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -137,7 +137,7 @@ setAutomationAccountPaused: (accountId: string, paused: boolean) => request<Auto
subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}/subscribe`, { method: 'POST' }),
```
-The types are in `shared/types/automation.ts`. Activity and stats take their filters as `URLSearchParams` (`accountId`, `ruleId`, `status` as a comma-separated list, `from`, `to`, `before`, `limit`), built in `features/automations/useAutomationActivity.ts`. An accepted reply means Instagram took the request; the API reports nothing about delivery or reading.
+The types are in `shared/types/automation.ts`. Activity and stats take their filters as `URLSearchParams` (`accountId`, `ruleId`, `status` as a comma-separated list, `from`, `to`, `before`, `limit`), built in `features/automations/useAutomationActivity.ts`. An accepted reply means Instagram took the request; the API reports nothing about delivery or reading. Rules carry `matchMode` (`contains`, `exact` or `any`) and the followers-only fields `requireFollow`, `followPromptText` and `notFollowingText`; account states carry `limitedUntil` and `messagesSubscribed`; activity items carry `gateStatus` and `followup`.
## Tracked Content Methods
diff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.md
index b2fe2b0..6ead526 100644
--- a/docs/features/NEW_SCHEDULED_TASK.md
+++ b/docs/features/NEW_SCHEDULED_TASK.md
@@ -67,13 +67,13 @@ myPlatformTokenRefresh: createMyPlatformTokenRefreshService({ accounts, context
### Step 2: Choose a Run on an Existing Trigger
-The Workers Free plan allows five cron triggers per Cloudflare account, and the project's account uses all five, so a new job runs on one of the Worker's two triggers (`*/5 * * * *` and `0 0 * * *`) at the times `cronPlan()` gives it, not on a new trigger. A daily job belongs on the daily trigger:
+The Workers Free plan allows five cron triggers per Cloudflare account, and this Worker uses three (`* * * * *`, `*/5 * * * *` and `0 0 * * *`). Other Workers on the same account count toward the five, so count the triggers on your account before adding one. When no slot is free, a new job runs on one of the existing triggers at the times `cronPlan()` gives it. A daily job belongs on the daily trigger:
```ts
// backend/jobs/scheduled.ts
} else if (plan === 'daily') {
await services.tokenRefresh.refreshExpiringInstagramTokens();
- await services.retention.purge();
+ await services.retention.purge(Date.now(), { commentBatches: RETENTION_BATCHES });
await services.myPlatformTokenRefresh.refreshTokens();
}
```
@@ -86,7 +86,7 @@ On an account with a free slot, or on Workers Paid (250 triggers), a job may get
```toml
[triggers]
-crons = ["*/5 * * * *", "0 0 * * *", "30 3 * * *"]
+crons = ["* * * * *", "*/5 * * * *", "0 0 * * *", "30 3 * * *"]
```
Every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`, which hands the expression to `runScheduledJob()`. Add a constant for the new expression in `backend/jobs/scheduled.ts`, return a new plan for it from `cronPlan()`, and run the job in that branch. `event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character; `backend/tests/jobs/scheduled.test.ts` checks the list. `server.ts` already wraps the job in `ctx.waitUntil()`, and the cron context gives it a `cron-` request id and a 14 minute deadline. Add a test in `backend/tests/services/` with fake repositories or the fake Supabase client (see `tokenRefreshService.test.ts`), and run `npm run typecheck` before deploying.
diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.md
index 03f2613..2bcbb0b 100644
--- a/docs/philosophy/SECURITY.md
+++ b/docs/philosophy/SECURITY.md
@@ -106,7 +106,9 @@ The caps also protect the free email quota. There are 100 emails a day by defaul
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.
-The replies themselves are limited in the database per instance, member, account, rule and recipient, so a flood of comments, a bug or a misconfigured rule cannot turn into a stream of messages (`docs/architecture/data-flows/AUTOMATION.md`). A reply whose outcome is unknown is never sent again without a person's decision.
+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.
+
+The replies themselves are limited in the database per instance, member, account, rule and recipient, so a flood of comments, a bug or a misconfigured rule cannot turn into a stream of messages (`docs/architecture/data-flows/AUTOMATION.md`). A reply whose outcome is unknown is never sent again without a person's decision; the five minute reconciliation only reads the conversation on Instagram and marks a reply accepted when it finds the exact text, by its sha-256 digest.
## Rate Limiting
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index 039ec16..473a6df 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -47,6 +47,8 @@ cd backend
npx wrangler deploy
```
+A deploy also registers the cron triggers in `wrangler.toml`: `* * * * *`, `*/5 * * * *` and `0 0 * * *`. The every minute trigger was added with the reply queue changes (#98). The Workers Free plan allows five cron triggers per Cloudflare account, so the account needs a free slot for it; the deploy fails when there is none. Count the triggers of the account's other Workers before the first deploy that adds one.
+
### Frontend (Cloudflare Pages)
```bash
@@ -99,6 +101,8 @@ The link is stored in `supabase/.temp/`, which git ignores.
A change the old code cannot live with (a dropped column, a renamed function) needs two releases: first the code that works with both shapes, then the migration.
+A Worker that calls new database functions fails until they exist, so run `npm run db:push` before merging such a change. The reply queue changes (#98) are one: their migrations add the follow-up, review, expiry, purge and queue health functions and replace the claim, reserve and finish functions. The replaced functions keep their old arguments working, so applying the migrations while the old Worker runs is safe.
+
### Rolling Back a Database Change
The CLI has no down migrations. To undo one change on a remote database:
@@ -148,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. 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`. To stop every reply at once, set `AUTOMATION_PAUSED` to `true`.
## Setting GitHub Actions Secrets
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 9a9a073..7161998 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -41,9 +41,13 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `backend/routes/automationRoutes.ts` | `backend/tests/routes/automationRoutes.test.ts` |
| `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/automationReconciler.ts` | `backend/tests/services/automationReconciler.test.ts` |
+| `backend/services/instagram/instagramMessaging.ts` | `backend/tests/services/instagram/instagramMessaging.test.ts` |
| `backend/services/retentionService.ts` | `backend/tests/services/retentionService.test.ts` |
-| `backend/lib/automationMatching.ts`, `automationDelivery.ts`, `metaWebhookSignature.ts` | `backend/tests/lib/` with the same names |
+| `backend/lib/automationMatching.ts`, `automationDelivery.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` |
| `backend/validators/automationValidators.ts`, `instagramWebhookValidators.ts` | `backend/tests/validators/` with the same names |
| `backend/jobs/scheduled.ts` | `backend/tests/jobs/scheduled.test.ts` |
@@ -79,9 +83,9 @@ Backend route and cron service tests (`tests/routes/*Routes.test.ts`, `tests/ser
Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.test.ts` covers the shared rules: the 20 minute lease outlasts the 14 minute limit of both schedulers, what a run does for each container status, which Graph API codes count as temporary, when a failure retries or fails, and when the final message says publishing stopped. `tests/repositories/scheduledPostRepository.test.ts` runs the claim against the fake Supabase client: two schedulers claiming the same listed post (only the first gets it, and the claim counts an attempt), which claims are stale and that a takeover must match the expired claim it saw, that a post being published is not deleted, and that an edit only lands while the post is pending. The `scheduled publisher recovery` block in `tests/services/scheduledPublisher.test.ts` runs the whole publisher: a publish reply lost on the way back is checked on Instagram and marked published, an unreadable container status leaves the post claimed, an expired claim is taken over and found published or publishes its ready container, a claim inside its lease is left alone, a passing failure goes back to `pending` and the third fails the post, a run past its deadline claims nothing, and a post taken over after its last attempt is only checked. On the frontend, `tests/features/publishing/scheduleHelpers.test.ts` covers when the overdue alert counts a retried post (from its last claim) and a stuck claim (after the lease and 30 minutes).
-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 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. 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. 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.
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.
@@ -229,6 +233,9 @@ Open the app in a browser. For each changed area, test:
- [ ] Comment the same keyword again on a post the rule does not cover: Activity shows No match without the words
- [ ] Turn off Replies for the account, comment again: Activity shows Held; turn it back on and the reply goes out on the next run
- [ ] Set `AUTOMATION_PAUSED=true`: comments are recorded and nothing is sent; remove it and they go out
+- [ ] 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
- [ ] 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.mdx
index fd801da..9a9814c 100644
--- a/site/content/docs/self-host/comment-automation.mdx
+++ b/site/content/docs/self-host/comment-automation.mdx
@@ -2,13 +2,13 @@ export const meta = { title: 'Comment automation (optional)', description: 'Let
<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's keyword matches, 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.
+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.
</Callout>
<Callout type="warning" title="Meta approval comes first">
-Comments reach your backend only while the Meta app is **Live** and has **Advanced Access** for the comments webhook field. Advanced Access needs App Review and business verification. Until then, only Instagram accounts with a role on the app (Settings, Roles) get comment events, which is enough to test with your own account.
+Comments reach your backend only while the Meta app is **Live** and has **Advanced Access** for the comments webhook field, and the messages field if you use followers-only rules. Advanced Access needs App Review and business verification. Until then, only Instagram accounts with a role on the app (Settings, Roles) get events, which is enough to test with your own account.
</Callout>
@@ -20,7 +20,7 @@ Follow [Instagram app](/docs/self-host/instagram) first. Twiligent's sign-in alr
</Step>
<Step title="Apply the database migrations">
-From the repository root, run `npm run db:check` and then `npm run db:push`. They add the automation tables and functions. See [Supabase](/docs/self-host/supabase) if your CLI is not linked yet.
+From the repository root, run `npm run db:check` and then `npm run db:push`. They add the automation tables and functions. Apply them before you deploy a backend version that uses them. See [Supabase](/docs/self-host/supabase) if your CLI is not linked yet.
</Step>
<Step title="Choose a verify token">
@@ -45,16 +45,20 @@ Open the app, **Instagram**, **API setup with Instagram business login**, **Conf
Choose **Verify and save**. Meta calls the URL once; if it fails, check that the backend is deployed and the secret is set. Then subscribe to the **comments** field.
+Subscribe to the **messages** field too only if you will use followers-only rules. Meta then sends every direct message to your connected accounts to the backend, each one a Worker request. Twiligent reads only who sent it, never the text, and answers only people a followers-only reply is waiting for.
+
</Step>
<Step title="Turn on comment events for each account">
-In Twiligent, open **Automations**, create a rule and turn it on. The first rule turned on for an account asks Instagram to send that account's comments to your backend. If the account shows **Not receiving comments**, choose **Turn on comment events**. The account must be public: Instagram sends no comment events for private accounts.
+In Twiligent, open **Automations**, create a rule and turn it on. The first rule turned on for an account asks Instagram to send that account's comments to your backend, and a followers-only rule asks for its messages as well. If the account shows **Not receiving comments**, choose **Turn on comment events**; if it shows **Follow checks off**, select the messages field in the Meta dashboard and choose **Turn on message events**. The account must be public: Instagram sends no comment events for private accounts.
</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.
+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.
+
</Step>
</Steps>
@@ -68,14 +72,18 @@ 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_BATCH_SIZE` | 10 | Replies sent by one webhook request or one sweep; at most 15 on the Workers Free plan |
+| `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 waits for the backend's 5 minute schedule, which also retries temporary Instagram errors and waits out Instagram's rate limits. A reply whose outcome is unknown, for example after a timeout, is never sent again on its own; it shows as **Needs review** so you can check Instagram first.
+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.
+
+## 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.
## Costs
-Everything runs on the services you already use, and nothing new is billed on Cloudflare's or Supabase's free plans. Each comment is one Worker request, and a matched one adds a few database calls and one Instagram call. Comments and reply history are deleted after 90 days.
+Everything runs on the services you already use, and nothing new is billed on Cloudflare's or Supabase's free plans. Each comment is one Worker request, and a matched one adds a few database calls and one Instagram call. With the messages field on, each direct message to a connected account is one more request. Comments and reply history are deleted after 90 days.
## Troubleshooting
@@ -86,3 +94,5 @@ Everything runs on the services you already use, and nothing new is billed on Cl
| 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 **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/self-host/deploy-backend.mdx b/site/content/docs/self-host/deploy-backend.mdx
index fa0066f..bd78cf7 100644
--- a/site/content/docs/self-host/deploy-backend.mdx
+++ b/site/content/docs/self-host/deploy-backend.mdx
@@ -54,13 +54,16 @@ Open `https://your-backend-url/api/health`. It should return `{"status":"ok"}` w
## Scheduled jobs
-Deploying also registers two cron triggers from `wrangler.toml`. You do not need to set anything up.
+Deploying also registers three cron triggers from `wrangler.toml`. You do not need to set anything up.
| Schedule | What it does |
| --- | --- |
-| `*/5 * * * *` | At minutes 0, 15, 30 and 45, publishes scheduled Instagram posts that are due. On every run, sends comment replies that are waiting. |
+| `* * * * *` | Sends comment replies and follow-up messages that are waiting. |
+| `*/5 * * * *` | At minutes 0, 15, 30 and 45, publishes scheduled Instagram posts that are due. On the other runs, checks the reply queue: expires replies that waited too long, looks for replies whose answer from Instagram was lost, and reports the queue's health in the logs. |
| `0 0 * * *` | Renews Instagram access tokens before they expire, and deletes comment automation records older than 90 days. |
+The Workers Free plan allows five cron triggers per Cloudflare account. If other Workers on your account already use three or more, free one before you deploy; the deploy fails when the account has no slot left.
+
## Run it locally
Create `backend/.dev.vars` with the same names and values, one per line as `NAME=value`, with `BACKEND_URL=http://localhost:8787` and `FRONTEND_URL=http://localhost:5173`. Then run `npm run dev` in the top folder of the project to start the backend on port 8787 and the website on port 5173 together, or `npm run dev:backend` for the backend alone. The file is ignored by Git; never commit it.
diff --git a/site/content/docs/use/automations.mdx b/site/content/docs/use/automations.mdx
index d77579e..ac8b01b 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.' }
-Automations send a private reply on Instagram when someone comments a keyword, such as GUIDE, on one of your posts or reels. A typical rule sends a link: "Here is your guide" and the address of the guide.
+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.
<Callout type="note" title="Before you start">
@@ -12,13 +12,28 @@ You need an Instagram Business or Creator account connected with Instagram sign-
1. Open **Automations** in the sidebar and choose **New rule**.
2. Choose the Instagram account, give the rule a name, and type its keywords, separated by commas.
-3. Choose how keywords 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.
+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**.
-A comment gets one reply, from the first rule that matches it. Rules for chosen posts are checked before rules for every post. You can copy a rule (the copy starts off), change it, turn it off, or delete it.
+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.
+
+<Callout type="warning" title="Any comment means everyone">
+
+An any-comment rule messages everyone who comments, including people who did not ask for a message. A busy post reaches the hourly limits sooner, and replies to other rules of the account then wait too. Aim such a rule at the posts you choose.
+
+</Callout>
+
+## Send the link only to followers
+
+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:
+
+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.
+
+If Instagram cannot say whether the person follows you, nothing is sent, and the activity says why. The link is never sent on a guess. The reply must come within 7 days of the first message, and the answer goes out within Instagram's 24 hours after their reply.
## What Instagram allows
@@ -40,9 +55,15 @@ The counts at the top cover the chosen period. **Activity** lists every comment
| Failed | Instagram refused it; the details say why |
| Skipped, Expired | The rule was turned off, the person reached the daily number of replies, or the 7 days ran out |
| No match | No rule answers this comment; its words are not kept |
+| Asked to follow | A followers-only rule sent its first reply and waits for the person to reply |
+| 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 |
+
+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.
-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.
+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.
## Pause an account
-Turn off **Replies** next to an account to hold its replies, for example during a live event. Comments keep arriving and their replies go out when you turn it back on, if they are still within 7 days. If an account shows **Held**, Instagram refused its permission to send messages: connect it again on the **Accounts** page, then turn its replies back on.
+Turn off **Replies** next to an account to hold its replies, for example during a live event. Comments keep arriving and their replies go out when you turn it back on, if they are still within 7 days. If an account shows **Held**, Instagram refused its permission to send messages: connect it again on the **Accounts** page, then turn its replies back on. **At its hourly limit** means the account sent its hourly number of replies; the rest go out as the hour frees up.