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 tables and queue functions for comment automation

spacesdrive2989a4bed5aa
diff --git a/shared/types/automation.ts b/shared/types/automation.ts
new file mode 100644
index 0000000..732db61
--- /dev/null
+++ b/shared/types/automation.ts
@@ -0,0 +1,164 @@
+// how a rule's keywords are compared with a comment: anywhere as whole words, or as the whole comment
+export type AutomationMatchMode = 'contains' | 'exact';
+
+// the life of a received comment; ignored ones matched no rule, the rest are reply jobs
+export type AutomationCommentStatus =
+ | 'ignored' | 'queued' | 'processing' | 'retry_wait' | 'sending'
+ | 'accepted' | 'failed' | 'needs_review' | 'skipped' | 'expired';
+
+// what one private reply request to Instagram ended as
+export type AutomationAttemptOutcome = 'sending' | 'accepted' | 'rejected' | 'rate_limited' | 'ambiguous';
+
+export interface AutomationRule {
+ id: string;
+ accountId: string;
+ name: string;
+ keywords: string[];
+ matchMode: AutomationMatchMode;
+ caseSensitive: boolean;
+ // empty means every post and reel of the account
+ mediaIds: string[];
+ replyText: string;
+ linkUrl: string | null;
+ enabled: boolean;
+ // null uses only the account's limit
+ hourlyLimit: number | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+// body of POST /api/automations/rules
+export interface AutomationRuleRequest {
+ accountId: string;
+ name: string;
+ keywords: string[];
+ matchMode?: AutomationMatchMode;
+ caseSensitive?: boolean;
+ mediaIds?: string[];
+ replyText: string;
+ linkUrl?: string | null;
+ enabled?: boolean;
+ hourlyLimit?: number | null;
+}
+
+// body of PUT /api/automations/rules/:id; a rule stays on its account
+export type AutomationRuleUpdateRequest = Partial<Omit<AutomationRuleRequest, 'accountId'>>;
+
+// one connected Instagram account as the automation sees it
+export interface AutomationAccountState {
+ accountId: string;
+ username: string;
+ profilePictureUrl: string;
+ paused: boolean;
+ cooldownUntil: string | null;
+ cooldownReason: string | null;
+ // when Instagram confirmed it sends this account's comments to the webhook
+ subscribedAt: string | null;
+}
+
+export interface AutomationLimits {
+ accountHourly: number;
+ userHourly: number;
+ globalHourly: number;
+ recipientDaily: number;
+}
+
+export interface AutomationSettings {
+ // the webhook secrets are set, so Meta's requests can be verified
+ webhookConfigured: boolean;
+ // AUTOMATION_PAUSED holds every reply on this instance
+ paused: boolean;
+ limits: AutomationLimits;
+}
+
+export interface AutomationActivityItem {
+ id: string;
+ accountId: string;
+ ruleId: string | null;
+ commentId: string;
+ mediaId: string | null;
+ fromUsername: string | null;
+ text: string | null;
+ status: AutomationCommentStatus;
+ statusReason: string | null;
+ errorMessage: string | null;
+ attempts: number;
+ nextAttemptAt: string | null;
+ acceptedAt: string | null;
+ expiresAt: string;
+ createdAt: string;
+}
+
+export interface AutomationStats {
+ comments: Partial<Record<AutomationCommentStatus, number>>;
+ attempts: Partial<Record<AutomationAttemptOutcome, number>>;
+}
+
+// GET /api/automations
+export interface AutomationOverviewResponse {
+ success: true;
+ rules: AutomationRule[];
+ accounts: AutomationAccountState[];
+ settings: AutomationSettings;
+}
+
+// POST /api/automations/rules, PUT /api/automations/rules/:id and POST /api/automations/rules/:id/duplicate
+export interface AutomationRuleResponse {
+ success: true;
+ rule: AutomationRule;
+}
+
+// body of POST /api/automations/test: a rule draft and a sample comment; nothing is sent
+export interface AutomationTestRequest {
+ keywords: string[];
+ matchMode?: AutomationMatchMode;
+ caseSensitive?: boolean;
+ mediaIds?: string[];
+ replyText: string;
+ linkUrl?: string | null;
+ comment: string;
+ mediaId?: string;
+}
+
+export interface AutomationTestResponse {
+ success: true;
+ matched: boolean;
+ // the keyword that matched, or null
+ keyword: string | null;
+ // the private reply exactly as it would be sent
+ message: string;
+ messageBytes: number;
+ maxMessageBytes: number;
+}
+
+// GET /api/automations/activity; pass nextBefore as before for the next page
+export interface AutomationActivityResponse {
+ success: true;
+ items: AutomationActivityItem[];
+ nextBefore: string | null;
+}
+
+// POST /api/automations/activity/:id/retry
+export interface AutomationActivityItemResponse {
+ success: true;
+ item: AutomationActivityItem;
+}
+
+// GET /api/automations/stats
+export interface AutomationStatsResponse {
+ success: true;
+ from: string;
+ to: string;
+ stats: AutomationStats;
+}
+
+// body of PUT /api/automations/accounts/:accountId
+export interface AutomationAccountRequest {
+ paused: boolean;
+}
+
+// PUT /api/automations/accounts/:accountId and POST /api/automations/accounts/:accountId/subscribe
+export interface AutomationAccountResponse {
+ success: true;
+ account: AutomationAccountState;
+}
diff --git a/supabase/migrations/20261016100000_create_automation_accounts.sql b/supabase/migrations/20261016100000_create_automation_accounts.sql
new file mode 100644
index 0000000..9d8c7f7
--- /dev/null
+++ b/supabase/migrations/20261016100000_create_automation_accounts.sql
@@ -0,0 +1,24 @@
+-- per Instagram account automation controls: the owner's pause, a cooldown after Instagram limits, and the webhook subscription
+create table public.automation_accounts (
+ account_id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ paused boolean not null default false,
+ -- null when the owner paused it; set when the Worker held replies because Instagram refused the account's token
+ paused_reason text,
+ cooldown_until timestamptz,
+ cooldown_reason text,
+ subscribed_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_accounts_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ constraint automation_accounts_paused_reason_check check (paused_reason is null or char_length(paused_reason) <= 200),
+ constraint automation_accounts_cooldown_reason_check check (cooldown_reason is null or char_length(cooldown_reason) <= 200)
+);
+
+-- only the Worker's service role reads the table; the anon key ships in every browser
+alter table public.automation_accounts enable row level security;
+revoke all on table public.automation_accounts from anon, authenticated;
+
+create trigger automation_accounts_set_updated_at before update on public.automation_accounts
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016100100_create_automation_rules.sql b/supabase/migrations/20261016100100_create_automation_rules.sql
new file mode 100644
index 0000000..e629c8b
--- /dev/null
+++ b/supabase/migrations/20261016100100_create_automation_rules.sql
@@ -0,0 +1,40 @@
+-- keyword rules that answer a comment with a private reply
+create table public.automation_rules (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ account_id text not null,
+ name text not null,
+ keywords text[] not null,
+ match_mode text not null default 'contains',
+ case_sensitive boolean not null default false,
+ -- empty means every post and reel of the account
+ media_ids text[] not null default '{}',
+ reply_text text not null,
+ link_url text,
+ enabled boolean not null default false,
+ hourly_limit integer,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_rules_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ constraint automation_rules_name_check check (char_length(name) between 1 and 80),
+ constraint automation_rules_keywords_check check (cardinality(keywords) between 1 and 10),
+ constraint automation_rules_match_mode_check check (match_mode in ('contains', 'exact')),
+ constraint automation_rules_media_ids_check check (cardinality(media_ids) <= 50),
+ constraint automation_rules_reply_text_check check (char_length(reply_text) between 1 and 1000),
+ constraint automation_rules_link_url_check check (link_url is null or link_url ~ '^https://'),
+ -- Instagram allows 750 private replies an hour per account for posts and reels
+ constraint automation_rules_hourly_limit_check check (hourly_limit is null or hourly_limit between 1 and 750)
+);
+
+-- only the Worker's service role reads the table; the anon key ships in every browser
+alter table public.automation_rules enable row level security;
+revoke all on table public.automation_rules from anon, authenticated;
+
+create trigger automation_rules_set_updated_at before update on public.automation_rules
+ for each row execute function public.set_updated_at();
+
+-- automationRules.listForUser: where user_id = $1 order by created_at, id
+create index automation_rules_user_id_created_at_idx on public.automation_rules (user_id, created_at, id);
+-- the webhook reads only the enabled rules of an account
+create index automation_rules_enabled_account_idx on public.automation_rules (account_id) where enabled;
diff --git a/supabase/migrations/20261016100200_create_automation_comments.sql b/supabase/migrations/20261016100200_create_automation_comments.sql
new file mode 100644
index 0000000..4980a7d
--- /dev/null
+++ b/supabase/migrations/20261016100200_create_automation_comments.sql
@@ -0,0 +1,58 @@
+-- every comment the webhook delivered for an account with an enabled rule; a matched comment is also the job that sends its reply
+create table public.automation_comments (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ account_id text not null,
+ rule_id text references public.automation_rules (id) on delete set null,
+ -- the professional account the webhook named, so a comment is stored once however many members connected that account
+ ig_user_id text not null,
+ comment_id text not null,
+ media_id text,
+ from_id text,
+ from_username text,
+ -- kept only for matched comments; others are counted without their words
+ text text,
+ status text not null,
+ status_reason text,
+ error_message text,
+ attempts integer not null default 0,
+ next_attempt_at timestamptz,
+ claimed_at timestamptz,
+ message_id text,
+ accepted_at timestamptz,
+ -- when Meta sent the notification; private replies close 7 days after the comment
+ notified_at timestamptz not null,
+ expires_at timestamptz not null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_comments_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ -- Meta delivers a notification again until it is acknowledged, so the second copy is refused here
+ constraint automation_comments_comment_key unique (ig_user_id, comment_id),
+ constraint automation_comments_status_check check (status in (
+ 'ignored', 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'
+ )),
+ constraint automation_comments_waiting_check check (status not in ('queued', 'retry_wait') or next_attempt_at is not null),
+ constraint automation_comments_attempts_check check (attempts >= 0),
+ -- Instagram comments are at most 2,200 characters
+ constraint automation_comments_text_check check (text is null or char_length(text) <= 2200),
+ constraint automation_comments_error_message_check check (error_message is null or char_length(error_message) <= 500)
+);
+
+-- only the Worker's service role reads the table; the anon key ships in every browser
+alter table public.automation_comments enable row level security;
+revoke all on table public.automation_comments from anon, authenticated;
+
+create trigger automation_comments_set_updated_at before update on public.automation_comments
+ for each row execute function public.set_updated_at();
+
+-- claim_automation_comments: jobs that are due, oldest first
+create index automation_comments_due_idx on public.automation_comments (next_attempt_at) where status in ('queued', 'retry_wait');
+-- claim_automation_comments: jobs whose run stopped holding them
+create index automation_comments_claimed_idx on public.automation_comments (claimed_at) where status in ('processing', 'sending');
+-- automationComments.listForUser and automation_stats: where user_id = $1 order by created_at desc
+create index automation_comments_user_id_created_at_idx on public.automation_comments (user_id, created_at desc);
+-- removing a rule clears rule_id on its comments
+create index automation_comments_rule_id_idx on public.automation_comments (rule_id) where rule_id is not null;
+-- the daily retention delete across all users
+create index automation_comments_created_at_idx on public.automation_comments (created_at);
diff --git a/supabase/migrations/20261016100300_create_automation_attempts.sql b/supabase/migrations/20261016100300_create_automation_attempts.sql
new file mode 100644
index 0000000..dcf7abf
--- /dev/null
+++ b/supabase/migrations/20261016100300_create_automation_attempts.sql
@@ -0,0 +1,36 @@
+-- one row per private reply request sent to Instagram, which is what the sending limits count
+create table public.automation_attempts (
+ 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,
+ recipient_id text,
+ outcome text not null default 'sending',
+ error_code integer,
+ error_subcode integer,
+ http_status integer,
+ started_at timestamptz not null default now(),
+ finished_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint automation_attempts_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade,
+ constraint automation_attempts_outcome_check check (outcome in ('sending', 'accepted', 'rejected', 'rate_limited', 'ambiguous'))
+);
+
+-- only the Worker's service role reads the table; the anon key ships in every browser
+alter table public.automation_attempts enable row level security;
+revoke all on table public.automation_attempts from anon, authenticated;
+
+create trigger automation_attempts_set_updated_at before update on public.automation_attempts
+ for each row execute function public.set_updated_at();
+
+-- reserve_automation_send counts the last hour at each scope, and the last day per recipient
+create index automation_attempts_started_at_idx on public.automation_attempts (started_at);
+create index automation_attempts_user_id_started_at_idx on public.automation_attempts (user_id, started_at);
+create index automation_attempts_account_id_started_at_idx on public.automation_attempts (account_id, started_at);
+create index automation_attempts_rule_id_started_at_idx on public.automation_attempts (rule_id, started_at) where rule_id is not null;
+create index automation_attempts_recipient_idx on public.automation_attempts (account_id, recipient_id, started_at);
+-- finish_automation_send and the claim close the attempts of one comment
+create index automation_attempts_comment_idx on public.automation_attempts (automation_comment_id);
diff --git a/supabase/migrations/20261016100400_create_audit_events.sql b/supabase/migrations/20261016100400_create_audit_events.sql
new file mode 100644
index 0000000..90699c4
--- /dev/null
+++ b/supabase/migrations/20261016100400_create_audit_events.sql
@@ -0,0 +1,26 @@
+-- who connected, removed or changed what; rows outlive the account they describe, and go with the user
+create table public.audit_events (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ action text not null,
+ subject_type text not null,
+ subject_id text,
+ details jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint audit_events_action_check check (action ~ '^[a-z_]+\.[a-z_]+$'),
+ constraint audit_events_subject_type_check check (subject_type in ('account', 'automation_rule', 'automation_account', 'automation_comment')),
+ constraint audit_events_details_check check (jsonb_typeof(details) = 'object')
+);
+
+-- only the Worker's service role reads the table; the anon key ships in every browser
+alter table public.audit_events enable row level security;
+revoke all on table public.audit_events from anon, authenticated;
+
+create trigger audit_events_set_updated_at before update on public.audit_events
+ for each row execute function public.set_updated_at();
+
+-- auditEvents.listForUser: where user_id = $1 order by created_at desc
+create index audit_events_user_id_created_at_idx on public.audit_events (user_id, created_at desc);
+-- the daily retention delete across all users
+create index audit_events_created_at_idx on public.audit_events (created_at);
diff --git a/supabase/migrations/20261016100500_index_accounts_instagram_user.sql b/supabase/migrations/20261016100500_index_accounts_instagram_user.sql
new file mode 100644
index 0000000..9972da0
--- /dev/null
+++ b/supabase/migrations/20261016100500_index_accounts_instagram_user.sql
@@ -0,0 +1,2 @@
+-- a webhook names the Instagram account by its id, which lives in data, so the lookup needs its own index
+create index if not exists accounts_instagram_user_idx on public.accounts ((data ->> 'igUserId')) where platform = 'instagram';
diff --git a/supabase/migrations/20261016100600_create_automation_rules_for_ig_user_function.sql b/supabase/migrations/20261016100600_create_automation_rules_for_ig_user_function.sql
new file mode 100644
index 0000000..2fba753
--- /dev/null
+++ b/supabase/migrations/20261016100600_create_automation_rules_for_ig_user_function.sql
@@ -0,0 +1,28 @@
+-- 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/migrations/20261016100700_create_claim_automation_comments_function.sql b/supabase/migrations/20261016100700_create_claim_automation_comments_function.sql
new file mode 100644
index 0000000..37128d1
--- /dev/null
+++ b/supabase/migrations/20261016100700_create_claim_automation_comments_function.sql
@@ -0,0 +1,89 @@
+-- hands one run the due reply jobs, at most p_per_account per account so a busy account cannot hold back the others;
+-- p_ids limits it to the comments a webhook has just stored
+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
+ -- 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 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 (
+ -- the status test is repeated on the locked row, so a job another run claimed in between is left alone
+ 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;
+$$;
+
+-- 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/20261016100800_create_reserve_automation_send_function.sql b/supabase/migrations/20261016100800_create_reserve_automation_send_function.sql
new file mode 100644
index 0000000..b66451d
--- /dev/null
+++ b/supabase/migrations/20261016100800_create_reserve_automation_send_function.sql
@@ -0,0 +1,94 @@
+-- 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)
+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
+ -- 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
+ if job.from_id is not null and (
+ select count(*) 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'
+ ) >= 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.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;
+$$;
+
+-- 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) 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/migrations/20261016100900_create_finish_automation_send_function.sql b/supabase/migrations/20261016100900_create_finish_automation_send_function.sql
new file mode 100644
index 0000000..97361f6
--- /dev/null
+++ b/supabase/migrations/20261016100900_create_finish_automation_send_function.sql
@@ -0,0 +1,68 @@
+-- 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
+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;
+ -- 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) 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/migrations/20261016101000_create_automation_stats_function.sql b/supabase/migrations/20261016101000_create_automation_stats_function.sql
new file mode 100644
index 0000000..2d2ab34
--- /dev/null
+++ b/supabase/migrations/20261016101000_create_automation_stats_function.sql
@@ -0,0 +1,45 @@
+-- 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;
diff --git a/supabase/rollbacks/20261016100000_create_automation_accounts.sql b/supabase/rollbacks/20261016100000_create_automation_accounts.sql
new file mode 100644
index 0000000..b3d8f3a
--- /dev/null
+++ b/supabase/rollbacks/20261016100000_create_automation_accounts.sql
@@ -0,0 +1,2 @@
+-- removes every account's pause, cooldown and webhook subscription record
+drop table if exists public.automation_accounts;
diff --git a/supabase/rollbacks/20261016100100_create_automation_rules.sql b/supabase/rollbacks/20261016100100_create_automation_rules.sql
new file mode 100644
index 0000000..e7aff57
--- /dev/null
+++ b/supabase/rollbacks/20261016100100_create_automation_rules.sql
@@ -0,0 +1,2 @@
+-- removes every automation rule; roll back automation_comments and automation_attempts first
+drop table if exists public.automation_rules;
diff --git a/supabase/rollbacks/20261016100200_create_automation_comments.sql b/supabase/rollbacks/20261016100200_create_automation_comments.sql
new file mode 100644
index 0000000..ed19096
--- /dev/null
+++ b/supabase/rollbacks/20261016100200_create_automation_comments.sql
@@ -0,0 +1,2 @@
+-- removes every received comment and its reply history; roll back automation_attempts first
+drop table if exists public.automation_comments;
diff --git a/supabase/rollbacks/20261016100300_create_automation_attempts.sql b/supabase/rollbacks/20261016100300_create_automation_attempts.sql
new file mode 100644
index 0000000..5ec16dd
--- /dev/null
+++ b/supabase/rollbacks/20261016100300_create_automation_attempts.sql
@@ -0,0 +1,2 @@
+-- removes the record of every private reply request
+drop table if exists public.automation_attempts;
diff --git a/supabase/rollbacks/20261016100400_create_audit_events.sql b/supabase/rollbacks/20261016100400_create_audit_events.sql
new file mode 100644
index 0000000..57d3861
--- /dev/null
+++ b/supabase/rollbacks/20261016100400_create_audit_events.sql
@@ -0,0 +1,2 @@
+-- removes the audit history of every user
+drop table if exists public.audit_events;
diff --git a/supabase/rollbacks/20261016100500_index_accounts_instagram_user.sql b/supabase/rollbacks/20261016100500_index_accounts_instagram_user.sql
new file mode 100644
index 0000000..1ffd193
--- /dev/null
+++ b/supabase/rollbacks/20261016100500_index_accounts_instagram_user.sql
@@ -0,0 +1 @@
+drop index if exists public.accounts_instagram_user_idx;
diff --git a/supabase/rollbacks/20261016100600_create_automation_rules_for_ig_user_function.sql b/supabase/rollbacks/20261016100600_create_automation_rules_for_ig_user_function.sql
new file mode 100644
index 0000000..6e46e3c
--- /dev/null
+++ b/supabase/rollbacks/20261016100600_create_automation_rules_for_ig_user_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_rules_for_ig_user(text);
diff --git a/supabase/rollbacks/20261016100700_create_claim_automation_comments_function.sql b/supabase/rollbacks/20261016100700_create_claim_automation_comments_function.sql
new file mode 100644
index 0000000..5b92cb4
--- /dev/null
+++ b/supabase/rollbacks/20261016100700_create_claim_automation_comments_function.sql
@@ -0,0 +1 @@
+drop function if exists public.claim_automation_comments(integer, integer, integer, text[]);
diff --git a/supabase/rollbacks/20261016100800_create_reserve_automation_send_function.sql b/supabase/rollbacks/20261016100800_create_reserve_automation_send_function.sql
new file mode 100644
index 0000000..ba58ed1
--- /dev/null
+++ b/supabase/rollbacks/20261016100800_create_reserve_automation_send_function.sql
@@ -0,0 +1 @@
+drop function if exists public.reserve_automation_send(text, text, integer, integer, integer, integer);
diff --git a/supabase/rollbacks/20261016100900_create_finish_automation_send_function.sql b/supabase/rollbacks/20261016100900_create_finish_automation_send_function.sql
new file mode 100644
index 0000000..a5d3612
--- /dev/null
+++ b/supabase/rollbacks/20261016100900_create_finish_automation_send_function.sql
@@ -0,0 +1 @@
+drop function if exists public.finish_automation_send(text, text, text, text, text, text, text, integer, integer, integer, timestamptz, timestamptz, text, text);
diff --git a/supabase/rollbacks/20261016101000_create_automation_stats_function.sql b/supabase/rollbacks/20261016101000_create_automation_stats_function.sql
new file mode 100644
index 0000000..b6589ed
--- /dev/null
+++ b/supabase/rollbacks/20261016101000_create_automation_stats_function.sql
@@ -0,0 +1 @@
+drop function if exists public.automation_stats(uuid, timestamptz, timestamptz, text, text);