# Sentifix — Agent Integration Guide

Sentifix is an AI-powered UX signal intelligence platform. It ingests raw user behavior events from your application, clusters them into actionable signals, and provides AI-generated assessments with severity ratings and fix recommendations.

## Authentication

Every Sentifix project has a unique **project key** (prefixed `sfx_`). This is a write-only key safe for client-side use — it can only send events and cannot read data or access account settings. Pass it in the request body.

An **active subscription** (Builder, Scale, or Enterprise) is required to ingest events.

## Ingest Endpoint

```
POST https://juqwvnoehaymrchieyof.supabase.co/functions/v1/ingest-event
Content-Type: application/json
```

### Request Body

| Field              | Type     | Required | Description                                      |
|--------------------|----------|----------|--------------------------------------------------|
| `api_key`          | string   | Yes      | Project API key (`sfx_` prefix)                  |
| `type`             | string   | No*      | Event type (single-event mode)                   |
| `events`           | array    | No*      | Array of event objects (batch mode, max 50)       |
| `payload`          | object   | No       | Arbitrary metadata about the event                |
| `session_id`       | string   | No       | Session identifier for grouping events            |
| `user_fingerprint` | string   | No       | Anonymous user identifier                         |
| `idempotency_key`  | string   | No       | Unique key to prevent duplicate ingestion         |
| `context`          | object   | No       | Client-side context (see below)                   |

\* Provide either `type` (single event) or `events` (batch). Not both.

### Event Object (batch mode)

Each object in the `events` array accepts:

| Field              | Type   | Required | Description                        |
|--------------------|--------|----------|------------------------------------|
| `type`             | string | Yes      | Event type                         |
| `payload`          | object | No       | Arbitrary metadata                 |
| `session_id`       | string | No       | Session identifier                 |
| `user_fingerprint` | string | No       | Anonymous user identifier          |
| `idempotency_key`  | string | No       | Unique key to prevent duplicates   |

### Context Object

Optional client-side context merged into the payload under `_context`:

| Field        | Type   | Description                    |
|--------------|--------|--------------------------------|
| `page_url`   | string | URL where the event occurred   |
| `user_agent` | string | Browser/OS user-agent string   |
| `viewport`   | object | `{ width, height }` in pixels  |
| `locale`     | string | `navigator.language` value     |
| `referrer`   | string | `document.referrer` value      |
| `timestamp`  | string | Client-side ISO 8601 timestamp |

### Valid Event Types

- `error` — JavaScript errors, unhandled exceptions
- `crash` — Application crashes, white screens
- `rage_click` — Repeated rapid clicks on the same element
- `dead_end` — User reaches a point with no obvious next action
- `workaround` — User takes an unusual path to accomplish a task
- `feature_pattern` — Repeated behavior suggesting a missing feature
- `performance` — Slow loads, long tasks, layout shifts

### Example — Single Event

```bash
curl -X POST https://juqwvnoehaymrchieyof.supabase.co/functions/v1/ingest-event \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "sfx_your_project_key",
    "type": "rage_click",
    "payload": {
      "element": "#export-btn",
      "click_count": 7,
      "page": "/dashboard"
    },
    "session_id": "sess_abc123",
    "user_fingerprint": "fp_xyz789",
    "idempotency_key": "evt_unique_123",
    "context": {
      "page_url": "https://app.example.com/dashboard",
      "user_agent": "Mozilla/5.0 ...",
      "viewport": { "width": 1440, "height": 900 },
      "locale": "en-US"
    }
  }'
```

### Example — Batch

```bash
curl -X POST https://juqwvnoehaymrchieyof.supabase.co/functions/v1/ingest-event \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "sfx_your_project_key",
    "events": [
      { "type": "error", "payload": { "message": "TypeError" }, "idempotency_key": "e1" },
      { "type": "rage_click", "payload": { "element": "#save" }, "idempotency_key": "e2" }
    ],
    "context": {
      "page_url": "https://app.example.com/settings",
      "locale": "en-US"
    }
  }'
```

### Response — Single Event

**201 Created**
```json
{ "success": true, "event_id": "uuid", "status": "created" }
```

### Response — Batch

**201 Created**
```json
{
  "success": true,
  "events": [
    { "event_id": "uuid1", "status": "created" },
    { "event_id": "uuid2", "status": "duplicate" }
  ]
}
```

### Idempotency

When an `idempotency_key` is provided, the endpoint checks for an existing event with the same key in the same project. If found, it returns the existing `event_id` with `"status": "duplicate"` instead of inserting a new row. This makes retries safe.

### Error Responses

**400 Bad Request** — Missing fields, invalid type, or batch too large
**401 Unauthorized** — Invalid API key
**403 Forbidden** — No active subscription
**429 Too Many Requests** — Rate limit exceeded

### Rate Limits

| Plan       | Events per minute |
|------------|-------------------|
| Builder    | 2,000             |
| Scale      | 10,000            |
| Enterprise | 25,000            |

## Signal Schema

Events are automatically clustered into **signals** with:

- `type`: `issue` or `opportunity`
- `category`: Same as event types above
- `severity`: `low`, `medium`, or `high`
- `title`: Human-readable summary
- `description`: Detailed explanation
- `frequency`: Number of occurrences
- `claude_assessment`: AI-generated analysis including:
  - Root cause analysis
  - Impact assessment
  - Recommended fix
  - Priority rating

## Pricing

- **Builder** — $19/mo, 3 projects, 2k events/min
- **Scale** — $39/mo, 10 projects, 10k events/min
- **Enterprise** — Custom pricing, unlimited projects, 25k events/min

## Smart AI Routing

Sentifix tiers your BYOK calls across three model classes to minimize cost without losing quality:

| Tier       | Models                                    | Used for                              |
|------------|-------------------------------------------|---------------------------------------|
| Triage     | Haiku 4, GPT-5 nano         | Classification, dedupe, severity      |
| Analysis   | Sonnet 4.5, GPT-5                         | Root cause, repro steps, fix suggestion |
| Escalation | Opus 4, GPT-5 Pro                         | Hard cases where triage confidence is low |

Routing modes (set per project in Settings): `cost-optimized` (default), `balanced`, `quality-first`. Typical spend reduction is around 60% vs always-frontier.
