# Trigger System

Triggers define **when** an agent activates in a conversation. Each trigger watches for a
specific event (a keyword, any DM, an ad referral, etc.) and routes the conversation to the
configured agent.

---

## Trigger Types

### 1. DM_KEYWORD
Activates when an inbound DM contains a specific keyword.

- **When to use:** Campaigns ("reply PROMO to learn more"), opt-in flows, specific product inquiries.
- **Config:** `keyword` field on the trigger row.

#### Match Mode
Controls how the keyword is searched within the user's message:

| Option | Behavior |
|---|---|
| **Anywhere in message** | Activates if the keyword appears anywhere in the message (e.g. "I want the PROMO deal" matches `PROMO`) |
| **Exact match only** | Activates only if the user's message is exactly the keyword, nothing more |

#### Allow Typos
When enabled, the trigger matches even with small spelling mistakes.

> Example: `"prise"` matches `"price"`

Disable this if you need strict, exact spelling (e.g. promo codes, command words).

### 2. ALL_DM
Activates for every inbound direct message — no keyword needed.

- **When to use:** Catch-all agent that handles every new DM.
- **Note:** Usually paired with other triggers as a fallback. Only one ALL_DM trigger should be active per agent.

### 3. COMMENT_KEYWORD
Activates when a user comments on a post with a matching keyword.

- **When to use:** "Comment INFO to get the guide" call-to-action on Instagram posts.
- **Flow:** Detected comment → agent sends a DM to the commenter.
- **Config:** `keyword` field.

#### Match Mode
Same options as DM_KEYWORD — **Anywhere in comment** or **Exact match only**.

#### Allow Typos
Same behavior as DM_KEYWORD — matches with small spelling mistakes when enabled.

### 4. ALL_COMMENTS
Activates for every comment on any post.

- **When to use:** When you want the agent to respond to all comments (rare — high volume).

### 5. STORY_REPLY
Activates when a user replies to an Instagram story.

- **When to use:** Story CTAs ("reply to this story to get the link"), lead capture from stories.
- **Flow:** Story reply → opens DM conversation → agent activates.

### 6. AD_REFERRAL
Activates when a user sends a DM that originated from clicking a Meta ad (Click-to-DM).

- **When to use:** Paid traffic campaigns. The agent knows which ad triggered the conversation.
- **Config:** `adId` field — the Meta ad identifier.
- **Available metadata:** Ad title, photo, video, post ID, product ID, flow ID are stored on the message for context.

### 7. INSTAGRAM_HISTORY
Activates based on Instagram story history replies (used for archival/re-engagement flows).

### 8. FILE_ROUTING
Routes a conversation to a specific agent based on the contact's identifier.

- **When to use:** Importing a list of contacts and pre-routing each one to a specific agent.
- **Config:** Match fields — Instagram username, WhatsApp number, email, Facebook name, or TikTok handle.
- **How it works:** When a matching contact starts a conversation, it's automatically routed to the designated agent.

---

## Negative Configs (Blocklist)

Every trigger supports a **negative config** — a blocklist that prevents the trigger from
activating for specific contacts or conditions.

| Config field | Description |
|-------------|-------------|
| Expiry DateTime | After this date/time, the blocklist entry is ignored |
| User timezone | Used to evaluate the expiry in the contact's local time |
| Activation timestamp | When the block was applied |

**How to add:** Via the platform UI on the trigger's settings, or via SQL INSERT into
`trigger_negative_configs`.

**Never DELETE trigger or negative_config rows.** Deactivate via platform UI or set an
expiry date in the past.

---

## Activation Evaluation

Every time a message is received, the system evaluates whether to activate an agent.
The result is stored in `agent_activation_evaluations`:

| Field | Description |
|-------|-------------|
| `activated` | Whether the agent was activated for this message |
| `confidence` | Confidence score of the activation decision |
| `reasoning` | Snapshot of why the agent was (or wasn't) activated |
| `cost` | Token cost of the evaluation |

**Useful for debugging:** If an agent isn't responding when it should, query
`agent_activation_evaluations` to see why it was skipped.

```sql
SELECT activated, confidence, reasoning, created_at
FROM agent_activation_evaluations
WHERE conversation_id = '<uuid>'
ORDER BY created_at DESC
LIMIT 10
```

---

## Trigger Priority & Conflicts

When multiple triggers match the same inbound message, the most specific wins:
1. FILE_ROUTING (exact contact match)
2. AD_REFERRAL (specific ad ID)
3. DM_KEYWORD / COMMENT_KEYWORD (specific keyword)
4. STORY_REPLY (story context)
5. ALL_DM / ALL_COMMENTS (catch-all)

If two triggers of the same specificity match, the platform routes to the first one in
creation order.

---

## Common Patterns

### Keyword + Catch-all
```
Agent A: DM_KEYWORD "PROMO"   ← handles promo-specific flow
Agent B: ALL_DM               ← handles everything else
```

### Story → DM pipeline
```
Agent: STORY_REPLY            ← activates on story reply
       ↓
       DM conversation started automatically
       Agent runs its qualification flow
```

### Ad attribution
```
Meta Ad → Click-to-DM → AD_REFERRAL trigger
Agent knows: which ad brought the lead, ad title, media
```
