Skip to content

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

feat(database): add public comment replies as their own queue

spacesdriveec0b10927a51
diff --git a/supabase/migrations/20261016130000_alter_automation_rules_reply_actions.sql b/supabase/migrations/20261016130000_alter_automation_rules_reply_actions.sql
new file mode 100644
index 0000000..3a42add
--- /dev/null
+++ b/supabase/migrations/20261016130000_alter_automation_rules_reply_actions.sql
@@ -0,0 +1,18 @@
+-- a rule answers a matching comment with a private reply, a public reply under the comment, or both; existing rules
+-- keep the private reply alone. A public reply rotates between up to five texts, so a busy post does not fill with
+-- the same words
+alter table public.automation_rules
+ drop constraint automation_rules_reply_text_check,
+ add column private_reply_enabled boolean not null default true,
+ add column public_reply_enabled boolean not null default false,
+ add column public_reply_texts text[] not null default '{}',
+ -- a rule without the private reply keeps an empty reply text
+ add constraint automation_rules_reply_text_check check (
+ char_length(reply_text) between 1 and 1000 or (not private_reply_enabled and reply_text = '')
+ ),
+ add constraint automation_rules_actions_check check (private_reply_enabled or public_reply_enabled),
+ add constraint automation_rules_public_reply_texts_check check (
+ cardinality(public_reply_texts) <= 5 and (not public_reply_enabled or cardinality(public_reply_texts) >= 1)
+ ),
+ -- the followers-only wait starts with the private reply
+ add constraint automation_rules_follow_private_check check (not require_follow or private_reply_enabled);
diff --git a/supabase/migrations/20261016130100_alter_automation_accounts_public_reply_fields.sql b/supabase/migrations/20261016130100_alter_automation_accounts_public_reply_fields.sql
new file mode 100644
index 0000000..c4f589f
--- /dev/null
+++ b/supabase/migrations/20261016130100_alter_automation_accounts_public_reply_fields.sql
@@ -0,0 +1,7 @@
+-- public replies have their own cooldown and hourly limit: Instagram limits commenting and messaging apart, so a
+-- block on one never holds the other
+alter table public.automation_accounts
+ add column public_cooldown_until timestamptz,
+ add column public_cooldown_reason text,
+ add column public_limited_until timestamptz,
+ add constraint automation_accounts_public_cooldown_reason_check check (public_cooldown_reason is null or char_length(public_cooldown_reason) <= 200);
diff --git a/supabase/migrations/20261016130200_create_automation_public_replies.sql b/supabase/migrations/20261016130200_create_automation_public_replies.sql
new file mode 100644
index 0000000..9c67ae2
--- /dev/null
+++ b/supabase/migrations/20261016130200_create_automation_public_replies.sql
@@ -0,0 +1,43 @@
+-- a public reply under a comment a rule matched, one per comment; it is tracked apart from the private reply, so
+-- either one can fail, wait or be retried without touching the other
+create table public.automation_public_replies (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ account_id text not null,
+ automation_comment_id text not null references public.automation_comments (id) on delete cascade,
+ rule_id text references public.automation_rules (id) on delete set null,
+ ig_user_id text not null,
+ -- the comment answered, with its post and author for the limit of one public reply per person and post a day
+ comment_id text not null,
+ media_id text,
+ from_id text,
+ -- picked from the rule's texts when the comment arrived, so every try and every check sees the same words
+ reply_text text not null,
+ status text not null,
+ status_reason text,
+ error_message text,
+ attempts integer not null default 0,
+ next_attempt_at timestamptz,
+ claimed_at timestamptz,
+ -- the id Instagram gave the reply
+ reply_id text,
+ accepted_at timestamptz,
+ -- checks of a reply whose outcome was unknown against the comment's replies on Instagram
+ review_checks integer not null default 0,
+ review_checked_at timestamptz,
+ expires_at timestamptz not null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_public_replies_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ constraint automation_public_replies_comment_key unique (automation_comment_id),
+ constraint automation_public_replies_status_check check (status in (
+ 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'
+ )),
+ constraint automation_public_replies_waiting_check check (status not in ('queued', 'retry_wait') or next_attempt_at is not null),
+ constraint automation_public_replies_attempts_check check (attempts >= 0),
+ constraint automation_public_replies_review_checks_check check (review_checks >= 0),
+ -- Instagram comments are at most 2,200 characters
+ constraint automation_public_replies_reply_text_check check (char_length(reply_text) between 1 and 2200),
+ constraint automation_public_replies_error_message_check check (error_message is null or char_length(error_message) <= 500)
+);
diff --git a/supabase/migrations/20261016130300_revoke_browser_access_automation_public_replies.sql b/supabase/migrations/20261016130300_revoke_browser_access_automation_public_replies.sql
new file mode 100644
index 0000000..f4bf131
--- /dev/null
+++ b/supabase/migrations/20261016130300_revoke_browser_access_automation_public_replies.sql
@@ -0,0 +1,3 @@
+-- only the Worker's service role reads automation_public_replies; the anon key ships in every browser
+alter table public.automation_public_replies enable row level security;
+revoke all on table public.automation_public_replies from anon, authenticated;
diff --git a/supabase/migrations/20261016130400_add_automation_public_replies_updated_at_trigger.sql b/supabase/migrations/20261016130400_add_automation_public_replies_updated_at_trigger.sql
new file mode 100644
index 0000000..276a225
--- /dev/null
+++ b/supabase/migrations/20261016130400_add_automation_public_replies_updated_at_trigger.sql
@@ -0,0 +1,3 @@
+-- set_updated_at() keeps updated_at, so no query has to set it
+create trigger automation_public_replies_set_updated_at before update on public.automation_public_replies
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016130500_index_automation_public_replies_due_by_account.sql b/supabase/migrations/20261016130500_index_automation_public_replies_due_by_account.sql
new file mode 100644
index 0000000..2cf204a
--- /dev/null
+++ b/supabase/migrations/20261016130500_index_automation_public_replies_due_by_account.sql
@@ -0,0 +1,3 @@
+-- claim_automation_public_replies and the expiry: each account's public replies waiting to go out, so accounts take
+-- turns however long one queue is; partial, so the history is left out
+create index automation_public_replies_due_account_idx on public.automation_public_replies (account_id, next_attempt_at) where status in ('queued', 'retry_wait');
diff --git a/supabase/migrations/20261016130600_index_automation_public_replies_claimed.sql b/supabase/migrations/20261016130600_index_automation_public_replies_claimed.sql
new file mode 100644
index 0000000..2314f2d
--- /dev/null
+++ b/supabase/migrations/20261016130600_index_automation_public_replies_claimed.sql
@@ -0,0 +1,2 @@
+-- claim_automation_public_replies: public replies whose run stopped holding them
+create index automation_public_replies_claimed_idx on public.automation_public_replies (claimed_at) where status in ('processing', 'sending');
diff --git a/supabase/migrations/20261016130700_index_automation_public_replies_needs_review.sql b/supabase/migrations/20261016130700_index_automation_public_replies_needs_review.sql
new file mode 100644
index 0000000..c7c5610
--- /dev/null
+++ b/supabase/migrations/20261016130700_index_automation_public_replies_needs_review.sql
@@ -0,0 +1,2 @@
+-- automation_public_review_candidates and the queue health: public replies whose outcome is unknown
+create index automation_public_replies_needs_review_idx on public.automation_public_replies (review_checked_at nulls first, updated_at) where status = 'needs_review';
diff --git a/supabase/migrations/20261016130800_index_automation_public_replies_recipient.sql b/supabase/migrations/20261016130800_index_automation_public_replies_recipient.sql
new file mode 100644
index 0000000..a55d1af
--- /dev/null
+++ b/supabase/migrations/20261016130800_index_automation_public_replies_recipient.sql
@@ -0,0 +1,3 @@
+-- reserve_automation_public_reply: the public replies one person already got, or may have got, on one post
+create index automation_public_replies_recipient_idx on public.automation_public_replies (account_id, from_id, media_id, created_at)
+ where status in ('sending', 'accepted', 'needs_review');
diff --git a/supabase/migrations/20261016130850_index_automation_public_replies_user_created.sql b/supabase/migrations/20261016130850_index_automation_public_replies_user_created.sql
new file mode 100644
index 0000000..a59e249
--- /dev/null
+++ b/supabase/migrations/20261016130850_index_automation_public_replies_user_created.sql
@@ -0,0 +1,2 @@
+-- automation_stats: one user's public replies in a period
+create index automation_public_replies_user_created_idx on public.automation_public_replies (user_id, created_at);
diff --git a/supabase/migrations/20261016130900_alter_automation_attempts_public_reply.sql b/supabase/migrations/20261016130900_alter_automation_attempts_public_reply.sql
new file mode 100644
index 0000000..405162f
--- /dev/null
+++ b/supabase/migrations/20261016130900_alter_automation_attempts_public_reply.sql
@@ -0,0 +1,7 @@
+-- public replies are counted with the other requests, under their own kind: Instagram limits them apart from
+-- private replies, so neither kind's hourly limit counts the other
+alter table public.automation_attempts
+ add column public_reply_id text references public.automation_public_replies (id) on delete cascade,
+ drop constraint automation_attempts_kind_check,
+ add constraint automation_attempts_kind_check check (kind in ('private_reply', 'followup', 'public_reply')),
+ add constraint automation_attempts_public_reply_check check ((kind = 'public_reply') = (public_reply_id is not null));
diff --git a/supabase/migrations/20261016131000_index_automation_attempts_public_reply.sql b/supabase/migrations/20261016131000_index_automation_attempts_public_reply.sql
new file mode 100644
index 0000000..73c117b
--- /dev/null
+++ b/supabase/migrations/20261016131000_index_automation_attempts_public_reply.sql
@@ -0,0 +1,2 @@
+-- deleting a public reply removes its attempts, and the review reads them, without scanning every attempt
+create index automation_attempts_public_reply_idx on public.automation_attempts (public_reply_id) where public_reply_id is not null;
diff --git a/supabase/migrations/20261016131100_replace_automation_rules_for_ig_user_function.sql b/supabase/migrations/20261016131100_replace_automation_rules_for_ig_user_function.sql
new file mode 100644
index 0000000..6a7a401
--- /dev/null
+++ b/supabase/migrations/20261016131100_replace_automation_rules_for_ig_user_function.sql
@@ -0,0 +1,35 @@
+-- the enabled rules of every connected account a webhook's Instagram account id belongs to, oldest account first,
+-- with what each one answers with: the private reply, the public reply and its texts. The return only gains
+-- columns, so the Worker deployed before this change reads the ones it knows
+drop function if exists public.automation_rules_for_ig_user(text);
+create or replace function public.automation_rules_for_ig_user(p_ig_user_id text)
+returns table (
+ id text,
+ user_id uuid,
+ account_id text,
+ keywords text[],
+ match_mode text,
+ case_sensitive boolean,
+ media_ids text[],
+ created_at timestamptz,
+ private_reply_enabled boolean,
+ public_reply_enabled boolean,
+ public_reply_texts text[]
+)
+language sql
+stable
+set search_path = ''
+as $$
+ select r.id, r.user_id, r.account_id, r.keywords, r.match_mode, r.case_sensitive, r.media_ids, r.created_at,
+ r.private_reply_enabled, r.public_reply_enabled, r.public_reply_texts
+ from public.accounts a
+ join public.automation_rules r on r.account_id = a.id and r.user_id = a.user_id
+ where a.platform = 'instagram'
+ and a.data ->> 'igUserId' = p_ig_user_id
+ and r.enabled
+ order by a.created_at, a.id, r.created_at, r.id;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_rules_for_ig_user(text) from public, anon, authenticated;
+grant execute on function public.automation_rules_for_ig_user(text) to service_role;
diff --git a/supabase/migrations/20261016131200_create_store_automation_comments_function.sql b/supabase/migrations/20261016131200_create_store_automation_comments_function.sql
new file mode 100644
index 0000000..6926394
--- /dev/null
+++ b/supabase/migrations/20261016131200_create_store_automation_comments_function.sql
@@ -0,0 +1,54 @@
+-- stores a webhook's comments and the public replies their rules ask for in one transaction, so a comment is never
+-- kept without its public reply. A notification Meta delivers again inserts nothing: comments are unique per account
+-- and public replies per comment. Answers the new comments' ids and statuses and the new public replies' ids
+create or replace function public.store_automation_comments(p_comments jsonb)
+returns jsonb
+language plpgsql
+set search_path = ''
+as $$
+declare
+ stored jsonb;
+ replies jsonb;
+begin
+ with inserted as (
+ insert into public.automation_comments (
+ id, user_id, account_id, rule_id, ig_user_id, comment_id, media_id, from_id, from_username, text, status,
+ status_reason, next_attempt_at, notified_at, expires_at
+ )
+ select x.id, x.user_id, x.account_id, x.rule_id, x.ig_user_id, x.comment_id, x.media_id, x.from_id, x.from_username,
+ x.text, x.status, x.status_reason, x.next_attempt_at, x.notified_at, x.expires_at
+ from jsonb_to_recordset(p_comments) as x(
+ id text, user_id uuid, account_id text, rule_id text, ig_user_id text, comment_id text, media_id text,
+ from_id text, from_username text, text text, status text, status_reason text, next_attempt_at timestamptz,
+ notified_at timestamptz, expires_at timestamptz
+ )
+ on conflict (ig_user_id, comment_id) do nothing
+ returning automation_comments.id, automation_comments.status
+ )
+ select coalesce(jsonb_agg(jsonb_build_object('id', inserted.id, 'status', inserted.status)), '[]'::jsonb) into stored from inserted;
+
+ -- joined to the comment as stored, new or kept from an earlier copy, and only while the same rule answers it
+ with inserted as (
+ insert into public.automation_public_replies (
+ id, user_id, account_id, automation_comment_id, rule_id, ig_user_id, comment_id, media_id, from_id, reply_text,
+ status, next_attempt_at, expires_at
+ )
+ select x.public_reply_id, c.user_id, c.account_id, c.id, c.rule_id, c.ig_user_id, c.comment_id, c.media_id, c.from_id,
+ x.public_reply_text, 'queued', now(), c.expires_at
+ from jsonb_to_recordset(p_comments) as x(
+ ig_user_id text, comment_id text, rule_id text, public_reply_id text, public_reply_text text
+ )
+ join public.automation_comments c on c.ig_user_id = x.ig_user_id and c.comment_id = x.comment_id and c.rule_id = x.rule_id
+ where x.public_reply_id is not null and x.public_reply_text is not null
+ on conflict (automation_comment_id) do nothing
+ returning automation_public_replies.id
+ )
+ select coalesce(jsonb_agg(inserted.id), '[]'::jsonb) into replies from inserted;
+
+ return jsonb_build_object('comments', stored, 'public_replies', replies);
+end;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.store_automation_comments(jsonb) from public, anon, authenticated;
+grant execute on function public.store_automation_comments(jsonb) to service_role;
diff --git a/supabase/migrations/20261016131300_create_claim_automation_public_replies_function.sql b/supabase/migrations/20261016131300_create_claim_automation_public_replies_function.sql
new file mode 100644
index 0000000..2d34e5c
--- /dev/null
+++ b/supabase/migrations/20261016131300_create_claim_automation_public_replies_function.sql
@@ -0,0 +1,133 @@
+-- hands one run the due public replies with accounts taking turns, as claim_automation_comments does for private
+-- replies. Accounts that are paused, or whose public replies are cooling down or at their hourly limit, are left out;
+-- p_ids limits it to the replies a webhook or a retry has just queued
+create or replace function public.claim_automation_public_replies(
+ p_limit integer,
+ p_per_account integer,
+ p_lease_seconds integer,
+ p_ids text[] default null
+)
+returns table (
+ id text,
+ user_id uuid,
+ account_id text,
+ rule_id text,
+ ig_user_id text,
+ comment_id text,
+ attempts integer,
+ expires_at timestamptz,
+ reply_text text,
+ rule_enabled boolean,
+ access_token text
+)
+language plpgsql
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ stale_before timestamptz := now() - make_interval(secs => p_lease_seconds);
+begin
+ -- a reply whose run stopped while sending may be on Instagram; the review reads the comment's replies to find out
+ with interrupted as (
+ update public.automation_public_replies p
+ set status = 'needs_review',
+ status_reason = 'interrupted',
+ claimed_at = null,
+ error_message = 'The run stopped while this public reply was being sent. Twiligent checks the comment''s replies on Instagram.'
+ where p.status = 'sending' and p.claimed_at < stale_before
+ returning p.id
+ )
+ update public.automation_attempts t
+ set outcome = 'ambiguous', finished_at = now()
+ where t.public_reply_id in (select interrupted.id from interrupted) and t.outcome = 'sending';
+
+ return query
+ with recursive waiting_accounts as (
+ -- one index probe per account instead of reading every waiting reply
+ (select p.account_id
+ from public.automation_public_replies p
+ where p.status in ('queued', 'retry_wait') and p_ids is null
+ order by p.account_id
+ limit 1)
+ union all
+ select (select p.account_id
+ from public.automation_public_replies p
+ where p.status in ('queued', 'retry_wait') and p.account_id > w.account_id
+ order by p.account_id
+ limit 1)
+ from waiting_accounts w
+ where w.account_id is not null
+ ),
+ due_accounts as (
+ select w.account_id from waiting_accounts w where w.account_id is not null
+ union
+ select p.account_id from public.automation_public_replies p where p.id = any (p_ids)
+ union
+ select p.account_id
+ from public.automation_public_replies p
+ where p.status = 'processing' and p.claimed_at < stale_before and (p_ids is null or p.id = any (p_ids))
+ ),
+ open_accounts as (
+ select d.account_id
+ from due_accounts d
+ left join public.automation_accounts s on s.account_id = d.account_id
+ where s.account_id is null
+ or (not s.paused
+ and (s.public_cooldown_until is null or s.public_cooldown_until <= now())
+ and (s.public_limited_until is null or s.public_limited_until <= now()))
+ ),
+ -- locked as they are read, so runs at the same moment take different replies
+ candidates as (
+ select x.id, x.account_id, x.next_attempt_at as due_at
+ from open_accounts o
+ cross join lateral (
+ select p.id, p.account_id, p.next_attempt_at
+ from public.automation_public_replies p
+ where p.account_id = o.account_id and p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()
+ and (p_ids is null or p.id = any (p_ids))
+ order by p.next_attempt_at
+ limit p_per_account
+ for update of p skip locked
+ ) x
+ union all
+ select x.id, x.account_id, x.claimed_at as due_at
+ from open_accounts o
+ cross join lateral (
+ select p.id, p.account_id, p.claimed_at
+ from public.automation_public_replies p
+ where p.account_id = o.account_id and p.status = 'processing' and p.claimed_at < stale_before
+ and (p_ids is null or p.id = any (p_ids))
+ order by p.claimed_at
+ limit p_per_account
+ for update of p skip locked
+ ) x
+ ),
+ picked as (
+ select ranked.id
+ from (
+ select candidates.id, candidates.due_at,
+ row_number() over (partition by candidates.account_id order by candidates.due_at, candidates.id) as place
+ from candidates
+ ) ranked
+ order by ranked.place, ranked.due_at
+ limit p_limit
+ ),
+ claimed as (
+ update public.automation_public_replies p
+ set status = 'processing', claimed_at = now()
+ from picked
+ where p.id = picked.id
+ returning p.id, p.user_id, p.account_id, p.rule_id, p.ig_user_id, p.comment_id, p.attempts, p.expires_at, p.reply_text
+ )
+ select claimed.id, claimed.user_id, claimed.account_id, claimed.rule_id, claimed.ig_user_id, claimed.comment_id,
+ claimed.attempts, claimed.expires_at, claimed.reply_text,
+ coalesce(r.enabled and r.public_reply_enabled, false), a.data ->> 'accessToken'
+ from claimed
+ left join public.automation_rules r on r.id = claimed.rule_id
+ left join public.accounts a on a.id = claimed.account_id and a.user_id = claimed.user_id;
+end;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.claim_automation_public_replies(integer, integer, integer, text[]) from public, anon, authenticated;
+grant execute on function public.claim_automation_public_replies(integer, integer, integer, text[]) to service_role;
diff --git a/supabase/migrations/20261016131400_create_reserve_automation_public_reply_function.sql b/supabase/migrations/20261016131400_create_reserve_automation_public_reply_function.sql
new file mode 100644
index 0000000..ac364f0
--- /dev/null
+++ b/supabase/migrations/20261016131400_create_reserve_automation_public_reply_function.sql
@@ -0,0 +1,73 @@
+-- decides whether a claimed public reply may go out now and, when it may, records the attempt before the request
+-- leaves; answers ok, gone, paused, cooldown, recipient_limit or account_limit. Only public reply attempts count, and
+-- a full account is marked until a reply frees up so runs stop claiming its public replies
+create or replace function public.reserve_automation_public_reply(
+ p_id text,
+ p_attempt_id text,
+ p_account_limit integer,
+ p_message_digest text default null
+)
+returns table (outcome text, retry_at timestamptz)
+language plpgsql
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ job public.automation_public_replies%rowtype;
+ controls public.automation_accounts%rowtype;
+ free_at timestamptz;
+begin
+ -- one public reservation at a time across every Worker; private replies take another lock, so neither waits on the other
+ perform pg_advisory_xact_lock(hashtext('reserve_automation_public_reply'));
+
+ select * into job from public.automation_public_replies p where p.id = p_id and p.status = 'processing' for update;
+ if not found then
+ return query select 'gone'::text, null::timestamptz;
+ return;
+ end if;
+
+ select * into controls from public.automation_accounts a where a.account_id = job.account_id;
+ if controls.paused then
+ return query select 'paused'::text, null::timestamptz;
+ return;
+ end if;
+ if controls.public_cooldown_until > now() then
+ return query select 'cooldown'::text, controls.public_cooldown_until;
+ return;
+ end if;
+
+ -- one public reply per person and post a day, however often they comment; it also ends a loop with another
+ -- account's automation answering every reply
+ if job.from_id is not null and exists (
+ select 1 from public.automation_public_replies p
+ where p.account_id = job.account_id and p.from_id = job.from_id and p.media_id is not distinct from job.media_id
+ and p.id <> job.id and p.status in ('sending', 'accepted', 'needs_review') and p.created_at > now() - interval '1 day'
+ ) then
+ return query select 'recipient_limit'::text, null::timestamptz;
+ return;
+ end if;
+
+ -- when the account is full, a reply frees up an hour after the oldest one in the window
+ select case when count(*) >= p_account_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t
+ where t.account_id = job.account_id and t.kind = 'public_reply' and t.started_at > now() - interval '1 hour';
+ if free_at is not null then
+ insert into public.automation_accounts (account_id, user_id, public_limited_until)
+ values (job.account_id, job.user_id, free_at)
+ on conflict (account_id) do update set public_limited_until = excluded.public_limited_until;
+ return query select 'account_limit'::text, free_at;
+ return;
+ end if;
+
+ update public.automation_public_replies p
+ set status = 'sending', claimed_at = now(), attempts = p.attempts + 1
+ where p.id = p_id;
+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, kind, public_reply_id, message_digest)
+ values (p_attempt_id, job.user_id, job.account_id, job.automation_comment_id, job.rule_id, job.from_id, 'public_reply', job.id, p_message_digest);
+ return query select 'ok'::text, null::timestamptz;
+end;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.reserve_automation_public_reply(text, text, integer, text) from public, anon, authenticated;
+grant execute on function public.reserve_automation_public_reply(text, text, integer, text) to service_role;
diff --git a/supabase/migrations/20261016131500_create_finish_automation_public_reply_function.sql b/supabase/migrations/20261016131500_create_finish_automation_public_reply_function.sql
new file mode 100644
index 0000000..7b414e3
--- /dev/null
+++ b/supabase/migrations/20261016131500_create_finish_automation_public_reply_function.sql
@@ -0,0 +1,69 @@
+-- records what Instagram answered to a public reply in one transaction: the reply, its attempt, a cooldown for the
+-- account's public replies, or a hold on the whole account when Instagram refused its token. An answer that comes
+-- back after its run was marked interrupted still lands, because the answer is better than a guess
+create or replace function public.finish_automation_public_reply(
+ p_id text,
+ p_attempt_id text,
+ p_status text,
+ p_outcome text,
+ p_reason text default null,
+ p_error_message text default null,
+ p_reply_id text default null,
+ p_error_code integer default null,
+ p_error_subcode integer default null,
+ p_http_status integer default null,
+ p_next_attempt_at timestamptz default null,
+ p_cooldown_until timestamptz default null,
+ p_cooldown_reason text default null,
+ p_pause_reason text default null
+)
+returns boolean
+language plpgsql
+set search_path = ''
+as $$
+declare
+ job public.automation_public_replies%rowtype;
+begin
+ update public.automation_public_replies p
+ set status = p_status,
+ status_reason = p_reason,
+ error_message = p_error_message,
+ reply_id = coalesce(p_reply_id, p.reply_id),
+ accepted_at = case when p_status = 'accepted' then now() else p.accepted_at end,
+ next_attempt_at = p_next_attempt_at,
+ claimed_at = null
+ where p.id = p_id and (p.status = 'sending' or (p.status = 'needs_review' and p.status_reason = 'interrupted'))
+ returning * into job;
+ -- a reply already settled keeps the attempt that settled it
+ if not found then
+ return false;
+ end if;
+
+ update public.automation_attempts t
+ set outcome = p_outcome,
+ error_code = p_error_code,
+ error_subcode = p_error_subcode,
+ http_status = p_http_status,
+ finished_at = now()
+ where t.id = p_attempt_id and t.public_reply_id = p_id;
+
+ if p_cooldown_until is not null then
+ insert into public.automation_accounts (account_id, user_id, public_cooldown_until, public_cooldown_reason)
+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)
+ on conflict (account_id) do update
+ set public_cooldown_until = greatest(coalesce(public.automation_accounts.public_cooldown_until, excluded.public_cooldown_until), excluded.public_cooldown_until),
+ public_cooldown_reason = excluded.public_cooldown_reason;
+ end if;
+
+ if p_pause_reason is not null then
+ insert into public.automation_accounts (account_id, user_id, paused, paused_reason)
+ values (job.account_id, job.user_id, true, p_pause_reason)
+ on conflict (account_id) do update set paused = true, paused_reason = excluded.paused_reason;
+ end if;
+ return true;
+end;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.finish_automation_public_reply(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text) from public, anon, authenticated;
+grant execute on function public.finish_automation_public_reply(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text) to service_role;
diff --git a/supabase/migrations/20261016131600_create_automation_public_review_candidates_function.sql b/supabase/migrations/20261016131600_create_automation_public_review_candidates_function.sql
new file mode 100644
index 0000000..acd61d9
--- /dev/null
+++ b/supabase/migrations/20261016131600_create_automation_public_review_candidates_function.sql
@@ -0,0 +1,46 @@
+-- public replies whose outcome was unknown, ready to be looked for among the comment's replies on Instagram: the
+-- last attempt left at least p_settle_seconds ago, fewer than p_max_checks checks so far and none in the last
+-- p_recheck_seconds; ambiguous_attempts tells the Worker whether the reply was already sent again once
+create or replace function public.automation_public_review_candidates(
+ p_limit integer,
+ p_settle_seconds integer,
+ p_max_checks integer,
+ p_recheck_seconds integer
+)
+returns table (
+ id text,
+ ig_user_id text,
+ comment_id text,
+ started_at timestamptz,
+ message_digest text,
+ access_token text,
+ review_checks integer,
+ ambiguous_attempts integer
+)
+language sql
+stable
+set search_path = ''
+as $$
+ select p.id, p.ig_user_id, p.comment_id, t.started_at, t.message_digest, a.data ->> 'accessToken', p.review_checks,
+ (select count(*)::integer from public.automation_attempts x where x.public_reply_id = p.id and x.outcome = 'ambiguous')
+ from public.automation_public_replies p
+ join lateral (
+ select t.started_at, t.message_digest
+ from public.automation_attempts t
+ where t.public_reply_id = p.id and t.outcome = 'ambiguous'
+ order by t.started_at desc
+ limit 1
+ ) t on true
+ join public.accounts a on a.id = p.account_id and a.user_id = p.user_id
+ where p.status = 'needs_review'
+ and p.status_reason in ('no_answer', 'interrupted')
+ and p.review_checks < p_max_checks
+ and (p.review_checked_at is null or p.review_checked_at < now() - make_interval(secs => p_recheck_seconds))
+ and t.started_at < now() - make_interval(secs => p_settle_seconds)
+ order by p.review_checked_at nulls first, p.updated_at
+ limit p_limit;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_public_review_candidates(integer, integer, integer, integer) from public, anon, authenticated;
+grant execute on function public.automation_public_review_candidates(integer, integer, integer, integer) to service_role;
diff --git a/supabase/migrations/20261016131700_create_record_automation_public_review_function.sql b/supabase/migrations/20261016131700_create_record_automation_public_review_function.sql
new file mode 100644
index 0000000..e85b1f5
--- /dev/null
+++ b/supabase/migrations/20261016131700_create_record_automation_public_review_function.sql
@@ -0,0 +1,66 @@
+-- records one check of a public reply whose outcome was unknown. Found among the comment's replies: the reply and
+-- its latest attempt become accepted. Not found, with p_resend: the Worker read every reply on two checks minutes
+-- apart and it was in neither, so the reply goes back in the queue once. Otherwise one more check is counted with a
+-- note for the person. Only a reply still waiting for review changes, so a person's retry in between is never undone
+create or replace function public.record_automation_public_review(
+ p_id text,
+ p_found boolean,
+ p_reply_id text default null,
+ p_sent_at timestamptz default null,
+ p_note text default null,
+ p_resend boolean default false
+)
+returns boolean
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if p_found then
+ update public.automation_public_replies p
+ set status = 'accepted',
+ status_reason = 'confirmed',
+ error_message = null,
+ reply_id = coalesce(p_reply_id, p.reply_id),
+ accepted_at = coalesce(p_sent_at, now()),
+ review_checks = p.review_checks + 1,
+ review_checked_at = now()
+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');
+ if not found then
+ return false;
+ end if;
+ update public.automation_attempts t
+ set outcome = 'accepted', finished_at = coalesce(t.finished_at, now())
+ where t.id = (
+ select x.id from public.automation_attempts x
+ where x.public_reply_id = p_id and x.outcome = 'ambiguous'
+ order by x.started_at desc
+ limit 1
+ );
+ return true;
+ end if;
+
+ if p_resend then
+ update public.automation_public_replies p
+ set status = 'queued',
+ status_reason = 'resend_after_check',
+ error_message = null,
+ next_attempt_at = now(),
+ claimed_at = null,
+ review_checks = 0,
+ review_checked_at = null
+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');
+ return found;
+ end if;
+
+ update public.automation_public_replies p
+ set review_checks = p.review_checks + 1,
+ review_checked_at = now(),
+ error_message = coalesce(left(p_note, 500), p.error_message)
+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');
+ return found;
+end;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.record_automation_public_review(text, boolean, text, timestamptz, text, boolean) from public, anon, authenticated;
+grant execute on function public.record_automation_public_review(text, boolean, text, timestamptz, text, boolean) to service_role;
diff --git a/supabase/migrations/20261016131800_replace_expire_automation_jobs_function.sql b/supabase/migrations/20261016131800_replace_expire_automation_jobs_function.sql
new file mode 100644
index 0000000..146f7a3
--- /dev/null
+++ b/supabase/migrations/20261016131800_replace_expire_automation_jobs_function.sql
@@ -0,0 +1,72 @@
+-- expires up to p_limit replies whose 7 days ran out, up to p_limit follow-ups whose 24 hours ran out and up to
+-- p_limit public replies still waiting 7 days after their comment, without a run claiming each one; rows a run holds
+-- are skipped and settled by that run. The answer gains public_replies, which the earlier Worker ignores
+create or replace function public.expire_automation_jobs(p_limit integer)
+returns jsonb
+language sql
+set search_path = ''
+as $$
+ with due_comments as (
+ select c.id
+ from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.expires_at <= now()
+ limit p_limit
+ for update skip locked
+ ),
+ expired_comments as (
+ update public.automation_comments c
+ set status = 'expired',
+ status_reason = 'expired',
+ error_message = 'The 7 days in which Instagram allows a private reply to this comment ran out.',
+ next_attempt_at = null,
+ claimed_at = null
+ from due_comments
+ where c.id = due_comments.id
+ returning c.id
+ ),
+ due_followups as (
+ select f.id
+ from public.automation_followups f
+ where f.status in ('queued', 'retry_wait') and f.window_expires_at <= now()
+ limit p_limit
+ for update skip locked
+ ),
+ expired_followups as (
+ update public.automation_followups f
+ set status = 'expired',
+ status_reason = 'expired',
+ error_message = 'The 24 hours in which Instagram allows a message after the person''s reply ran out.',
+ next_attempt_at = null,
+ claimed_at = null
+ from due_followups
+ where f.id = due_followups.id
+ returning f.id
+ ),
+ due_public_replies as (
+ select p.id
+ from public.automation_public_replies p
+ where p.status in ('queued', 'retry_wait') and p.expires_at <= now()
+ limit p_limit
+ for update skip locked
+ ),
+ expired_public_replies as (
+ update public.automation_public_replies p
+ set status = 'expired',
+ status_reason = 'expired',
+ error_message = 'This public reply waited 7 days without going out, so Twiligent stopped trying.',
+ next_attempt_at = null,
+ claimed_at = null
+ from due_public_replies
+ where p.id = due_public_replies.id
+ returning p.id
+ )
+ select jsonb_build_object(
+ 'comments', (select count(*) from expired_comments),
+ 'followups', (select count(*) from expired_followups),
+ 'public_replies', (select count(*) from expired_public_replies)
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.expire_automation_jobs(integer) from public, anon, authenticated;
+grant execute on function public.expire_automation_jobs(integer) to service_role;
diff --git a/supabase/migrations/20261016131900_replace_automation_queue_health_function.sql b/supabase/migrations/20261016131900_replace_automation_queue_health_function.sql
new file mode 100644
index 0000000..00411bb
--- /dev/null
+++ b/supabase/migrations/20261016131900_replace_automation_queue_health_function.sql
@@ -0,0 +1,61 @@
+-- the instance's reply queue in one call, each count read through its own partial index: jobs due now and the oldest
+-- of them, jobs held by runs that stopped, replies that need review, follow-ups due, public replies due, held or
+-- unknown, and accounts that are held. The answer only gains keys, which the earlier Worker ignores
+create or replace function public.automation_queue_health(p_lease_seconds integer)
+returns jsonb
+language sql
+stable
+set search_path = ''
+as $$
+ select jsonb_build_object(
+ 'due', (
+ select count(*) from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()
+ ),
+ 'oldest_due_at', (
+ select min(c.next_attempt_at) from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()
+ ),
+ 'waiting', (
+ select count(*) from public.automation_comments c where c.status in ('queued', 'retry_wait')
+ ),
+ 'stale', (
+ select count(*) from public.automation_comments c
+ where c.status in ('processing', 'sending') and c.claimed_at < now() - make_interval(secs => p_lease_seconds)
+ ),
+ 'needs_review', (
+ select count(*) from public.automation_comments c where c.status = 'needs_review'
+ ),
+ 'followups_due', (
+ select count(*) from public.automation_followups f
+ where f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now()
+ ),
+ 'public_due', (
+ select count(*) from public.automation_public_replies p
+ where p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()
+ ),
+ 'public_oldest_due_at', (
+ select min(p.next_attempt_at) from public.automation_public_replies p
+ where p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()
+ ),
+ 'public_stale', (
+ select count(*) from public.automation_public_replies p
+ where p.status in ('processing', 'sending') and p.claimed_at < now() - make_interval(secs => p_lease_seconds)
+ ),
+ 'public_needs_review', (
+ select count(*) from public.automation_public_replies p where p.status = 'needs_review'
+ ),
+ 'paused_accounts', (
+ select count(*) from public.automation_accounts a where a.paused
+ ),
+ 'limited_accounts', (
+ select count(*) from public.automation_accounts a
+ where a.cooldown_until > now() or a.limited_until > now()
+ or a.public_cooldown_until > now() or a.public_limited_until > now()
+ )
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_queue_health(integer) from public, anon, authenticated;
+grant execute on function public.automation_queue_health(integer) to service_role;
diff --git a/supabase/migrations/20261016132000_replace_automation_stats_function.sql b/supabase/migrations/20261016132000_replace_automation_stats_function.sql
new file mode 100644
index 0000000..8a92b96
--- /dev/null
+++ b/supabase/migrations/20261016132000_replace_automation_stats_function.sql
@@ -0,0 +1,58 @@
+-- one user's comment counts by status, public reply counts by status and request counts by outcome for a period,
+-- counted in the database instead of loading every row; p_account_id and p_rule_id narrow it when set. The answer
+-- only gains public_replies, which the earlier Worker ignores
+create or replace function public.automation_stats(
+ p_user_id uuid,
+ p_from timestamptz,
+ p_to timestamptz,
+ p_account_id text default null,
+ p_rule_id text default null
+)
+returns jsonb
+language sql
+stable
+set search_path = ''
+as $$
+ select jsonb_build_object(
+ 'comments', coalesce((
+ select jsonb_object_agg(counted.status, counted.total)
+ from (
+ select c.status, count(*) as total
+ from public.automation_comments c
+ where c.user_id = p_user_id
+ and c.created_at >= p_from and c.created_at < p_to
+ and (p_account_id is null or c.account_id = p_account_id)
+ and (p_rule_id is null or c.rule_id = p_rule_id)
+ group by c.status
+ ) counted
+ ), '{}'::jsonb),
+ 'public_replies', coalesce((
+ select jsonb_object_agg(counted.status, counted.total)
+ from (
+ select p.status, count(*) as total
+ from public.automation_public_replies p
+ where p.user_id = p_user_id
+ and p.created_at >= p_from and p.created_at < p_to
+ and (p_account_id is null or p.account_id = p_account_id)
+ and (p_rule_id is null or p.rule_id = p_rule_id)
+ group by p.status
+ ) counted
+ ), '{}'::jsonb),
+ 'attempts', coalesce((
+ select jsonb_object_agg(counted.outcome, counted.total)
+ from (
+ select t.outcome, count(*) as total
+ from public.automation_attempts t
+ where t.user_id = p_user_id
+ and t.started_at >= p_from and t.started_at < p_to
+ and (p_account_id is null or t.account_id = p_account_id)
+ and (p_rule_id is null or t.rule_id = p_rule_id)
+ group by t.outcome
+ ) counted
+ ), '{}'::jsonb)
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_stats(uuid, timestamptz, timestamptz, text, text) from public, anon, authenticated;
+grant execute on function public.automation_stats(uuid, timestamptz, timestamptz, text, text) to service_role;
diff --git a/supabase/rollbacks/20261016130000_alter_automation_rules_reply_actions.sql b/supabase/rollbacks/20261016130000_alter_automation_rules_reply_actions.sql
new file mode 100644
index 0000000..8b6c14e
--- /dev/null
+++ b/supabase/rollbacks/20261016130000_alter_automation_rules_reply_actions.sql
@@ -0,0 +1,11 @@
+-- a rule without the private reply has no place in the old shape, so such rules are removed first
+delete from public.automation_rules where not private_reply_enabled;
+alter table public.automation_rules
+ drop constraint if exists automation_rules_follow_private_check,
+ drop constraint if exists automation_rules_public_reply_texts_check,
+ drop constraint if exists automation_rules_actions_check,
+ drop constraint if exists automation_rules_reply_text_check,
+ drop column if exists public_reply_texts,
+ drop column if exists public_reply_enabled,
+ drop column if exists private_reply_enabled,
+ add constraint automation_rules_reply_text_check check (char_length(reply_text) between 1 and 1000);
diff --git a/supabase/rollbacks/20261016130100_alter_automation_accounts_public_reply_fields.sql b/supabase/rollbacks/20261016130100_alter_automation_accounts_public_reply_fields.sql
new file mode 100644
index 0000000..78c388d
--- /dev/null
+++ b/supabase/rollbacks/20261016130100_alter_automation_accounts_public_reply_fields.sql
@@ -0,0 +1,5 @@
+alter table public.automation_accounts
+ drop constraint if exists automation_accounts_public_cooldown_reason_check,
+ drop column if exists public_limited_until,
+ drop column if exists public_cooldown_reason,
+ drop column if exists public_cooldown_until;
diff --git a/supabase/rollbacks/20261016130200_create_automation_public_replies.sql b/supabase/rollbacks/20261016130200_create_automation_public_replies.sql
new file mode 100644
index 0000000..c5b00d3
--- /dev/null
+++ b/supabase/rollbacks/20261016130200_create_automation_public_replies.sql
@@ -0,0 +1,2 @@
+-- removes every public reply; roll back the automation_attempts change first
+drop table if exists public.automation_public_replies;
diff --git a/supabase/rollbacks/20261016130300_revoke_browser_access_automation_public_replies.sql b/supabase/rollbacks/20261016130300_revoke_browser_access_automation_public_replies.sql
new file mode 100644
index 0000000..897ad81
--- /dev/null
+++ b/supabase/rollbacks/20261016130300_revoke_browser_access_automation_public_replies.sql
@@ -0,0 +1 @@
+alter table if exists public.automation_public_replies disable row level security;
diff --git a/supabase/rollbacks/20261016130400_add_automation_public_replies_updated_at_trigger.sql b/supabase/rollbacks/20261016130400_add_automation_public_replies_updated_at_trigger.sql
new file mode 100644
index 0000000..68f9756
--- /dev/null
+++ b/supabase/rollbacks/20261016130400_add_automation_public_replies_updated_at_trigger.sql
@@ -0,0 +1 @@
+drop trigger if exists automation_public_replies_set_updated_at on public.automation_public_replies;
diff --git a/supabase/rollbacks/20261016130500_index_automation_public_replies_due_by_account.sql b/supabase/rollbacks/20261016130500_index_automation_public_replies_due_by_account.sql
new file mode 100644
index 0000000..8666346
--- /dev/null
+++ b/supabase/rollbacks/20261016130500_index_automation_public_replies_due_by_account.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_public_replies_due_account_idx;
diff --git a/supabase/rollbacks/20261016130600_index_automation_public_replies_claimed.sql b/supabase/rollbacks/20261016130600_index_automation_public_replies_claimed.sql
new file mode 100644
index 0000000..64f8a96
--- /dev/null
+++ b/supabase/rollbacks/20261016130600_index_automation_public_replies_claimed.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_public_replies_claimed_idx;
diff --git a/supabase/rollbacks/20261016130700_index_automation_public_replies_needs_review.sql b/supabase/rollbacks/20261016130700_index_automation_public_replies_needs_review.sql
new file mode 100644
index 0000000..d46df96
--- /dev/null
+++ b/supabase/rollbacks/20261016130700_index_automation_public_replies_needs_review.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_public_replies_needs_review_idx;
diff --git a/supabase/rollbacks/20261016130800_index_automation_public_replies_recipient.sql b/supabase/rollbacks/20261016130800_index_automation_public_replies_recipient.sql
new file mode 100644
index 0000000..79d26c1
--- /dev/null
+++ b/supabase/rollbacks/20261016130800_index_automation_public_replies_recipient.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_public_replies_recipient_idx;
diff --git a/supabase/rollbacks/20261016130850_index_automation_public_replies_user_created.sql b/supabase/rollbacks/20261016130850_index_automation_public_replies_user_created.sql
new file mode 100644
index 0000000..db7fdf3
--- /dev/null
+++ b/supabase/rollbacks/20261016130850_index_automation_public_replies_user_created.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_public_replies_user_created_idx;
diff --git a/supabase/rollbacks/20261016130900_alter_automation_attempts_public_reply.sql b/supabase/rollbacks/20261016130900_alter_automation_attempts_public_reply.sql
new file mode 100644
index 0000000..42f058a
--- /dev/null
+++ b/supabase/rollbacks/20261016130900_alter_automation_attempts_public_reply.sql
@@ -0,0 +1,7 @@
+-- public reply attempts have no place in the old table, so they are removed first
+delete from public.automation_attempts where kind = 'public_reply';
+alter table public.automation_attempts
+ drop constraint if exists automation_attempts_public_reply_check,
+ drop constraint if exists automation_attempts_kind_check,
+ drop column if exists public_reply_id,
+ add constraint automation_attempts_kind_check check (kind in ('private_reply', 'followup'));
diff --git a/supabase/rollbacks/20261016131000_index_automation_attempts_public_reply.sql b/supabase/rollbacks/20261016131000_index_automation_attempts_public_reply.sql
new file mode 100644
index 0000000..272fd0e
--- /dev/null
+++ b/supabase/rollbacks/20261016131000_index_automation_attempts_public_reply.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_attempts_public_reply_idx;
diff --git a/supabase/rollbacks/20261016131100_replace_automation_rules_for_ig_user_function.sql b/supabase/rollbacks/20261016131100_replace_automation_rules_for_ig_user_function.sql
new file mode 100644
index 0000000..c19fcf7
--- /dev/null
+++ b/supabase/rollbacks/20261016131100_replace_automation_rules_for_ig_user_function.sql
@@ -0,0 +1,30 @@
+-- puts back the function from 20261016103100, without the public reply columns
+drop function if exists public.automation_rules_for_ig_user(text);
+-- the enabled rules of every connected account a webhook's Instagram account id belongs to, oldest account first
+create or replace function public.automation_rules_for_ig_user(p_ig_user_id text)
+returns table (
+ id text,
+ user_id uuid,
+ account_id text,
+ keywords text[],
+ match_mode text,
+ case_sensitive boolean,
+ media_ids text[],
+ created_at timestamptz
+)
+language sql
+stable
+set search_path = ''
+as $$
+ select r.id, r.user_id, r.account_id, r.keywords, r.match_mode, r.case_sensitive, r.media_ids, r.created_at
+ from public.accounts a
+ join public.automation_rules r on r.account_id = a.id and r.user_id = a.user_id
+ where a.platform = 'instagram'
+ and a.data ->> 'igUserId' = p_ig_user_id
+ and r.enabled
+ order by a.created_at, a.id, r.created_at, r.id;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_rules_for_ig_user(text) from public, anon, authenticated;
+grant execute on function public.automation_rules_for_ig_user(text) to service_role;
diff --git a/supabase/rollbacks/20261016131200_create_store_automation_comments_function.sql b/supabase/rollbacks/20261016131200_create_store_automation_comments_function.sql
new file mode 100644
index 0000000..bdb03d8
--- /dev/null
+++ b/supabase/rollbacks/20261016131200_create_store_automation_comments_function.sql
@@ -0,0 +1 @@
+drop function if exists public.store_automation_comments(jsonb);
diff --git a/supabase/rollbacks/20261016131300_create_claim_automation_public_replies_function.sql b/supabase/rollbacks/20261016131300_create_claim_automation_public_replies_function.sql
new file mode 100644
index 0000000..0c750fd
--- /dev/null
+++ b/supabase/rollbacks/20261016131300_create_claim_automation_public_replies_function.sql
@@ -0,0 +1 @@
+drop function if exists public.claim_automation_public_replies(integer, integer, integer, text[]);
diff --git a/supabase/rollbacks/20261016131400_create_reserve_automation_public_reply_function.sql b/supabase/rollbacks/20261016131400_create_reserve_automation_public_reply_function.sql
new file mode 100644
index 0000000..3d50876
--- /dev/null
+++ b/supabase/rollbacks/20261016131400_create_reserve_automation_public_reply_function.sql
@@ -0,0 +1 @@
+drop function if exists public.reserve_automation_public_reply(text, text, integer, text);
diff --git a/supabase/rollbacks/20261016131500_create_finish_automation_public_reply_function.sql b/supabase/rollbacks/20261016131500_create_finish_automation_public_reply_function.sql
new file mode 100644
index 0000000..6753812
--- /dev/null
+++ b/supabase/rollbacks/20261016131500_create_finish_automation_public_reply_function.sql
@@ -0,0 +1 @@
+drop function if exists public.finish_automation_public_reply(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text);
diff --git a/supabase/rollbacks/20261016131600_create_automation_public_review_candidates_function.sql b/supabase/rollbacks/20261016131600_create_automation_public_review_candidates_function.sql
new file mode 100644
index 0000000..f0b96ef
--- /dev/null
+++ b/supabase/rollbacks/20261016131600_create_automation_public_review_candidates_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_public_review_candidates(integer, integer, integer, integer);
diff --git a/supabase/rollbacks/20261016131700_create_record_automation_public_review_function.sql b/supabase/rollbacks/20261016131700_create_record_automation_public_review_function.sql
new file mode 100644
index 0000000..2a8f67d
--- /dev/null
+++ b/supabase/rollbacks/20261016131700_create_record_automation_public_review_function.sql
@@ -0,0 +1 @@
+drop function if exists public.record_automation_public_review(text, boolean, text, timestamptz, text, boolean);
diff --git a/supabase/rollbacks/20261016131800_replace_expire_automation_jobs_function.sql b/supabase/rollbacks/20261016131800_replace_expire_automation_jobs_function.sql
new file mode 100644
index 0000000..7f877ac
--- /dev/null
+++ b/supabase/rollbacks/20261016131800_replace_expire_automation_jobs_function.sql
@@ -0,0 +1,53 @@
+-- puts back the function from 20261016122300, without the public reply columns
+-- expires up to p_limit replies whose 7 days ran out and up to p_limit follow-ups whose 24 hours ran out, without a
+-- run claiming each one; rows a run holds are skipped and settled by that run
+create or replace function public.expire_automation_jobs(p_limit integer)
+returns jsonb
+language sql
+set search_path = ''
+as $$
+ with due_comments as (
+ select c.id
+ from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.expires_at <= now()
+ limit p_limit
+ for update skip locked
+ ),
+ expired_comments as (
+ update public.automation_comments c
+ set status = 'expired',
+ status_reason = 'expired',
+ error_message = 'The 7 days in which Instagram allows a private reply to this comment ran out.',
+ next_attempt_at = null,
+ claimed_at = null
+ from due_comments
+ where c.id = due_comments.id
+ returning c.id
+ ),
+ due_followups as (
+ select f.id
+ from public.automation_followups f
+ where f.status in ('queued', 'retry_wait') and f.window_expires_at <= now()
+ limit p_limit
+ for update skip locked
+ ),
+ expired_followups as (
+ update public.automation_followups f
+ set status = 'expired',
+ status_reason = 'expired',
+ error_message = 'The 24 hours in which Instagram allows a message after the person''s reply ran out.',
+ next_attempt_at = null,
+ claimed_at = null
+ from due_followups
+ where f.id = due_followups.id
+ returning f.id
+ )
+ select jsonb_build_object(
+ 'comments', (select count(*) from expired_comments),
+ 'followups', (select count(*) from expired_followups)
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.expire_automation_jobs(integer) from public, anon, authenticated;
+grant execute on function public.expire_automation_jobs(integer) to service_role;
diff --git a/supabase/rollbacks/20261016131900_replace_automation_queue_health_function.sql b/supabase/rollbacks/20261016131900_replace_automation_queue_health_function.sql
new file mode 100644
index 0000000..4dbf28a
--- /dev/null
+++ b/supabase/rollbacks/20261016131900_replace_automation_queue_health_function.sql
@@ -0,0 +1,45 @@
+-- puts back the function from 20261016122500, without the public reply columns
+-- the instance's reply queue in one call, each count read through its own partial index: jobs due now and the oldest
+-- of them, jobs held by runs that stopped, replies that need review, follow-ups due, and accounts that are held
+create or replace function public.automation_queue_health(p_lease_seconds integer)
+returns jsonb
+language sql
+stable
+set search_path = ''
+as $$
+ select jsonb_build_object(
+ 'due', (
+ select count(*) from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()
+ ),
+ 'oldest_due_at', (
+ select min(c.next_attempt_at) from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()
+ ),
+ 'waiting', (
+ select count(*) from public.automation_comments c where c.status in ('queued', 'retry_wait')
+ ),
+ 'stale', (
+ select count(*) from public.automation_comments c
+ where c.status in ('processing', 'sending') and c.claimed_at < now() - make_interval(secs => p_lease_seconds)
+ ),
+ 'needs_review', (
+ select count(*) from public.automation_comments c where c.status = 'needs_review'
+ ),
+ 'followups_due', (
+ select count(*) from public.automation_followups f
+ where f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now()
+ ),
+ 'paused_accounts', (
+ select count(*) from public.automation_accounts a where a.paused
+ ),
+ 'limited_accounts', (
+ select count(*) from public.automation_accounts a
+ where a.cooldown_until > now() or a.limited_until > now()
+ )
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_queue_health(integer) from public, anon, authenticated;
+grant execute on function public.automation_queue_health(integer) to service_role;
diff --git a/supabase/rollbacks/20261016132000_replace_automation_stats_function.sql b/supabase/rollbacks/20261016132000_replace_automation_stats_function.sql
new file mode 100644
index 0000000..a331350
--- /dev/null
+++ b/supabase/rollbacks/20261016132000_replace_automation_stats_function.sql
@@ -0,0 +1,46 @@
+-- puts back the function from 20261016103500, without the public reply columns
+-- one user's comment counts by status and request counts by outcome for a period, counted in the database
+-- instead of loading every row; p_account_id and p_rule_id narrow it when set
+create or replace function public.automation_stats(
+ p_user_id uuid,
+ p_from timestamptz,
+ p_to timestamptz,
+ p_account_id text default null,
+ p_rule_id text default null
+)
+returns jsonb
+language sql
+stable
+set search_path = ''
+as $$
+ select jsonb_build_object(
+ 'comments', coalesce((
+ select jsonb_object_agg(counted.status, counted.total)
+ from (
+ select c.status, count(*) as total
+ from public.automation_comments c
+ where c.user_id = p_user_id
+ and c.created_at >= p_from and c.created_at < p_to
+ and (p_account_id is null or c.account_id = p_account_id)
+ and (p_rule_id is null or c.rule_id = p_rule_id)
+ group by c.status
+ ) counted
+ ), '{}'::jsonb),
+ 'attempts', coalesce((
+ select jsonb_object_agg(counted.outcome, counted.total)
+ from (
+ select t.outcome, count(*) as total
+ from public.automation_attempts t
+ where t.user_id = p_user_id
+ and t.started_at >= p_from and t.started_at < p_to
+ and (p_account_id is null or t.account_id = p_account_id)
+ and (p_rule_id is null or t.rule_id = p_rule_id)
+ group by t.outcome
+ ) counted
+ ), '{}'::jsonb)
+ );
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_stats(uuid, timestamptz, timestamptz, text, text) from public, anon, authenticated;
+grant execute on function public.automation_stats(uuid, timestamptz, timestamptz, text, text) to service_role;