# AI Ad Review — Setup & Operations

Autonomous AI review of seller ads using **Gemini as the primary AI**. Ads are
approved, rejected, or flagged after a human-like **5-10 minute** delay.

## How it works
1. A seller submits an ad → `Product` is created as `PENDING` and an `AdAiReview`
   job is queued with a randomized `reviewAfter` (5-10 min).
2. An external cron hits `GET /api/cron/ai-ad-review?secret=CRON_SECRET` every 1-2 minutes.
3. The worker claims due jobs, runs the Gemini review (rubric from the Post Ad Tips
   plus advanced safety rules), and applies a **deterministic** policy:
   - **APPROVE** — the AI decides APPROVE, no MEDIUM+ violations were found,
     images were verified, and confidence ≥ 90.
   - **REJECT** — a clear-cut HIGH-severity violation (prohibited item,
     contact/payment leakage, scam, counterfeit, etc.) at confidence ≥ 95.
   - **FLAG** — anything uncertain or unverifiable. The ad stays `PENDING` and
     appears in the admin **AI Review** tab for a human to resolve.
4. On APPROVE/REJECT the seller is notified (in-app + email). On FLAG the seller
   is not notified; the ad simply shows "Under AI review".
5. If an admin resolves the ad **manually** from the **Pending** tab (approve or
   reject), the matching **AI Review** entry is updated to the same outcome
   automatically — it disappears from the AI Review list and the worker will not
   re-review an already-decided ad. (Resolving from the AI Review tab itself
   already updates both.)

**Ad Boost is never touched by the AI.** The worker only ever writes `status`
and `rejectionReason`.

## Environment variables
| Variable | Default | Purpose |
|---|---|---|
| `AI_AD_REVIEW_ENABLED` | `true` | Kill switch for the worker. |
| `AI_AD_REVIEW_MODE` | `auto` | `observe` = record decisions but flag everything for a human. `auto` = apply decisions. |
| `AI_AD_REVIEW_DELAY_MIN` | `5` | Minimum review delay (minutes). |
| `AI_AD_REVIEW_DELAY_MAX` | `10` | Maximum review delay (minutes). |
| `AI_AD_REVIEW_APPROVE_CONFIDENCE` | `90` | Min confidence to auto-approve. |
| `AI_AD_REVIEW_REJECT_CONFIDENCE` | `95` | Min confidence to auto-reject. |
| `AI_AD_REVIEW_BATCH_SIZE` | `2` | Jobs processed per cron run. |
| `AI_AD_REVIEW_MAX_ATTEMPTS` | `3` | Retries before failing to FLAG. |
| `AI_AD_REVIEW_MODEL` | `gemini-2.5-flash` | Gemini model. |
| `AI_AD_REVIEW_FALLBACK_MODEL` | `openai/gpt-oss-120b` | Groq model for the text-only fallback. Must be a model your Groq account can access. |
| `AI_AD_REVIEW_VISION_FALLBACK_MODELS` | `google/gemma-4-26b-a4b-it:free,nvidia/nemotron-3.5-super-vl:free,nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free,dots-studio/dots-3-note-preview:free` | Comma-separated OpenRouter **free vision** models, tried in order. They CAN see images, so they may auto-approve a clean ad. |
| `AI_AD_REVIEW_MAX_IMAGES` | `4` | Images sent to Gemini per ad. |
| `AI_AD_REVIEW_PACING_MS` | `4000` | Delay between reviews in a batch. |
| `AI_AD_REVIEW_VERIFY_VIDEO` | `false` | When `false`, any ad with a video link is flagged for human verification. When `true`, Gemini attempts to watch/verify the video (uses more tokens). |

> **Platform watermark:** every uploaded image is stamped with "Posted on Affiliate+"
> and the seller's name. The rubric explicitly tells the AI this is expected and must
> never be treated as a violation.

> **Video links:** by default any ad with a video link is flagged for human
> verification (the AI cannot reliably watch a video). Set
> `AI_AD_REVIEW_VERIFY_VIDEO=true` to let Gemini attempt to watch/verify it.

> **Digital download links:** for DIGITAL products the download link must be from an
> approved platform (Google Drive, Google Docs, WPS, Microsoft OneDrive/SharePoint,
> Dropbox, Mega, MediaFire, WeTransfer, Box, iCloud, pCloud, Sync, GoFile). Storefront
> links (selar.com, amazon.com, gumroad.com, etc.) are flagged. The worker also fetches
> the link to confirm it is publicly accessible without a login; if it is not, the ad
> is flagged for human review.

> **Description quality:** a short but clear description is acceptable and is NOT a
> violation. However, unreadable gibberish/placeholder text (e.g. "kiuusnvnpoeusgisvmkmskj")
> is detected deterministically and treated as a hard violation, and descriptions that
> are unrelated to the product are flagged.

> **Free-tier note:** the defaults (batch 2, pacing 4s, 5-10 min delay) keep the
> worker well under Gemini free-tier limits (roughly 10 requests/min). If you
> process a very high volume of ads, watch the daily request cap and raise the
> delay window or lower the batch size if needed.

> **Gemini RPD cap / "everything is being flagged":** when Gemini's daily free
> request cap is reached, the worker falls back in this order. Only the last one
> is image-blind and therefore unable to approve:
> 1. **Gemini** (primary, vision).
> 2. **OpenRouter free vision models** (`AI_AD_REVIEW_VISION_FALLBACK_MODELS`) —
>    these CAN see images, so they can still approve a clean ad. This is the
>    preferred fallback when Gemini is rate-limited but you don't want to add billing.
> 3. **Groq / OpenRouter text-only** (`AI_AD_REVIEW_FALLBACK_MODEL`) — image-blind;
>    can only reject or flag, never approve.

Requires `GEMINI_API_KEY` (primary). `OPENROUTER_API_KEY` enables the free vision
fallback above. `GROQ_API_KEY` / `OPENROUTER_API_KEY` also provide the text-only
last-resort fallback — a text-only result can never auto-approve an ad.

> **Finding working free vision models:** run
> `npx ts-node --project tsconfig.scripts.json -r ./scripts/register-alias.js scripts/test-openrouter-vision.ts`
> to list OpenRouter's free vision-capable models and probe each with a live image.
> Use the verified IDs in `AI_AD_REVIEW_VISION_FALLBACK_MODELS`.

## One-time setup
```bash
# 1. Create the AdAiReview table (this project is schema-first, no migrations folder)
npx prisma generate
npx prisma db push

# 2. (Optional) Queue existing PENDING ads for review
npm run backfill:ai-reviews

# 3. Run the tests
npm run test:ai-review
```

> The npm scripts use `tsconfig.scripts.json` and `scripts/register-alias.js`, so
> they work on Windows, macOS, and Linux without any shell-quoting issues.
> (The raw `npx ts-node --compiler-options '...'` form fails on Windows `cmd`.)

## Cron schedule
Add a cron entry (server crontab or an external service like cron-job.org) that
calls the worker every 1-2 minutes:

```cron
* * * * * curl -s "https://affiliateplus.ng/api/cron/ai-ad-review?secret=YOUR_CRON_SECRET" > /dev/null 2>&1
```

> **cron-job.org:** a 1-minute interval is supported. Its free plan has a ~30s
> request timeout, so pair a 1-minute schedule with `AI_AD_REVIEW_BATCH_SIZE=1`
> to keep each run short. A 2-5 minute interval also works fine — the 5-10 minute
> review delay means ads are never reviewed faster than that anyway.

## Rollout
1. Deploy with `AI_AD_REVIEW_MODE=observe`. The AI reviews every ad but only
   flags them; nothing is auto-approved/rejected. Watch the **AI Review** tab.
2. Once decisions look correct, set `AI_AD_REVIEW_MODE=auto` and restart PM2.
3. Use `AI_AD_REVIEW_ENABLED=false` to pause the worker at any time.

## Troubleshooting
- **Gemini returns 403 `CONSUMER_SUSPENDED`** — the Google Cloud project behind
  `GEMINI_API_KEY` has been suspended. Reinstate the project or issue a new key.
  Until then, Gemini cannot review ads and the worker will fall back / flag.
- **Groq returns 404 `model_not_found`** — the configured
  `AI_AD_REVIEW_FALLBACK_MODEL` is not available on your Groq account. Set it to a
  model you can access.
- **Everything is being flagged** — expected if providers are unavailable, or while
  `AI_AD_REVIEW_MODE=observe`. In `auto` mode, verify the worker is receiving your
  `GEMINI_API_KEY`, `OPENROUTER_API_KEY`, and `GROQ_API_KEY` (see
  [`ecosystem.config.js`](ecosystem.config.js)) and then check the worker response.
- **Stale FLAGGED entries after manual review** — if ads were approved/rejected
  from the Pending tab before the sync fix, their AI Review rows may still show as
  FLAGGED. Preview with `npm run backfill:ai-review-flags -- --dry-run`, then run
  `npm run backfill:ai-review-flags` to sync them to their product status (and
  re-enqueue any still-PENDING ones for a fresh review). Use `--sync-only` or
  `--requeue-only` to restrict the action.
- **A job is stuck** — the worker auto-recovers `IN_PROGRESS` jobs older than 10
  minutes back to `ERROR` on the next run.
