TrolyPage

An autonomous Marketing & Sales operating system for businesses that want AI-powered omni-channel growth.

Contact Info

Follow Us

17 min read

Auto-Stop State Machines for AI Follow-Up Agents: Never Pitch a Customer Who Already Paid or Replied

TrolyPage

Dec 01, 2026
14 views
Architecture diagram showing four mandatory auto-stop gates—customer reply, confirmed payment, opt-out, and human takeover—before AI follow-up dispatch.

To prevent AI follow-up sequences from pitching customers who already paid or replied, replace blind timer queues with a deterministic state machine asserted right before dispatch. Enforce four mandatory hard-stop transitions: customer reply, confirmed payment or new order, explicit or semantic opt-out, and human takeover, combined with live channel outbound window validation across Messenger, Instagram, WhatsApp, and Twilio SMS.

Editorial disclosure: Published by TrolyPage, one of the automation platforms discussed in this architecture guide. External platform policies, error codes, and TrolyPage plan limits were verified against primary vendor documentation on December 1, 2026; quantitative failure-rate examples below are labeled explicit engineering calculations.

Why AI Follow-Up Sequences Break Without a Pre-Dispatch State Machine

Every ecommerce and SaaS operations team eventually hits the same bug: a prospect asks about pricing in Messenger or WhatsApp, completes checkout twenty minutes later, and still gets an automated "Still thinking it over? Here is 10% off" message the next morning. The buyer either demands a retroactive discount or blocks your account.

The flaw is architectural, not copywriting-related: teams schedule follow-ups as fire-and-forget timer jobs at enrollment (t = 0) instead of asserting live state at dispatch (t = send). When a buyer replies, pays externally, gets claimed by a rep, or opts out during the delay window, a blind queue cannot abort the queued send.

In Anthropic's engineering guidance on building effective agents, the authors draw a sharp line between autonomous agent loops and deterministic workflows governed by predefined code paths. Follow-up suppression belongs strictly in deterministic code paths. Similarly, the OpenAI Agents SDK Guardrails architecture uses tripwire checks to halt execution before an agent triggers an external side effect. For messaging sequences, the outbound API call is the irreversible side effect.

Consider an illustrative operational calculation for a mid-volume DTC or B2B SaaS team processing 1,000 follow-up candidates per month on a timer-based drip queue with a 2-hour CRM sync lag:

  • Mid-sequence collision volume: If 14% of enrolled leads (140 customers) reply in a separate thread or complete an order between sequence enrollment and the next scheduled nudge, a blind timer queue dispatches stale pitches to all 140 customers.
  • Block and spam-report spillover: If just 15% of those collided recipients (21 customers) tap Block or Report Spam out of frustration, that single sequence generates a 2.1% negative-feedback rate (21 / 1,000). Under Meta's dynamic rolling 7-day WhatsApp quality-rating model (which evaluates user blocks and spam reports without publishing a fixed percentage cutoff), sustained feedback spikes degrade phone-number quality and restrict outbound throughput.
  • Compounding compliance exposure: On Meta Messenger or Instagram, firing an unguarded timer job past the 24-hour clock triggers Graph API rejections and policy strikes; on SMS, missing a non-standard opt-out sentence exposes the sender to federal Telephone Consumer Protection Act (TCPA) claims.

Architectural Comparison: Event-Driven Auto-Stop vs. Timer Drips vs. Manual Unenroll

Comparison chart of post-conversion collision rates and Meta 24-hour or TCPA compliance risk across three follow-up architectures
Post-conversion collision rates and Meta / SMS compliance exposure across event-driven Auto-Stop gates, timer drips, and manual CRM tag cleanup.

Operations teams generally choose among three patterns when orchestrating AI follow-up messaging sequences. The table below compares their failure modes, channel compliance posture, and ongoing engineering overhead.

Architecture Pattern Collision Probability (Paid / Replied Leads) Meta 24h & WhatsApp Policy Risk Twilio SMS & TCPA Exposure Ops & Engineering Cost Primary Failure Cost
Option A: 4-Signal Event-Driven Auto-Stop State Machine + Pre-Dispatch Assertion Near zero (<0.5%, limited only to sub-second webhook transit lag via atomic DB lock) Low: hard-checks live window_expires_at before Graph/Cloud API call; suppresses promotional sends past 24h Low: pairs Twilio OptOutType webhooks and Error 21610 blocks with semantic intent tripwires for immediate suppression Initial schema + webhook wiring (or native rules in platforms like TrolyPage); minimal daily rep triage Webhook downtime or unmapped external checkout IDs if third-party stores omit payment sync
Option B: Fire-and-Forget Timer Drip Queue High (10%–20% when orders or replies happen during 2h–24h delay windows) High: stale jobs fire past the 24h customer service window or after block events, driving Graph subcode 2018278 errors and rolling 7-day quality-rating penalties High: misses conversational opt-outs and async order events unless workers re-query CRM state at send time Low initial setup, high ongoing incident firefighting, list scrubbing, and support apologies Retroactive coupon payouts, WhatsApp number quality downgrade to Red, and TCPA demand risk ($500–$1,500/text statutory exposure)
Option C: Manual Agent Unenroll Moderate to High (8%–18% during nights, weekends, shift handoffs, and promo spikes) Moderate: reps forget to remove leads before 24h expiry or across multiple inbox tabs Moderate to High: human lag fails immediate suppression when a customer texts back off-hours Zero dev build, high recurring labor cost (est. 15–30 min/rep/day auditing tags across channels) Extra seat overhead and silent sequence collisions whenever live chat volume spikes

Option A eliminates the gap between intent and execution because it treats follow-up eligibility as a real-time state transition rather than a static queue entry. Even if an async job wakes up at T+4 hours, it cannot call the channel send endpoint until an atomic pre-dispatch assertion clears all four hard-stop conditions and verifies the outbound window.

The 4 Mandatory Hard-Stop Conditions and Channel Outbound Windows

Event-driven Auto-Stop state machine and transactional pre-dispatch gate checking reply, payment, opt-out, and human takeover
Transactional Pre-Send Gate: workers re-verify all four hard-stop signals and outbound channel policy windows at dispatch time.

To make auto stop rules for AI follow up messaging sequences airtight across omnichannel inboxes, every active sequence must subscribe to four immutable stop transitions plus a channel-specific outbound clock.

1. Customer Reply (REPLIED)

Any inbound contact interaction—text, voice note, quick-reply tap, story reply, or reaction—must transition state from ENROLLED to STOPPED_REPLIED. Never scope this check to a single channel: if a prospect messages on Instagram DM and later replies via Website Chat or Email under a matched contact ID, abort the Instagram sequence immediately.

An inbound reply also resets Meta's 24-hour messaging clock, so your router should pass the fresh turn back to the live conversational AI or assigned agent with full thread context.

2. Confirmed Payment or New Order (PAID_OR_ORDERED)

Never stop sequences only at "Delivered," and never stop early on an unpaid draft. Separate ORDER_DRAFT_CREATED (keep follow-up armed) from PAID_OR_ORDERED (hard-stop immediately).

If checkout runs inside your inbox platform's native order flow, payment updates the thread automatically. On external storefronts like Shopify, WooCommerce, or Stripe Payment Links, your billing layer must push orders/paid or checkout.session.completed webhooks matched by phone, email, or customer ID—otherwise the follow-up engine stays blind to completed revenue.

3. Explicit and Semantic Opt-Out (OPTED_OUT)

Opt-out enforcement fails when teams rely solely on exact single-word keyword matching. On SMS, Twilio's Advanced Opt-Out documentation specifies standard English opt-out keywords—STOP, STOPALL, UNSUBSCRIBE, CANCEL, END, QUIT, REVOKE, and OPTOUT—which trigger carrier-level suppression and cause subsequent send attempts to fail with Twilio API Error 21610 (HTTP 400: attempt to send to unsubscribed recipient).

However, on Messenger, Instagram, WhatsApp, and even SMS when users write full sentences, customers rarely type a bare STOP. They write "Please take me off this list," "Stop messaging me here," or "No thanks, I already bought from someone else." Under US Federal Communications Commission (FCC) TCPA revocation rules, consumers can revoke consent through any reasonable method, with a hard compliance ceiling of 10 business days—and under 47 U.S.C. § 227, unauthorized automated texts carry $500 in base statutory damages per message and up to $1,500 per willful violation. Similarly, the WhatsApp Business Messaging Policy requires businesses to respect opt-out requests immediately or risk quality-rating drops and account restrictions.

Your state machine must therefore treat OPTED_OUT as a permanent, workspace-wide contact attribute (overriding future sequence re-enrollments) populated by both deterministic carrier/API webhooks (such as Twilio's OptOutType parameter) and a semantic intent guardrail on free-form replies.

4. Human Takeover (HUMAN_LOCKED)

Nothing erodes buyer trust faster than an account executive negotiating custom onboarding terms in chat while an automated sequence drops a generic "Need help choosing a plan?" template mid-thread. Whenever a human agent claims a conversation, posts a manual outbound reply, applies an escalation tag, or triggers a handoff action, the state machine must lock automated follow-ups immediately.

If your support desk runs shift rotations, configure a deterministic release policy: either require manual re-enablement when the rep closes the ticket, or enforce a long cooldown (for example, 72 hours after the last human reply) rather than auto-resuming while a rep is simply at lunch. For detailed escalation thresholds, review our guide on when an AI chatbot should hand off to a human.

5. Channel Outbound Window Validation (WINDOW_EXPIRED)

Even if none of the four business-logic stop signals have fired, your pre-dispatch gate must verify channel-specific messaging policy windows before every send:

  • Facebook Messenger & Instagram DM: Per the Meta Messenger Platform and IG Messaging API Policy and Send Messages documentation, businesses have a 24-hour standard messaging window from the user's most recent interaction (extended up to 7 days for threads initiated via Click-to-Messenger or Click-to-Direct ads). Sending promotional follow-ups after window expiry triggers Graph API error subcode 2018278 and risks page messaging restrictions. See our Messenger 24-hour rule breakdown for tag constraints.
  • WhatsApp Cloud API: According to the WhatsApp Cloud API Send Messages guide, free-form messages are permitted only inside the active 24-hour customer service window opened by an inbound user message. Once closed, your state machine must block free-form AI follow-ups unless the step explicitly transitions to a pre-approved Utility or Marketing Message Template with valid opt-in.
  • Twilio SMS & Email: No 24-hour Meta session clock applies, so the gate enforces global suppression (OPTED_OUT / Error 21610 sync), regional quiet hours, and maximum cadence caps (for example, 1–2 touches max per inquiry).

Production Asset 1: Deterministic Pre-Dispatch State Machine (SQL + Python)

Below is a production-ready pattern combining an atomic PostgreSQL row lock (FOR UPDATE SKIP LOCKED) with a deterministic Python pre-dispatch evaluator. Notice that the worker re-verifies all four hard-stop conditions and the channel window inside the final millisecond before calling the messaging API—preventing two concurrent workers or a late-arriving payment webhook from racing past a stale flag.

-- 1. PostgreSQL State Table & Atomic Pre-Dispatch Claim
CREATE TABLE followup_enrollments (
    id                  BIGSERIAL PRIMARY KEY,
    workspace_id        BIGINT NOT NULL,
    contact_id          BIGINT NOT NULL,
    conversation_id     BIGINT NOT NULL,
    channel             VARCHAR(32) NOT NULL,
    status              VARCHAR(32) NOT NULL DEFAULT 'ENROLLED',
    enrolled_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    next_dispatch_at    TIMESTAMPTZ NOT NULL,
    last_customer_msg_at TIMESTAMPTZ NOT NULL,
    window_expires_at   TIMESTAMPTZ,
    stop_reason         VARCHAR(64),
    stopped_at          TIMESTAMPTZ,
    step_index          SMALLINT NOT NULL DEFAULT 1
);

CREATE UNIQUE INDEX uq_active_enrollment
ON followup_enrollments (workspace_id, contact_id, conversation_id)
WHERE status = 'ENROLLED';

CREATE INDEX idx_followup_due ON followup_enrollments (status, next_dispatch_at)
WHERE status = 'ENROLLED';

BEGIN;
SELECT fe.*, c.opted_out, c.last_paid_order_at, conv.human_locked_at, conv.last_inbound_at
FROM followup_enrollments fe
JOIN contacts c ON c.id = fe.contact_id
JOIN conversations conv ON conv.id = fe.conversation_id
WHERE fe.status = 'ENROLLED'
  AND fe.next_dispatch_at <= NOW()
ORDER BY fe.next_dispatch_at ASC
LIMIT 50
FOR UPDATE OF fe SKIP LOCKED;
# 2. Python Pre-Dispatch Assertion Engine
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional


class DispatchDecision(str, Enum):
    ALLOW = "ALLOW"
    STOP_REPLIED = "STOPPED_REPLIED"
    STOP_PAID = "STOPPED_PAID"
    STOP_OPT_OUT = "STOPPED_OPT_OUT"
    PAUSE_HUMAN = "PAUSED_HUMAN"
    EXPIRE_WINDOW = "EXPIRED_WINDOW"


@dataclass(frozen=True)
class FollowUpSnapshot:
    channel: str
    enrolled_at: datetime
    now_utc: datetime
    last_inbound_at: Optional[datetime]
    last_paid_order_at: Optional[datetime]
    contact_opted_out: bool
    human_locked_at: Optional[datetime]
    window_expires_at: Optional[datetime]
    uses_approved_wa_template: bool = False


def evaluate_followup_eligibility(s: FollowUpSnapshot) -> DispatchDecision:
    if s.contact_opted_out:
        return DispatchDecision.STOP_OPT_OUT
    if s.last_paid_order_at is not None and s.last_paid_order_at >= s.enrolled_at:
        return DispatchDecision.STOP_PAID
    if s.human_locked_at is not None:
        return DispatchDecision.PAUSE_HUMAN
    if s.last_inbound_at is not None and s.last_inbound_at > s.enrolled_at:
        return DispatchDecision.STOP_REPLIED
    if s.channel in {"messenger", "instagram", "whatsapp"}:
        if s.window_expires_at is None or s.now_utc >= s.window_expires_at:
            if s.channel == "whatsapp" and s.uses_approved_wa_template:
                return DispatchDecision.ALLOW
            return DispatchDecision.EXPIRE_WINDOW
    return DispatchDecision.ALLOW

Notice the evaluation precedence inside evaluate_followup_eligibility: OPTED_OUT runs first because carrier and TCPA/WhatsApp compliance overrides every other state, followed by PAID_OR_ORDERED, HUMAN_LOCKED, REPLIED, and finally WINDOW_EXPIRED. Because every timestamp comparison uses UTC timestamps captured from authoritative webhook events, the LLM never decides whether a user is eligible to receive a nudge.

Production Asset 2: Trigger-Condition-Action Rule Table & Semantic Opt-Out Guardrail

When implementing auto-stop rules inside an automation engine—whether custom-built or configured in an omnichannel inbox—translate your state transitions into explicit Trigger-Condition-Action policies paired with a two-tier opt-out detector.

{
  "followup_auto_stop_rules": [
    {
      "rule_id": "stop_on_inbound_reply",
      "trigger": "message.inbound.received",
      "condition": "contact.active_followup_count > 0",
      "action": [
        "set_followup_status('STOPPED_REPLIED')",
        "refresh_channel_window_24h()",
        "route_to_ai_or_assigned_agent()"
      ]
    },
    {
      "rule_id": "stop_on_confirmed_payment",
      "trigger": "order.paid_or_confirmed",
      "condition": "order.status IN ['paid', 'processing', 'completed'] AND contact.active_followup_count > 0",
      "action": [
        "set_followup_status('STOPPED_PAID')",
        "cancel_pending_followup_jobs(contact_id)",
        "tag_conversation('converted_order')"
      ]
    },
    {
      "rule_id": "stop_on_opt_out_signal",
      "trigger": "opt_out.detected_or_webhook",
      "condition": "twilio.OptOutType == 'STOP' OR regex_opt_out_match OR semantic_opt_out.should_stop == true",
      "action": [
        "set_contact_global_suppression(true)",
        "set_followup_status('STOPPED_OPT_OUT')",
        "log_compliance_audit_event()"
      ]
    },
    {
      "rule_id": "pause_on_human_handoff",
      "trigger": "conversation.human_takeover",
      "condition": "actor.type == 'human_agent' OR ai.action == 'handoff'",
      "action": [
        "set_followup_status('PAUSED_HUMAN')",
        "pause_ai_auto_replies(conversation_id)"
      ]
    }
  ],
  "semantic_opt_out_guardrail": {
    "tier_1_zero_token_regex": "^(stop|stopall|unsubscribe|cancel|end|quit|revoke|optout|no thanks|remove me)$",
    "tier_2_llm_classifier_prompt": "Classify if the customer message expresses an explicit or implicit request to stop receiving messages or marketing follow-ups (e.g., 'stop texting me', 'take me off your list', 'bought elsewhere do not follow up'). Return strict JSON: {\"should_stop\": boolean, \"confidence\": number, \"reason\": string}.",
    "tripwire_threshold": 0.75
  }
}

The two-tier opt-out guardrail balances cost and latency. Tier 1 catches exact keywords (STOP, UNSUBSCRIBE, CANCEL) and Twilio's OptOutType webhook at 0 LLM tokens and under 2ms. Tier 2—a structured JSON tripwire—fires only when inbound text contains negative markers ("don't", "stop", "remove", "bought elsewhere") without matching Tier 1, consuming roughly 250 tokens per checked turn (~6.25% of a typical 4,000-token RAG exchange).

How TrolyPage Implements Auto-Stop Sequences — And Where You Still Need Webhooks

If your team prefers not to build and maintain the PostgreSQL queue, Meta Graph error handlers, and handoff locks from scratch, TrolyPage's messaging and automation workspace implements native Auto-Stop Follow-up logic directly inside its omnichannel inbox. Automated follow-up sequences pause or terminate on all four mandatory conditions—customer reply, purchase or payment, opt-out, and human takeover (handoff)—while respecting channel outbound rules across Facebook Messenger, Instagram DM, WhatsApp Cloud API, Telegram, Zalo OA, Zalo Personal, Email, and Twilio SMS (with Twilio carrier fees billed separately). Website Chat is supported in the shared inbox and human handoff flow, not for automated follow-up sequences.

From a budgeting standpoint on TrolyPage's USD plans (listed VAT-inclusive), teams can test the workflow on a one-time time-limited Free trial ($0/mo, 100 MAU, 3 service connections, 50,000 AI tokens) before moving to Lite ($8/mo, 250 MAU, 4M tokens), Starter ($16/mo, 500 MAU, 16M tokens), Pro ($32/mo, 1,600 MAU, 40M tokens + TrolyMail), or Scale ($104/mo, 10,000 MAU, 200M tokens + TrolyMail), with extra human seats priced at $1/mo each.

At the same time, technical buyers should account for five documented TrolyPage boundaries before committing an architecture:

  • No automated Follow-up sequences on Website Chat: While Website Chat runs in TrolyPage's shared inbox with AI replies and human handoff, TrolyPage's Follow-up module does not support Website Chat because browser sessions are ephemeral rather than persistent messaging handles.
  • No visual drag-and-drop chatbot flowchart builder: TrolyPage orchestrates automation through AI knowledge/instructions and trigger-condition-action rules rather than node-and-wire conversation trees. If your team insists on drawing branching flowcharts by hand, you will miss a visual canvas.
  • No native two-way Shopify, WooCommerce, or BigCommerce order/refund sync: TrolyPage includes a built-in catalog and order flow, and its Website Chat widget embeds on Shopify or WooCommerce. However, if your buyers check out on an external storefront cart, TrolyPage does not natively pull Shopify refunds or fulfillment state back into the inbox—you must send external order-paid events via inbound webhooks or Zapier Webhooks so the PAID_OR_ORDERED stop signal fires reliably.
  • No storefront abandoned-cart capture campaigns: TrolyPage's follow-up engine operates on chat-initiated conversations within channel messaging windows, not anonymous website checkout-abandonment pixels.
  • Support hours vs. automation uptime: Automated AI replies and auto-stop state evaluations run 24/7, but live TrolyPage staff support operates during Vietnam business hours (UTC+7).

Pre-Launch Verification Checklist for Engineering & RevOps Teams

Before enabling any AI follow-up sequence in production, run these six deterministic failure-injection tests against a staging page or test phone number:

  1. Mid-delay reply race test: Enroll a test contact with a 60-second delay, send an inbound reply at T+45s, and verify the worker logs STOPPED_REPLIED with zero outbound API calls at T+60s.
  2. External payment webhook test: Trigger your storefront's order.paid webhook before the scheduled step fires and verify both the enrollment table and pending job queue clear immediately—especially when the buyer's email matches a different channel thread than their Messenger PSID.
  3. Conversational opt-out tripwire test: Send "Thanks, please stop messaging me about this" (without a standalone STOP) and confirm Tier 2 sets global contact suppression and logs a compliance audit record.
  4. Twilio 21610 & Advanced Opt-Out sync test: Reply STOP to your Twilio sender, confirm OptOutType=STOP sets your internal suppression flag, and verify subsequent sequence steps abort locally before hitting Twilio's API.
  5. Human takeover lock test: Have a rep send a manual reply or invoke handoff, then verify queued follow-ups transition to PAUSED_HUMAN and remain paused until explicit ticket resolution.
  6. 24-hour window expiry test: Set window_expires_at to one minute in the past on a Messenger and WhatsApp test thread; confirm Messenger aborts with EXPIRED_WINDOW and WhatsApp blocks free-form copy unless switched to an approved Message Template.

Comments

Your comment will appear after review.

Sign in to comment

No comments to show.