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 queue fairness, follow-ups, review checks and batched upkeep

spacesdriveaccee23b642d
diff --git a/supabase/migrations/20261016120000_alter_automation_rules_match_options.sql b/supabase/migrations/20261016120000_alter_automation_rules_match_options.sql
new file mode 100644
index 0000000..2245da8
--- /dev/null
+++ b/supabase/migrations/20261016120000_alter_automation_rules_match_options.sql
@@ -0,0 +1,16 @@
+-- rules that answer any comment, and the followers-only option: the private reply asks the person to follow and
+-- reply, because Instagram reports whether someone follows the account only after they have messaged it
+alter table public.automation_rules
+ drop constraint automation_rules_match_mode_check,
+ drop constraint automation_rules_keywords_check,
+ add column require_follow boolean not null default false,
+ add column follow_prompt_text text,
+ add column not_following_text text,
+ add constraint automation_rules_match_mode_check check (match_mode in ('contains', 'exact', 'any')),
+ -- an any-comment rule has no keywords; a keyword rule has 1 to 10
+ add constraint automation_rules_keywords_check check (
+ case when match_mode = 'any' then cardinality(keywords) = 0 else cardinality(keywords) between 1 and 10 end
+ ),
+ add constraint automation_rules_follow_prompt_text_check check (follow_prompt_text is null or char_length(follow_prompt_text) between 1 and 1000),
+ add constraint automation_rules_not_following_text_check check (not_following_text is null or char_length(not_following_text) between 1 and 1000),
+ add constraint automation_rules_follow_texts_check check (not require_follow or (follow_prompt_text is not null and not_following_text is not null));
diff --git a/supabase/migrations/20261016120100_alter_automation_comments_followup_review.sql b/supabase/migrations/20261016120100_alter_automation_comments_followup_review.sql
new file mode 100644
index 0000000..a34b2f5
--- /dev/null
+++ b/supabase/migrations/20261016120100_alter_automation_comments_followup_review.sql
@@ -0,0 +1,12 @@
+alter table public.automation_comments
+ -- the person Instagram says received the private reply, so their answer can be matched to this comment
+ add column recipient_id text,
+ -- followers-only rules: waiting for the person to reply, link sent, or no more reminders
+ add column gate_status text,
+ add column gate_prompts integer not null default 0,
+ -- checks of a reply whose outcome was unknown against the conversation on Instagram
+ add column review_checks integer not null default 0,
+ add column review_checked_at timestamptz,
+ add constraint automation_comments_gate_status_check check (gate_status is null or gate_status in ('awaiting_reply', 'completed', 'closed')),
+ add constraint automation_comments_gate_prompts_check check (gate_prompts >= 0),
+ add constraint automation_comments_review_checks_check check (review_checks >= 0);
diff --git a/supabase/migrations/20261016120200_alter_automation_accounts_limit_fields.sql b/supabase/migrations/20261016120200_alter_automation_accounts_limit_fields.sql
new file mode 100644
index 0000000..10b5e9b
--- /dev/null
+++ b/supabase/migrations/20261016120200_alter_automation_accounts_limit_fields.sql
@@ -0,0 +1,5 @@
+alter table public.automation_accounts
+ -- set when the account reached its hourly reply limit, so runs leave its jobs alone until a send frees up
+ add column limited_until timestamptz,
+ -- the webhook fields Instagram confirmed for the account; follow checks need messages as well as comments
+ add column subscribed_fields text[];
diff --git a/supabase/migrations/20261016120300_create_automation_followups.sql b/supabase/migrations/20261016120300_create_automation_followups.sql
new file mode 100644
index 0000000..8f29042
--- /dev/null
+++ b/supabase/migrations/20261016120300_create_automation_followups.sql
@@ -0,0 +1,36 @@
+-- a message sent after a person answered a followers-only private reply: the reply and link once Instagram says they
+-- follow the account, a reminder to follow otherwise
+create table public.automation_followups (
+ 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,
+ ig_user_id text not null,
+ recipient_id text not null,
+ -- the person's message; Meta delivers a notification again until it is acknowledged
+ trigger_message_id text not null,
+ status text not null,
+ status_reason text,
+ error_message text,
+ -- what was sent: set once the follow check answers
+ kind text,
+ attempts integer not null default 0,
+ next_attempt_at timestamptz,
+ claimed_at timestamptz,
+ message_id text,
+ accepted_at timestamptz,
+ -- the person's message time plus 24 hours, Instagram's standard messaging window
+ window_expires_at timestamptz not null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_followups_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ constraint automation_followups_message_key unique (ig_user_id, trigger_message_id),
+ constraint automation_followups_status_check check (status in (
+ 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'
+ )),
+ constraint automation_followups_waiting_check check (status not in ('queued', 'retry_wait') or next_attempt_at is not null),
+ constraint automation_followups_kind_check check (kind is null or kind in ('link', 'reminder')),
+ constraint automation_followups_attempts_check check (attempts >= 0),
+ constraint automation_followups_error_message_check check (error_message is null or char_length(error_message) <= 500)
+);
diff --git a/supabase/migrations/20261016120400_revoke_browser_access_automation_followups.sql b/supabase/migrations/20261016120400_revoke_browser_access_automation_followups.sql
new file mode 100644
index 0000000..8e606c0
--- /dev/null
+++ b/supabase/migrations/20261016120400_revoke_browser_access_automation_followups.sql
@@ -0,0 +1,3 @@
+-- only the Worker's service role reads automation_followups; the anon key ships in every browser
+alter table public.automation_followups enable row level security;
+revoke all on table public.automation_followups from anon, authenticated;
diff --git a/supabase/migrations/20261016120500_add_automation_followups_updated_at_trigger.sql b/supabase/migrations/20261016120500_add_automation_followups_updated_at_trigger.sql
new file mode 100644
index 0000000..6ed3aab
--- /dev/null
+++ b/supabase/migrations/20261016120500_add_automation_followups_updated_at_trigger.sql
@@ -0,0 +1,3 @@
+-- set_updated_at() keeps updated_at, so no query has to set it
+create trigger automation_followups_set_updated_at before update on public.automation_followups
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016120600_index_automation_followups_due.sql b/supabase/migrations/20261016120600_index_automation_followups_due.sql
new file mode 100644
index 0000000..af4affa
--- /dev/null
+++ b/supabase/migrations/20261016120600_index_automation_followups_due.sql
@@ -0,0 +1,2 @@
+-- claim_automation_followups and the expiry: each account's follow-ups waiting to go out; partial, so the history is left out
+create index automation_followups_due_idx on public.automation_followups (account_id, next_attempt_at) where status in ('queued', 'retry_wait');
diff --git a/supabase/migrations/20261016120700_index_automation_followups_claimed.sql b/supabase/migrations/20261016120700_index_automation_followups_claimed.sql
new file mode 100644
index 0000000..19f9a6a
--- /dev/null
+++ b/supabase/migrations/20261016120700_index_automation_followups_claimed.sql
@@ -0,0 +1,2 @@
+-- claim_automation_followups: follow-ups whose run stopped holding them
+create index automation_followups_claimed_idx on public.automation_followups (claimed_at) where status in ('processing', 'sending');
diff --git a/supabase/migrations/20261016120800_index_automation_followups_open_comment.sql b/supabase/migrations/20261016120800_index_automation_followups_open_comment.sql
new file mode 100644
index 0000000..eebed1d
--- /dev/null
+++ b/supabase/migrations/20261016120800_index_automation_followups_open_comment.sql
@@ -0,0 +1,3 @@
+-- one open follow-up per comment, so several messages from one person get one answer
+create unique index automation_followups_open_comment_key on public.automation_followups (automation_comment_id)
+ where status in ('queued', 'processing', 'retry_wait', 'sending');
diff --git a/supabase/migrations/20261016120900_index_automation_followups_comment_id.sql b/supabase/migrations/20261016120900_index_automation_followups_comment_id.sql
new file mode 100644
index 0000000..7222737
--- /dev/null
+++ b/supabase/migrations/20261016120900_index_automation_followups_comment_id.sql
@@ -0,0 +1,2 @@
+-- deleting a comment removes its follow-ups, and the activity list shows the latest one
+create index automation_followups_comment_id_idx on public.automation_followups (automation_comment_id, created_at);
diff --git a/supabase/migrations/20261016121000_alter_automation_attempts_kind_digest.sql b/supabase/migrations/20261016121000_alter_automation_attempts_kind_digest.sql
new file mode 100644
index 0000000..cb0d876
--- /dev/null
+++ b/supabase/migrations/20261016121000_alter_automation_attempts_kind_digest.sql
@@ -0,0 +1,8 @@
+alter table public.automation_attempts
+ -- private replies count against Instagram's 750 an hour per account; follow-ups go through the Send API instead
+ add column kind text not null default 'private_reply',
+ -- sha-256 of the text sent, so a reply whose answer was lost can be recognised in the conversation later
+ add column message_digest text,
+ add column followup_id text references public.automation_followups (id) on delete cascade,
+ add constraint automation_attempts_kind_check check (kind in ('private_reply', 'followup')),
+ add constraint automation_attempts_followup_check check ((kind = 'followup') = (followup_id is not null));
diff --git a/supabase/migrations/20261016121100_index_automation_comments_due_by_account.sql b/supabase/migrations/20261016121100_index_automation_comments_due_by_account.sql
new file mode 100644
index 0000000..9c8b66d
--- /dev/null
+++ b/supabase/migrations/20261016121100_index_automation_comments_due_by_account.sql
@@ -0,0 +1,2 @@
+-- claim_automation_comments: each account's oldest due jobs, so accounts take turns however long one queue is
+create index automation_comments_due_account_idx on public.automation_comments (account_id, next_attempt_at) where status in ('queued', 'retry_wait');
diff --git a/supabase/migrations/20261016121200_index_automation_comments_awaiting_reply.sql b/supabase/migrations/20261016121200_index_automation_comments_awaiting_reply.sql
new file mode 100644
index 0000000..99190df
--- /dev/null
+++ b/supabase/migrations/20261016121200_index_automation_comments_awaiting_reply.sql
@@ -0,0 +1,2 @@
+-- automation_followups_for_messages: a sender's comments that wait for their reply; partial, so it stays small
+create index automation_comments_awaiting_reply_idx on public.automation_comments (ig_user_id, recipient_id, accepted_at) where gate_status = 'awaiting_reply';
diff --git a/supabase/migrations/20261016121300_index_automation_comments_needs_review.sql b/supabase/migrations/20261016121300_index_automation_comments_needs_review.sql
new file mode 100644
index 0000000..4f55c4e
--- /dev/null
+++ b/supabase/migrations/20261016121300_index_automation_comments_needs_review.sql
@@ -0,0 +1,2 @@
+-- automation_review_candidates and the queue health: replies a person may need to check, without scanning the history
+create index automation_comments_needs_review_idx on public.automation_comments (review_checked_at nulls first, updated_at) where status = 'needs_review';
diff --git a/supabase/migrations/20261016121400_replace_claim_automation_comments_function.sql b/supabase/migrations/20261016121400_replace_claim_automation_comments_function.sql
new file mode 100644
index 0000000..4dab75e
--- /dev/null
+++ b/supabase/migrations/20261016121400_replace_claim_automation_comments_function.sql
@@ -0,0 +1,142 @@
+-- hands one run the due reply jobs with accounts taking turns: each account's oldest job first, then each one's second,
+-- so a busy account cannot hold back the others and an account alone can fill the batch. 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 put
+-- back on every run; p_ids limits it to the comments a webhook has just stored. The return gains the rule's
+-- followers-only fields, and the Worker deployed before this change reads the columns it knows
+drop function if exists public.claim_automation_comments(integer, integer, integer, text[]);
+create or replace function public.claim_automation_comments(
+ 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,
+ from_id text,
+ attempts integer,
+ expires_at timestamptz,
+ rule_enabled boolean,
+ reply_text text,
+ link_url text,
+ access_token text,
+ require_follow boolean,
+ follow_prompt_text text
+)
+language plpgsql
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ stale_before timestamptz := now() - make_interval(secs => p_lease_seconds);
+begin
+ -- a send whose run stopped may have reached Instagram, so a person decides instead of a second send
+ with interrupted as (
+ update public.automation_comments c
+ set status = 'needs_review',
+ status_reason = 'interrupted',
+ claimed_at = null,
+ error_message = 'The run stopped while this reply was being sent. Check the conversation on Instagram before you retry.'
+ where c.status = 'sending' and c.claimed_at < stale_before
+ returning c.id
+ )
+ update public.automation_attempts t
+ set outcome = 'ambiguous', finished_at = now()
+ where t.automation_comment_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 job, however long one account's queue is
+ (select c.account_id
+ from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and p_ids is null
+ order by c.account_id
+ limit 1)
+ union all
+ select (select c.account_id
+ from public.automation_comments c
+ where c.status in ('queued', 'retry_wait') and c.account_id > w.account_id
+ order by c.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 c.account_id from public.automation_comments c where c.id = any (p_ids)
+ union
+ select c.account_id
+ from public.automation_comments c
+ where c.status = 'processing' and c.claimed_at < stale_before and (p_ids is null or c.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.cooldown_until is null or s.cooldown_until <= now())
+ and (s.limited_until is null or s.limited_until <= now()))
+ ),
+ -- each account's oldest due jobs, locked as they are read: a job another run holds is skipped, so runs at the
+ -- same moment take the next jobs instead of the same ones
+ candidates as (
+ select x.id, x.account_id, x.next_attempt_at as due_at
+ from open_accounts o
+ cross join lateral (
+ select c.id, c.account_id, c.next_attempt_at
+ from public.automation_comments c
+ where c.account_id = o.account_id and c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()
+ and (p_ids is null or c.id = any (p_ids))
+ order by c.next_attempt_at
+ limit p_per_account
+ for update of c 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 c.id, c.account_id, c.claimed_at
+ from public.automation_comments c
+ where c.account_id = o.account_id and c.status = 'processing' and c.claimed_at < stale_before
+ and (p_ids is null or c.id = any (p_ids))
+ order by c.claimed_at
+ limit p_per_account
+ for update of c 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_comments c
+ set status = 'processing', claimed_at = now()
+ from picked
+ where c.id = picked.id
+ returning c.id, c.user_id, c.account_id, c.rule_id, c.ig_user_id, c.comment_id, c.from_id, c.attempts, c.expires_at
+ )
+ select claimed.id, claimed.user_id, claimed.account_id, claimed.rule_id, claimed.ig_user_id, claimed.comment_id,
+ claimed.from_id, claimed.attempts, claimed.expires_at,
+ coalesce(r.enabled, false), r.reply_text, r.link_url, a.data ->> 'accessToken',
+ coalesce(r.require_follow, false), r.follow_prompt_text
+ 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_comments(integer, integer, integer, text[]) from public, anon, authenticated;
+grant execute on function public.claim_automation_comments(integer, integer, integer, text[]) to service_role;
diff --git a/supabase/migrations/20261016121500_replace_reserve_automation_send_function.sql b/supabase/migrations/20261016121500_replace_reserve_automation_send_function.sql
new file mode 100644
index 0000000..6f0e089
--- /dev/null
+++ b/supabase/migrations/20261016121500_replace_reserve_automation_send_function.sql
@@ -0,0 +1,104 @@
+-- decides whether a claimed job may send now and, when it may, records the attempt before the request leaves;
+-- answers ok, gone, paused, cooldown, recipient_limit, or the full scope (rule_limit, account_limit, user_limit,
+-- global_limit). Only private replies count, since follow-ups use a different Instagram limit; a full account is
+-- marked until a send frees up so runs stop claiming its jobs; p_message_digest lets a lost answer be checked later.
+-- The new parameter has a default, so the Worker deployed before this change still calls it
+drop function if exists public.reserve_automation_send(text, text, integer, integer, integer, integer);
+create or replace function public.reserve_automation_send(
+ p_id text,
+ p_attempt_id text,
+ p_global_limit integer,
+ p_user_limit integer,
+ p_account_limit integer,
+ p_recipient_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_comments%rowtype;
+ controls public.automation_accounts%rowtype;
+ rule_limit integer;
+ hour_ago timestamptz := now() - interval '1 hour';
+ free_at timestamptz;
+begin
+ -- one reservation at a time across every Worker, so two jobs cannot both take the last free send
+ perform pg_advisory_xact_lock(hashtext('reserve_automation_send'));
+
+ select * into job from public.automation_comments c where c.id = p_id and c.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.cooldown_until > now() then
+ return query select 'cooldown'::text, controls.cooldown_until;
+ return;
+ end if;
+
+ -- a person who comments again and again gets a few replies a day, never a stream of them; retries of this
+ -- comment are one reply, so only other comments count
+ if job.from_id is not null and (
+ select count(distinct t.automation_comment_id) from public.automation_attempts t
+ where t.account_id = job.account_id and t.recipient_id = job.from_id and t.kind = 'private_reply'
+ and t.started_at > now() - interval '1 day' and t.automation_comment_id <> job.id
+ ) >= p_recipient_limit then
+ return query select 'recipient_limit'::text, null::timestamptz;
+ return;
+ end if;
+
+ -- when a scope is full, a send frees up an hour after the oldest one in the window
+ select r.hourly_limit into rule_limit from public.automation_rules r where r.id = job.rule_id;
+ if rule_limit is not null then
+ select case when count(*) >= rule_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.rule_id = job.rule_id and t.kind = 'private_reply' and t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'rule_limit'::text, free_at;
+ return;
+ end if;
+ end if;
+
+ 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 = 'private_reply' and t.started_at > hour_ago;
+ if free_at is not null then
+ insert into public.automation_accounts (account_id, user_id, limited_until)
+ values (job.account_id, job.user_id, free_at)
+ on conflict (account_id) do update set limited_until = excluded.limited_until;
+ return query select 'account_limit'::text, free_at;
+ return;
+ end if;
+
+ select case when count(*) >= p_user_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.user_id = job.user_id and t.kind = 'private_reply' and t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'user_limit'::text, free_at;
+ return;
+ end if;
+
+ select case when count(*) >= p_global_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.kind = 'private_reply' and t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'global_limit'::text, free_at;
+ return;
+ end if;
+
+ update public.automation_comments c
+ set status = 'sending', claimed_at = now(), attempts = c.attempts + 1
+ where c.id = p_id;
+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, message_digest)
+ values (p_attempt_id, job.user_id, job.account_id, job.id, job.rule_id, job.from_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_send(text, text, integer, integer, integer, integer, text) from public, anon, authenticated;
+grant execute on function public.reserve_automation_send(text, text, integer, integer, integer, integer, text) to service_role;
diff --git a/supabase/migrations/20261016121600_replace_finish_automation_send_function.sql b/supabase/migrations/20261016121600_replace_finish_automation_send_function.sql
new file mode 100644
index 0000000..ed75ea3
--- /dev/null
+++ b/supabase/migrations/20261016121600_replace_finish_automation_send_function.sql
@@ -0,0 +1,75 @@
+-- records what Instagram answered in one transaction: the attempt, the comment's new state, and a cooldown or a hold
+-- for the account; a reply that comes back after its run was marked interrupted still lands, because the answer is
+-- better than a guess. p_recipient_id keeps who received an accepted reply and p_gate_status starts a followers-only
+-- wait; both default to null, so the Worker deployed before this change still calls it
+drop function if exists public.finish_automation_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text);
+create or replace function public.finish_automation_send(
+ 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_message_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,
+ p_recipient_id text default null,
+ p_gate_status text default null
+)
+returns boolean
+language plpgsql
+set search_path = ''
+as $$
+declare
+ job public.automation_comments%rowtype;
+begin
+ update public.automation_comments c
+ set status = p_status,
+ status_reason = p_reason,
+ error_message = p_error_message,
+ message_id = coalesce(p_message_id, c.message_id),
+ accepted_at = case when p_status = 'accepted' then now() else c.accepted_at end,
+ recipient_id = coalesce(p_recipient_id, c.recipient_id),
+ gate_status = coalesce(p_gate_status, c.gate_status),
+ next_attempt_at = p_next_attempt_at,
+ claimed_at = null
+ where c.id = p_id and (c.status = 'sending' or (c.status = 'needs_review' and c.status_reason = 'interrupted'))
+ returning * into job;
+ -- a comment 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.automation_comment_id = p_id;
+
+ if p_cooldown_until is not null then
+ insert into public.automation_accounts (account_id, user_id, cooldown_until, cooldown_reason)
+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)
+ on conflict (account_id) do update
+ set cooldown_until = greatest(coalesce(public.automation_accounts.cooldown_until, excluded.cooldown_until), excluded.cooldown_until),
+ cooldown_reason = excluded.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_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, text) from public, anon, authenticated;
+grant execute on function public.finish_automation_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, text) to service_role;
diff --git a/supabase/migrations/20261016121700_create_automation_followups_for_messages_function.sql b/supabase/migrations/20261016121700_create_automation_followups_for_messages_function.sql
new file mode 100644
index 0000000..f423af7
--- /dev/null
+++ b/supabase/migrations/20261016121700_create_automation_followups_for_messages_function.sql
@@ -0,0 +1,39 @@
+-- turns messages from people waiting on a followers-only reply into follow-up jobs, at most one open job per comment;
+-- p_messages is [{ "id", "sender_id", "message_id", "sent_at" }] with row ids made by the Worker, and a message Meta
+-- delivers again, or a second message while one is open, inserts nothing
+create or replace function public.automation_followups_for_messages(p_ig_user_id text, p_messages jsonb)
+returns table (id text)
+language sql
+set search_path = ''
+as $$
+ with incoming as (
+ select m.id, m.sender_id, m.message_id, m.sent_at
+ from jsonb_to_recordset(p_messages) as m (id text, sender_id text, message_id text, sent_at timestamptz)
+ where m.id is not null and m.sender_id is not null and m.message_id is not null and m.sent_at is not null
+ ),
+ waiting as (
+ -- the sender's newest reply that waits for them; a minute of slack covers the two clocks, and a reply older
+ -- than 7 days no longer waits
+ select distinct on (i.message_id)
+ i.id as followup_id, i.message_id, i.sent_at, c.id as comment_id, c.user_id, c.account_id, c.recipient_id
+ from incoming i
+ join public.automation_comments c
+ on c.ig_user_id = p_ig_user_id and c.recipient_id = i.sender_id and c.gate_status = 'awaiting_reply'
+ and c.accepted_at <= i.sent_at + interval '1 minute' and c.accepted_at > i.sent_at - interval '7 days'
+ order by i.message_id, c.accepted_at desc
+ )
+ insert into public.automation_followups as f (
+ id, user_id, account_id, automation_comment_id, ig_user_id, recipient_id, trigger_message_id, status,
+ next_attempt_at, window_expires_at
+ )
+ select w.followup_id, w.user_id, w.account_id, w.comment_id, p_ig_user_id, w.recipient_id, w.message_id, 'queued',
+ now() - interval '30 seconds', w.sent_at + interval '1 day'
+ from waiting w
+ order by w.sent_at
+ on conflict do nothing
+ returning f.id;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.automation_followups_for_messages(text, jsonb) from public, anon, authenticated;
+grant execute on function public.automation_followups_for_messages(text, jsonb) to service_role;
diff --git a/supabase/migrations/20261016121800_create_claim_automation_followups_function.sql b/supabase/migrations/20261016121800_create_claim_automation_followups_function.sql
new file mode 100644
index 0000000..bee68d5
--- /dev/null
+++ b/supabase/migrations/20261016121800_create_claim_automation_followups_function.sql
@@ -0,0 +1,105 @@
+-- hands one run the due follow-ups with accounts taking turns, leaving out paused and cooling accounts, with what a
+-- follow-up needs: the person, the rule's texts, the comment's followers-only state and the account's token
+create or replace function public.claim_automation_followups(
+ p_limit integer,
+ p_lease_seconds integer,
+ p_ids text[] default null
+)
+returns table (
+ id text,
+ user_id uuid,
+ account_id text,
+ automation_comment_id text,
+ ig_user_id text,
+ recipient_id text,
+ attempts integer,
+ window_expires_at timestamptz,
+ gate_status text,
+ gate_prompts integer,
+ rule_enabled boolean,
+ require_follow boolean,
+ reply_text text,
+ link_url text,
+ not_following_text text,
+ 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
+ -- as with private replies, a send whose run stopped may have arrived, so a person decides
+ with interrupted as (
+ update public.automation_followups f
+ set status = 'needs_review',
+ status_reason = 'interrupted',
+ claimed_at = null,
+ error_message = 'The run stopped while this message was being sent. Check the conversation on Instagram before you retry.'
+ where f.status = 'sending' and f.claimed_at < stale_before
+ returning f.id
+ )
+ update public.automation_attempts t
+ set outcome = 'ambiguous', finished_at = now()
+ where t.followup_id in (select interrupted.id from interrupted) and t.outcome = 'sending';
+
+ return query
+ with due_accounts as (
+ select distinct f.account_id
+ from public.automation_followups f
+ where ((f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())
+ or (f.status = 'processing' and f.claimed_at < stale_before))
+ and (p_ids is null or f.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.cooldown_until is null or s.cooldown_until <= now()))
+ ),
+ candidates as (
+ select x.id, x.due_at, row_number() over (partition by o.account_id order by x.due_at, x.id) as place
+ from open_accounts o
+ cross join lateral (
+ select f.id, coalesce(f.next_attempt_at, f.claimed_at) as due_at
+ from public.automation_followups f
+ where f.account_id = o.account_id
+ and ((f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())
+ or (f.status = 'processing' and f.claimed_at < stale_before))
+ and (p_ids is null or f.id = any (p_ids))
+ order by due_at
+ limit p_limit
+ ) x
+ ),
+ picked as (
+ select f.id
+ from public.automation_followups f
+ join candidates on candidates.id = f.id
+ where (f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())
+ or (f.status = 'processing' and f.claimed_at < stale_before)
+ order by candidates.place, candidates.due_at
+ limit p_limit
+ for update of f skip locked
+ ),
+ claimed as (
+ update public.automation_followups f
+ set status = 'processing', claimed_at = now()
+ from picked
+ where f.id = picked.id
+ returning f.id, f.user_id, f.account_id, f.automation_comment_id, f.ig_user_id, f.recipient_id, f.attempts, f.window_expires_at
+ )
+ select claimed.id, claimed.user_id, claimed.account_id, claimed.automation_comment_id, claimed.ig_user_id,
+ claimed.recipient_id, claimed.attempts, claimed.window_expires_at, c.gate_status, c.gate_prompts,
+ coalesce(r.enabled, false), coalesce(r.require_follow, false), r.reply_text, r.link_url, r.not_following_text,
+ a.data ->> 'accessToken'
+ from claimed
+ join public.automation_comments c on c.id = claimed.automation_comment_id
+ left join public.automation_rules r on r.id = c.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_followups(integer, integer, text[]) from public, anon, authenticated;
+grant execute on function public.claim_automation_followups(integer, integer, text[]) to service_role;
diff --git a/supabase/migrations/20261016121900_create_reserve_automation_followup_function.sql b/supabase/migrations/20261016121900_create_reserve_automation_followup_function.sql
new file mode 100644
index 0000000..2181a62
--- /dev/null
+++ b/supabase/migrations/20261016121900_create_reserve_automation_followup_function.sql
@@ -0,0 +1,48 @@
+-- decides whether a claimed follow-up may send now and records the attempt before the request leaves; answers ok,
+-- gone, paused or cooldown. Follow-ups use Instagram's Send API, not the private reply allowance, so the hourly
+-- reply limits do not apply to them
+create or replace function public.reserve_automation_followup(
+ p_id text,
+ p_attempt_id text,
+ p_kind text,
+ 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_followups%rowtype;
+ controls public.automation_accounts%rowtype;
+ rule text;
+begin
+ select * into job from public.automation_followups f where f.id = p_id and f.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.cooldown_until > now() then
+ return query select 'cooldown'::text, controls.cooldown_until;
+ return;
+ end if;
+
+ select c.rule_id into rule from public.automation_comments c where c.id = job.automation_comment_id;
+ update public.automation_followups f
+ set status = 'sending', claimed_at = now(), attempts = f.attempts + 1, kind = p_kind
+ where f.id = p_id;
+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, kind, followup_id, message_digest)
+ values (p_attempt_id, job.user_id, job.account_id, job.automation_comment_id, rule, job.recipient_id, 'followup', 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_followup(text, text, text, text) from public, anon, authenticated;
+grant execute on function public.reserve_automation_followup(text, text, text, text) to service_role;
diff --git a/supabase/migrations/20261016122000_create_finish_automation_followup_function.sql b/supabase/migrations/20261016122000_create_finish_automation_followup_function.sql
new file mode 100644
index 0000000..332399f
--- /dev/null
+++ b/supabase/migrations/20261016122000_create_finish_automation_followup_function.sql
@@ -0,0 +1,74 @@
+-- records what Instagram answered to a follow-up in one transaction: the follow-up, its attempt, a cooldown or a hold
+-- for the account, and the comment's followers-only state (link sent, or one more reminder counted)
+create or replace function public.finish_automation_followup(
+ 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_message_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,
+ p_gate_status text default null,
+ p_count_reminder boolean default false
+)
+returns boolean
+language plpgsql
+set search_path = ''
+as $$
+declare
+ job public.automation_followups%rowtype;
+begin
+ update public.automation_followups f
+ set status = p_status,
+ status_reason = p_reason,
+ error_message = p_error_message,
+ message_id = coalesce(p_message_id, f.message_id),
+ accepted_at = case when p_status = 'accepted' then now() else f.accepted_at end,
+ next_attempt_at = p_next_attempt_at,
+ claimed_at = null
+ where f.id = p_id and (f.status = 'sending' or (f.status = 'needs_review' and f.status_reason = 'interrupted'))
+ returning * into job;
+ 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.followup_id = p_id;
+
+ update public.automation_comments c
+ set gate_status = coalesce(p_gate_status, c.gate_status),
+ gate_prompts = c.gate_prompts + case when p_count_reminder then 1 else 0 end
+ where c.id = job.automation_comment_id;
+
+ if p_cooldown_until is not null then
+ insert into public.automation_accounts (account_id, user_id, cooldown_until, cooldown_reason)
+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)
+ on conflict (account_id) do update
+ set cooldown_until = greatest(coalesce(public.automation_accounts.cooldown_until, excluded.cooldown_until), excluded.cooldown_until),
+ cooldown_reason = excluded.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_followup(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, boolean) from public, anon, authenticated;
+grant execute on function public.finish_automation_followup(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, boolean) to service_role;
diff --git a/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql b/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql
new file mode 100644
index 0000000..00292f1
--- /dev/null
+++ b/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql
@@ -0,0 +1,44 @@
+-- replies whose outcome was unknown, ready to be looked for in the conversation 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;
+-- the least checked first
+create or replace function public.automation_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,
+ from_id text,
+ started_at timestamptz,
+ message_digest text,
+ access_token text
+)
+language sql
+stable
+set search_path = ''
+as $$
+ select c.id, c.ig_user_id, c.from_id, t.started_at, t.message_digest, a.data ->> 'accessToken'
+ from public.automation_comments c
+ join lateral (
+ select t.started_at, t.message_digest
+ from public.automation_attempts t
+ where t.automation_comment_id = c.id and t.kind = 'private_reply' and t.outcome = 'ambiguous'
+ order by t.started_at desc
+ limit 1
+ ) t on true
+ join public.accounts a on a.id = c.account_id and a.user_id = c.user_id
+ where c.status = 'needs_review'
+ and c.status_reason in ('no_answer', 'interrupted')
+ and c.from_id is not null
+ and c.review_checks < p_max_checks
+ and (c.review_checked_at is null or c.review_checked_at < now() - make_interval(secs => p_recheck_seconds))
+ and t.started_at < now() - make_interval(secs => p_settle_seconds)
+ order by c.review_checked_at nulls first, c.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_review_candidates(integer, integer, integer, integer) from public, anon, authenticated;
+grant execute on function public.automation_review_candidates(integer, integer, integer, integer) to service_role;
diff --git a/supabase/migrations/20261016122200_create_record_automation_review_function.sql b/supabase/migrations/20261016122200_create_record_automation_review_function.sql
new file mode 100644
index 0000000..bc1925c
--- /dev/null
+++ b/supabase/migrations/20261016122200_create_record_automation_review_function.sql
@@ -0,0 +1,54 @@
+-- records one check of a reply whose outcome was unknown. Found in the conversation: the comment and its attempt
+-- become accepted, and a followers-only rule starts waiting for the person's reply. Not found: one more check is
+-- counted with a note for the person; nothing is ever sent from here. Only a comment still waiting for review changes
+create or replace function public.record_automation_review(
+ p_id text,
+ p_found boolean,
+ p_message_id text default null,
+ p_sent_at timestamptz default null,
+ p_note text default null
+)
+returns boolean
+language plpgsql
+set search_path = ''
+as $$
+declare
+ job public.automation_comments%rowtype;
+begin
+ if p_found then
+ update public.automation_comments c
+ set status = 'accepted',
+ status_reason = 'confirmed',
+ error_message = null,
+ message_id = coalesce(p_message_id, c.message_id),
+ accepted_at = coalesce(p_sent_at, now()),
+ recipient_id = coalesce(c.recipient_id, c.from_id),
+ gate_status = case
+ when (select r.require_follow from public.automation_rules r where r.id = c.rule_id) then 'awaiting_reply'
+ else c.gate_status
+ end,
+ review_checks = c.review_checks + 1,
+ review_checked_at = now()
+ where c.id = p_id and c.status = 'needs_review' and c.status_reason in ('no_answer', 'interrupted')
+ returning * into job;
+ 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.automation_comment_id = p_id and t.kind = 'private_reply' and t.outcome = 'ambiguous';
+ return true;
+ end if;
+
+ update public.automation_comments c
+ set review_checks = c.review_checks + 1,
+ review_checked_at = now(),
+ error_message = coalesce(left(p_note, 500), c.error_message)
+ where c.id = p_id and c.status = 'needs_review' and c.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_review(text, boolean, text, timestamptz, text) from public, anon, authenticated;
+grant execute on function public.record_automation_review(text, boolean, text, timestamptz, text) to service_role;
diff --git a/supabase/migrations/20261016122300_create_expire_automation_jobs_function.sql b/supabase/migrations/20261016122300_create_expire_automation_jobs_function.sql
new file mode 100644
index 0000000..8b07d6b
--- /dev/null
+++ b/supabase/migrations/20261016122300_create_expire_automation_jobs_function.sql
@@ -0,0 +1,52 @@
+-- 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/migrations/20261016122400_create_purge_automation_comments_function.sql b/supabase/migrations/20261016122400_create_purge_automation_comments_function.sql
new file mode 100644
index 0000000..5f99ff5
--- /dev/null
+++ b/supabase/migrations/20261016122400_create_purge_automation_comments_function.sql
@@ -0,0 +1,27 @@
+-- deletes at most p_limit comments created before p_before, oldest first, and returns how many; their attempts and
+-- follow-ups go with them. A bounded batch keeps each statement short however much built up
+create or replace function public.purge_automation_comments(p_before timestamptz, p_limit integer)
+returns integer
+language sql
+set search_path = ''
+as $$
+ with doomed as (
+ select c.id
+ from public.automation_comments c
+ where c.created_at < p_before
+ order by c.created_at
+ limit p_limit
+ for update skip locked
+ ),
+ deleted as (
+ delete from public.automation_comments c
+ using doomed
+ where c.id = doomed.id
+ returning c.id
+ )
+ select count(*)::integer from deleted;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.purge_automation_comments(timestamptz, integer) from public, anon, authenticated;
+grant execute on function public.purge_automation_comments(timestamptz, integer) to service_role;
diff --git a/supabase/migrations/20261016122500_create_automation_queue_health_function.sql b/supabase/migrations/20261016122500_create_automation_queue_health_function.sql
new file mode 100644
index 0000000..8ea3ec3
--- /dev/null
+++ b/supabase/migrations/20261016122500_create_automation_queue_health_function.sql
@@ -0,0 +1,44 @@
+-- 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/20261016120000_alter_automation_rules_match_options.sql b/supabase/rollbacks/20261016120000_alter_automation_rules_match_options.sql
new file mode 100644
index 0000000..aa74b7a
--- /dev/null
+++ b/supabase/rollbacks/20261016120000_alter_automation_rules_match_options.sql
@@ -0,0 +1,13 @@
+-- the old checks allow no any-comment rule, so those rules are removed first
+delete from public.automation_rules where match_mode = 'any';
+alter table public.automation_rules
+ drop constraint if exists automation_rules_follow_texts_check,
+ drop constraint if exists automation_rules_not_following_text_check,
+ drop constraint if exists automation_rules_follow_prompt_text_check,
+ drop constraint if exists automation_rules_keywords_check,
+ drop constraint if exists automation_rules_match_mode_check,
+ drop column if exists not_following_text,
+ drop column if exists follow_prompt_text,
+ drop column if exists require_follow,
+ add constraint automation_rules_keywords_check check (cardinality(keywords) between 1 and 10),
+ add constraint automation_rules_match_mode_check check (match_mode in ('contains', 'exact'));
diff --git a/supabase/rollbacks/20261016120100_alter_automation_comments_followup_review.sql b/supabase/rollbacks/20261016120100_alter_automation_comments_followup_review.sql
new file mode 100644
index 0000000..f1d2b66
--- /dev/null
+++ b/supabase/rollbacks/20261016120100_alter_automation_comments_followup_review.sql
@@ -0,0 +1,9 @@
+alter table public.automation_comments
+ drop constraint if exists automation_comments_review_checks_check,
+ drop constraint if exists automation_comments_gate_prompts_check,
+ drop constraint if exists automation_comments_gate_status_check,
+ drop column if exists review_checked_at,
+ drop column if exists review_checks,
+ drop column if exists gate_prompts,
+ drop column if exists gate_status,
+ drop column if exists recipient_id;
diff --git a/supabase/rollbacks/20261016120200_alter_automation_accounts_limit_fields.sql b/supabase/rollbacks/20261016120200_alter_automation_accounts_limit_fields.sql
new file mode 100644
index 0000000..3040044
--- /dev/null
+++ b/supabase/rollbacks/20261016120200_alter_automation_accounts_limit_fields.sql
@@ -0,0 +1,3 @@
+alter table public.automation_accounts
+ drop column if exists subscribed_fields,
+ drop column if exists limited_until;
diff --git a/supabase/rollbacks/20261016120300_create_automation_followups.sql b/supabase/rollbacks/20261016120300_create_automation_followups.sql
new file mode 100644
index 0000000..fe06fa8
--- /dev/null
+++ b/supabase/rollbacks/20261016120300_create_automation_followups.sql
@@ -0,0 +1,2 @@
+-- removes every follow-up; roll back the automation_attempts change first
+drop table if exists public.automation_followups;
diff --git a/supabase/rollbacks/20261016120400_revoke_browser_access_automation_followups.sql b/supabase/rollbacks/20261016120400_revoke_browser_access_automation_followups.sql
new file mode 100644
index 0000000..b7bba42
--- /dev/null
+++ b/supabase/rollbacks/20261016120400_revoke_browser_access_automation_followups.sql
@@ -0,0 +1,2 @@
+-- the table had no browser grants before, because new tables in public start without them
+alter table public.automation_followups disable row level security;
diff --git a/supabase/rollbacks/20261016120500_add_automation_followups_updated_at_trigger.sql b/supabase/rollbacks/20261016120500_add_automation_followups_updated_at_trigger.sql
new file mode 100644
index 0000000..c17d0f6
--- /dev/null
+++ b/supabase/rollbacks/20261016120500_add_automation_followups_updated_at_trigger.sql
@@ -0,0 +1 @@
+drop trigger if exists automation_followups_set_updated_at on public.automation_followups;
diff --git a/supabase/rollbacks/20261016120600_index_automation_followups_due.sql b/supabase/rollbacks/20261016120600_index_automation_followups_due.sql
new file mode 100644
index 0000000..41c1cc2
--- /dev/null
+++ b/supabase/rollbacks/20261016120600_index_automation_followups_due.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_followups_due_idx;
diff --git a/supabase/rollbacks/20261016120700_index_automation_followups_claimed.sql b/supabase/rollbacks/20261016120700_index_automation_followups_claimed.sql
new file mode 100644
index 0000000..400a7a9
--- /dev/null
+++ b/supabase/rollbacks/20261016120700_index_automation_followups_claimed.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_followups_claimed_idx;
diff --git a/supabase/rollbacks/20261016120800_index_automation_followups_open_comment.sql b/supabase/rollbacks/20261016120800_index_automation_followups_open_comment.sql
new file mode 100644
index 0000000..83fbd56
--- /dev/null
+++ b/supabase/rollbacks/20261016120800_index_automation_followups_open_comment.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_followups_open_comment_key;
diff --git a/supabase/rollbacks/20261016120900_index_automation_followups_comment_id.sql b/supabase/rollbacks/20261016120900_index_automation_followups_comment_id.sql
new file mode 100644
index 0000000..665b9c7
--- /dev/null
+++ b/supabase/rollbacks/20261016120900_index_automation_followups_comment_id.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_followups_comment_id_idx;
diff --git a/supabase/rollbacks/20261016121000_alter_automation_attempts_kind_digest.sql b/supabase/rollbacks/20261016121000_alter_automation_attempts_kind_digest.sql
new file mode 100644
index 0000000..c2316a5
--- /dev/null
+++ b/supabase/rollbacks/20261016121000_alter_automation_attempts_kind_digest.sql
@@ -0,0 +1,8 @@
+-- follow-up attempts have no place in the old table, so they are removed first
+delete from public.automation_attempts where kind = 'followup';
+alter table public.automation_attempts
+ drop constraint if exists automation_attempts_followup_check,
+ drop constraint if exists automation_attempts_kind_check,
+ drop column if exists followup_id,
+ drop column if exists message_digest,
+ drop column if exists kind;
diff --git a/supabase/rollbacks/20261016121100_index_automation_comments_due_by_account.sql b/supabase/rollbacks/20261016121100_index_automation_comments_due_by_account.sql
new file mode 100644
index 0000000..13d7851
--- /dev/null
+++ b/supabase/rollbacks/20261016121100_index_automation_comments_due_by_account.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_comments_due_account_idx;
diff --git a/supabase/rollbacks/20261016121200_index_automation_comments_awaiting_reply.sql b/supabase/rollbacks/20261016121200_index_automation_comments_awaiting_reply.sql
new file mode 100644
index 0000000..f9e79cc
--- /dev/null
+++ b/supabase/rollbacks/20261016121200_index_automation_comments_awaiting_reply.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_comments_awaiting_reply_idx;
diff --git a/supabase/rollbacks/20261016121300_index_automation_comments_needs_review.sql b/supabase/rollbacks/20261016121300_index_automation_comments_needs_review.sql
new file mode 100644
index 0000000..df9259f
--- /dev/null
+++ b/supabase/rollbacks/20261016121300_index_automation_comments_needs_review.sql
@@ -0,0 +1 @@
+drop index if exists public.automation_comments_needs_review_idx;
diff --git a/supabase/rollbacks/20261016121400_replace_claim_automation_comments_function.sql b/supabase/rollbacks/20261016121400_replace_claim_automation_comments_function.sql
new file mode 100644
index 0000000..aa9b47e
--- /dev/null
+++ b/supabase/rollbacks/20261016121400_replace_claim_automation_comments_function.sql
@@ -0,0 +1,86 @@
+-- puts back the claim from 20261016103200, which takes the oldest due jobs and at most p_per_account per account
+drop function if exists public.claim_automation_comments(integer, integer, integer, text[]);
+create or replace function public.claim_automation_comments(
+ 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,
+ from_id text,
+ attempts integer,
+ expires_at timestamptz,
+ rule_enabled boolean,
+ reply_text text,
+ link_url text,
+ 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
+ with interrupted as (
+ update public.automation_comments c
+ set status = 'needs_review',
+ status_reason = 'interrupted',
+ claimed_at = null,
+ error_message = 'The run stopped while this reply was being sent. Check the conversation on Instagram before you retry.'
+ where c.status = 'sending' and c.claimed_at < stale_before
+ returning c.id
+ )
+ update public.automation_attempts t
+ set outcome = 'ambiguous', finished_at = now()
+ where t.automation_comment_id in (select interrupted.id from interrupted) and t.outcome = 'sending';
+
+ return query
+ with due as (
+ select c.id, c.account_id, coalesce(c.next_attempt_at, c.claimed_at) as due_at
+ from public.automation_comments c
+ where ((c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now())
+ or (c.status = 'processing' and c.claimed_at < stale_before))
+ and (p_ids is null or c.id = any (p_ids))
+ order by due_at
+ limit p_limit * 10
+ ),
+ fair as (
+ select due.id, due.due_at, row_number() over (partition by due.account_id order by due.due_at) as place
+ from due
+ ),
+ picked as (
+ select c.id
+ from public.automation_comments c
+ join fair on fair.id = c.id
+ where fair.place <= p_per_account
+ and ((c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now())
+ or (c.status = 'processing' and c.claimed_at < stale_before))
+ order by fair.due_at
+ limit p_limit
+ for update of c skip locked
+ ),
+ claimed as (
+ update public.automation_comments c
+ set status = 'processing', claimed_at = now()
+ from picked
+ where c.id = picked.id
+ returning c.id, c.user_id, c.account_id, c.rule_id, c.ig_user_id, c.comment_id, c.from_id, c.attempts, c.expires_at
+ )
+ select claimed.id, claimed.user_id, claimed.account_id, claimed.rule_id, claimed.ig_user_id, claimed.comment_id,
+ claimed.from_id, claimed.attempts, claimed.expires_at,
+ coalesce(r.enabled, false), r.reply_text, r.link_url, 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;
+$$;
+
+revoke execute on function public.claim_automation_comments(integer, integer, integer, text[]) from public, anon, authenticated;
+grant execute on function public.claim_automation_comments(integer, integer, integer, text[]) to service_role;
diff --git a/supabase/rollbacks/20261016121500_replace_reserve_automation_send_function.sql b/supabase/rollbacks/20261016121500_replace_reserve_automation_send_function.sql
new file mode 100644
index 0000000..6c74f3b
--- /dev/null
+++ b/supabase/rollbacks/20261016121500_replace_reserve_automation_send_function.sql
@@ -0,0 +1,91 @@
+-- puts back the reservation from 20261016103300, which counts every attempt and marks no account as limited
+drop function if exists public.reserve_automation_send(text, text, integer, integer, integer, integer, text);
+create or replace function public.reserve_automation_send(
+ p_id text,
+ p_attempt_id text,
+ p_global_limit integer,
+ p_user_limit integer,
+ p_account_limit integer,
+ p_recipient_limit integer
+)
+returns table (outcome text, retry_at timestamptz)
+language plpgsql
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ job public.automation_comments%rowtype;
+ controls public.automation_accounts%rowtype;
+ rule_limit integer;
+ hour_ago timestamptz := now() - interval '1 hour';
+ free_at timestamptz;
+begin
+ perform pg_advisory_xact_lock(hashtext('reserve_automation_send'));
+
+ select * into job from public.automation_comments c where c.id = p_id and c.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.cooldown_until > now() then
+ return query select 'cooldown'::text, controls.cooldown_until;
+ return;
+ end if;
+
+ if job.from_id is not null and (
+ select count(distinct t.automation_comment_id) from public.automation_attempts t
+ where t.account_id = job.account_id and t.recipient_id = job.from_id
+ and t.started_at > now() - interval '1 day' and t.automation_comment_id <> job.id
+ ) >= p_recipient_limit then
+ return query select 'recipient_limit'::text, null::timestamptz;
+ return;
+ end if;
+
+ select r.hourly_limit into rule_limit from public.automation_rules r where r.id = job.rule_id;
+ if rule_limit is not null then
+ select case when count(*) >= rule_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.rule_id = job.rule_id and t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'rule_limit'::text, free_at;
+ return;
+ end if;
+ end if;
+
+ 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.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'account_limit'::text, free_at;
+ return;
+ end if;
+
+ select case when count(*) >= p_user_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.user_id = job.user_id and t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'user_limit'::text, free_at;
+ return;
+ end if;
+
+ select case when count(*) >= p_global_limit then min(t.started_at) + interval '1 hour' end into free_at
+ from public.automation_attempts t where t.started_at > hour_ago;
+ if free_at is not null then
+ return query select 'global_limit'::text, free_at;
+ return;
+ end if;
+
+ update public.automation_comments c
+ set status = 'sending', claimed_at = now(), attempts = c.attempts + 1
+ where c.id = p_id;
+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id)
+ values (p_attempt_id, job.user_id, job.account_id, job.id, job.rule_id, job.from_id);
+ return query select 'ok'::text, null::timestamptz;
+end;
+$$;
+
+revoke execute on function public.reserve_automation_send(text, text, integer, integer, integer, integer) from public, anon, authenticated;
+grant execute on function public.reserve_automation_send(text, text, integer, integer, integer, integer) to service_role;
diff --git a/supabase/rollbacks/20261016121600_replace_finish_automation_send_function.sql b/supabase/rollbacks/20261016121600_replace_finish_automation_send_function.sql
new file mode 100644
index 0000000..accbe59
--- /dev/null
+++ b/supabase/rollbacks/20261016121600_replace_finish_automation_send_function.sql
@@ -0,0 +1,66 @@
+-- puts back the finish from 20261016103400, which keeps no recipient and starts no followers-only wait
+drop function if exists public.finish_automation_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, text);
+create or replace function public.finish_automation_send(
+ 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_message_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_comments%rowtype;
+begin
+ update public.automation_comments c
+ set status = p_status,
+ status_reason = p_reason,
+ error_message = p_error_message,
+ message_id = coalesce(p_message_id, c.message_id),
+ accepted_at = case when p_status = 'accepted' then now() else c.accepted_at end,
+ next_attempt_at = p_next_attempt_at,
+ claimed_at = null
+ where c.id = p_id and (c.status = 'sending' or (c.status = 'needs_review' and c.status_reason = 'interrupted'))
+ returning * into job;
+ 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.automation_comment_id = p_id;
+
+ if p_cooldown_until is not null then
+ insert into public.automation_accounts (account_id, user_id, cooldown_until, cooldown_reason)
+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)
+ on conflict (account_id) do update
+ set cooldown_until = greatest(coalesce(public.automation_accounts.cooldown_until, excluded.cooldown_until), excluded.cooldown_until),
+ cooldown_reason = excluded.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;
+$$;
+
+revoke execute on function public.finish_automation_send(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_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text) to service_role;
diff --git a/supabase/rollbacks/20261016121700_create_automation_followups_for_messages_function.sql b/supabase/rollbacks/20261016121700_create_automation_followups_for_messages_function.sql
new file mode 100644
index 0000000..1dd2cc4
--- /dev/null
+++ b/supabase/rollbacks/20261016121700_create_automation_followups_for_messages_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_followups_for_messages(text, jsonb);
diff --git a/supabase/rollbacks/20261016121800_create_claim_automation_followups_function.sql b/supabase/rollbacks/20261016121800_create_claim_automation_followups_function.sql
new file mode 100644
index 0000000..9a19c21
--- /dev/null
+++ b/supabase/rollbacks/20261016121800_create_claim_automation_followups_function.sql
@@ -0,0 +1 @@
+drop function if exists public.claim_automation_followups(integer, integer, text[]);
diff --git a/supabase/rollbacks/20261016121900_create_reserve_automation_followup_function.sql b/supabase/rollbacks/20261016121900_create_reserve_automation_followup_function.sql
new file mode 100644
index 0000000..0cbbce0
--- /dev/null
+++ b/supabase/rollbacks/20261016121900_create_reserve_automation_followup_function.sql
@@ -0,0 +1 @@
+drop function if exists public.reserve_automation_followup(text, text, text, text);
diff --git a/supabase/rollbacks/20261016122000_create_finish_automation_followup_function.sql b/supabase/rollbacks/20261016122000_create_finish_automation_followup_function.sql
new file mode 100644
index 0000000..c0101d2
--- /dev/null
+++ b/supabase/rollbacks/20261016122000_create_finish_automation_followup_function.sql
@@ -0,0 +1 @@
+drop function if exists public.finish_automation_followup(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text, text, boolean);
diff --git a/supabase/rollbacks/20261016122100_create_automation_review_candidates_function.sql b/supabase/rollbacks/20261016122100_create_automation_review_candidates_function.sql
new file mode 100644
index 0000000..ef3294c
--- /dev/null
+++ b/supabase/rollbacks/20261016122100_create_automation_review_candidates_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_review_candidates(integer, integer, integer, integer);
diff --git a/supabase/rollbacks/20261016122200_create_record_automation_review_function.sql b/supabase/rollbacks/20261016122200_create_record_automation_review_function.sql
new file mode 100644
index 0000000..639c143
--- /dev/null
+++ b/supabase/rollbacks/20261016122200_create_record_automation_review_function.sql
@@ -0,0 +1 @@
+drop function if exists public.record_automation_review(text, boolean, text, timestamptz, text);
diff --git a/supabase/rollbacks/20261016122300_create_expire_automation_jobs_function.sql b/supabase/rollbacks/20261016122300_create_expire_automation_jobs_function.sql
new file mode 100644
index 0000000..3c16649
--- /dev/null
+++ b/supabase/rollbacks/20261016122300_create_expire_automation_jobs_function.sql
@@ -0,0 +1 @@
+drop function if exists public.expire_automation_jobs(integer);
diff --git a/supabase/rollbacks/20261016122400_create_purge_automation_comments_function.sql b/supabase/rollbacks/20261016122400_create_purge_automation_comments_function.sql
new file mode 100644
index 0000000..1446de2
--- /dev/null
+++ b/supabase/rollbacks/20261016122400_create_purge_automation_comments_function.sql
@@ -0,0 +1 @@
+drop function if exists public.purge_automation_comments(timestamptz, integer);
diff --git a/supabase/rollbacks/20261016122500_create_automation_queue_health_function.sql b/supabase/rollbacks/20261016122500_create_automation_queue_health_function.sql
new file mode 100644
index 0000000..eacfd23
--- /dev/null
+++ b/supabase/rollbacks/20261016122500_create_automation_queue_health_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_queue_health(integer);