<!--
__POLSIA_SLUG__
canonical: /docs/competitor-refresh
-->

# Competitor Refresh Reference

This is the implementation-checked reference for the biweekly competitor
refresh. It documents the behavior currently implemented by the refresh job,
shared discovery helpers, database module, and API routes. The markdown source
is served at `/docs/competitor-refresh`.

## Feature boundary and source of truth

The refresh discovers and compares competitors for monitored brand profiles. It
does not accept a caller-supplied brand, engine list, candidate count, or
business payload. The implementation sources are:

| Concern | Source of truth |
| --- | --- |
| HTTP trigger and report/changelog reads | `routes/competitor-refresh.js` |
| Scheduled orchestration, diffs, alerts, and retry behavior | `jobs/competitor-refresh.js` |
| Prompts, parsing, normalization, aggregation, and snapshots | `lib/competitor-discovery.js` |
| Brand selection, report persistence, counts, idempotency, and changelog reads | `db/competitor-refresh.js` |
| Report and changelog tables/constraints | `migrations/1797100000000_competitor_refresh.js` and `migrations/1821300000000_competitor_refresh_hardening.js` |
| Schedule | `polsia.toml` |

The documentation route is read-only and serves this file; it does not access
PostgreSQL, call AI, or require admin credentials.

## Refresh inputs

### Caller-supplied trigger input

For `POST /api/competitor-refresh/trigger`, the only supported caller-supplied
input is the cron secret in either `x-cron-secret` or
`Authorization: Bearer <secret>`. The route does not read business options from
the request body or query string. Callers cannot select a brand, engines, or
candidate count. A valid request starts the full refresh with `force: true`,
which bypasses the scheduled odd-week check.

### Brands included

The job reads `brand_profiles` where `monitoring_enabled = true` and at least
one row exists in `competitors` for that brand. For each selected profile it
uses the stored brand ID, name, domain, and category. The database query also
resolves an owner contact for possible alert email delivery. If the stored
category is empty, the discovery prompt uses `your industry` as its fallback.

For each brand, the job reads all current competitor rows, including archived
rows, and the most recent prior completed report from an earlier `week_of`.
Current rows are used to calculate additions, removals, and reactivations; the
prior report's `engine_snapshot` is the baseline for position and share changes.
The refresh operates on every selected brand rather than a caller-selected
brand.

### Discovery and engine checks

For each selected brand, the implementation makes one shared discovery call
using the question:

> What brands does a buyer consider alongside `[BRAND]` when researching `[CATEGORY]`?

The prompt asks for up to 10 direct competitor candidates, each with a brand
`name` and primary `domain`. Candidates are normalized and the brand's own
domain is excluded.

The implementation then checks exactly these four engines:

`chatgpt`, `claude`, `perplexity`, and `gemini`.

Each engine prompt asks for up to three competitor candidates in answer order,
with `name`, primary `domain`, and an optional position supplied by the model.
Engine positions are normalized to integers from 1 through 3; when a valid
position is absent, the candidate's answer order supplies the position.

All discovery and engine candidates are deduplicated by normalized domain.
The first candidate retained for a domain supplies its name and optional
category; discovery candidates are considered before engine candidates.
Normalization lowercases the value, strips `http://` or `https://`, leading
`www`, paths, queries, fragments, trailing dots, and URL-parser ports. The own
brand is excluded after this normalization.

### Schedule and manual trigger

`polsia.toml` runs `node jobs/competitor-refresh.js` every Monday at 07:00 UTC.
The scheduled job is biweekly in practice: it skips even ISO weeks and runs on
odd ISO weeks. The authenticated on-demand trigger described above forces a
run in either week.

## HTTP contract

### Trigger

`POST /api/competitor-refresh/trigger`

Authentication is required with either:

- `x-cron-secret: <NURTURE_CRON_SECRET>`; or
- `Authorization: Bearer <NURTURE_CRON_SECRET>`.

The response is a newline-delimited stream with `Content-Type:
application/json`. It writes a `running` object first, then a `done` object if
the job resolves, or an `error` object if the job throws:

```json
{"status":"running","msg":"Competitor refresh started"}
{"status":"done","msg":"Competitor refresh complete"}
```

The error object has the supported shape
`{"status":"error","msg":"..."}`. A missing configured secret returns
503; a missing or incorrect secret returns 401.

### Report and changelog reads

These endpoints require the configured `ADMIN_PASSWORD` or `ADMIN_TOKEN` using
either `?token=<value>` or `Authorization: Bearer <value>`:

| Method | Endpoint | Response |
| --- | --- | --- |
| GET | `/api/competitor-refresh/reports` | `{ "reports": [...] }` |
| GET | `/api/competitor-refresh/reports/:brandSlug` | `{ "brand_slug": "...", "report": {...}, "history": [...] }` |
| GET | `/api/competitor-refresh/changelog/:brandSlug` | `{ "brand_slug": "...", "entries": [...] }` |

Without a configured or matching admin token, these endpoints return 401. A
brand report with no matching report returns 404 with `error: "no reports"`
and the requested `brand_slug`.

## Report contract

Each item in `reports`, `report`, and `history` has exactly the following 22
serialized fields. Types below describe the JSON response; nullable database
values can remain `null`, except where the serializer supplies a fallback.

| Field | JSON type and meaning |
| --- | --- |
| `id` | UUID string; report identifier |
| `type`, `report_type` | Strings; both use the stored report type, or `competitor_refresh` when it is empty or null |
| `brand_id` | UUID string; profile identifier |
| `brand_name` | String or `null`; stored profile name |
| `brand_slug` | String; first label of the profile domain, lowercased |
| `domain` | String; stored profile domain |
| `week_of` | Date string (`YYYY-MM-DD`) or `null`; refresh week |
| `run_at` | Timestamp string or `null`; run time |
| `run_status` | String; currently `running`, `completed`, or `failed`; falls back to `completed` when empty or null |
| `competitors_total`, `competitors_active` | Integer or `null`; all competitor rows and rows with `status = 'active'`, respectively |
| `alert_triggered` | Boolean or `null`; whether the run met an alert condition |
| `alert_reason` | String or `null`; reason when an alert condition was met |
| `alert_sent_at` | Timestamp string or `null`; set after successful alert delivery |
| `needs_review` | Boolean; derived from the profile review flag, with null/falsy values serialized as `false` |
| `new_competitors` | Array of new competitor objects; see the diff shapes below |
| `removed_competitors` | Array of removed competitor objects; see the diff shapes below |
| `position_changes` | Array of per-engine position-change objects; see the diff shapes below |
| `share_changes` | Array of four-engine share-change objects; see the diff shapes below |
| `summary` | JSON object; completed-run summary, failed-run error, or an empty object |
| `engine_snapshot` | JSON object; discovery and four-engine results, or an empty object |

The four top-level diff arrays are distinct response fields from `summary`.
For each, the serializer uses the corresponding array in `summary` when it is
present and otherwise falls back to the stored report column; if neither is
available, it returns `[]`. A completed run's `summary` contains
`competitors_total` and those same four arrays:

```json
{
  "competitors_total": 3,
  "new_competitors": [{"name":"Rival","domain":"rival.example","source":"auto"}],
  "removed_competitors": [{"name":"Former Rival","domain":"former.example","reason":"no longer discovered"}],
  "position_changes": [{
    "competitor":"Rival",
    "domain":"rival.example",
    "old_avg_position":4,
    "new_avg_position":2,
    "engine":"chatgpt",
    "is_new_top3":true
  }],
  "share_changes": [{
    "competitor":"Rival",
    "domain":"rival.example",
    "old_share_pct":25,
    "new_share_pct":50
  }]
}
```

`new_competitors` entries emitted by the diff contain string `name`, string
`domain`, and `source: "auto"`. `removed_competitors` entries contain string
`name`, string `domain`, and `reason: "no longer discovered"`. Position
changes contain string `competitor`, string `domain`, numeric or null
`old_avg_position` and `new_avg_position`, an `engine` string from the fixed
four-engine set, and boolean `is_new_top3`. An average position is null when
that side has no observation. Share changes contain string `competitor`,
string `domain`, and numeric or null `old_share_pct` and `new_share_pct`;
percentages use the fixed four-engine share calculation, and `old_share_pct`
is null when there is no prior report snapshot.

If the run fails, `summary` instead has the shape `{ "error": "..." }`, where
`error` is a string, for example:

```json
{"error":"All competitor discovery AI checks failed"}
```

In that case the top-level diff arrays still appear and fall back to their
stored report columns, which are empty for a newly claimed failed report.

The engine snapshot has one discovery object and one object for each fixed
engine (`chatgpt`, `claude`, `perplexity`, and `gemini`). Each object contains
boolean `success`, a `competitors` array, and a string-or-null `error`:

```json
{
  "discovery": {
    "success": true,
    "competitors": [{"name":"Rival","domain":"rival.example"}],
    "error": null
  },
  "chatgpt": {
    "success": true,
    "competitors": [{"name":"Rival","domain":"rival.example","position":2}],
    "error": null
  },
  "claude": {"success": false,"competitors": [],"error":"timeout"},
  "perplexity": {"success": true,"competitors": [],"error": null},
  "gemini": {"success": true,"competitors": [],"error": null}
}
```

Snapshot candidates contain string `name` and normalized string `domain`;
engine candidates also contain integer `position` from 1 through 3. The parser
may preserve an optional non-empty `category` string supplied in a candidate
response. Failed calls retain an empty candidate list and an error value
rather than implying that no competitor was found. A run with no successful
discovery or engine call is stored as `failed`; with at least one success it
can complete while preserving individual failed calls in the snapshot.

The changelog endpoint returns persisted entries with these fields:
`id`, `brand_id`, `refresh_report_id`, `change_type`, `competitor_domain`,
`competitor_name`, `old_position`, `new_position`, `engine`, `trigger`,
`created_at`, `domain`, `report_type`, `type`, `week_of`, and `run_status`.
Refresh-generated entries use `trigger: "scheduled"`; position-change entries
use `promoted` or `demoted`, and add/remove entries use `added` or `removed`.

## Persistence and behavior

The refresh aggregates the shared discovery candidates and successful engine
mentions into one auto-competitor set keyed by normalized domain. It excludes
the own brand and preserves manual competitors, including manual rows that are
not present in the current AI results. Only active auto competitors that are no
longer discovered can be archived. An archived auto competitor seen again is
reactivated.

Archival is disabled if the shared discovery call fails or any of the four
engine calls fails. This prevents incomplete AI results from mass-archiving
auto competitors. If every discovery and engine call fails, the run is stored
with `run_status: "failed"` and its failure snapshot. A run with at least one
successful call can complete, with failed calls remaining explicit in the
snapshot and archival still disabled when the full set did not succeed.

The database claims one report per brand and `week_of`. A completed or fresh
running report is reused on a repeat attempt; failed reports and stale running
reports can be claimed again using the same row. The hardening migration adds
the unique `(brand_id, week_of)` index and retry-safe report/changelog fields.
Report writes, competitor/changelog writes, alert-delivery claims, successful
send timestamps, and release-on-send-failure behavior are persisted through
`db/competitor-refresh.js`.

## Alerts

An alert is triggered when either condition is true:

- at least two new competitors are found; or
- a position change marks a competitor's first entry into the top three.

When triggered, the brand is marked as needing review. If an owner email is
available, the job sends a plain-text and HTML competitor alert through the
email proxy. The message includes new competitors and first-time top-three
entries. Delivery is claimed in the database to prevent duplicate sends;
successful delivery records `alert_sent_at`, while a failed send releases the
claim for retry. No alert is sent when there is no owner email.

The stored `alert_reason` is `N new competitors discovered` for the new-
competitor threshold, or `<competitor> moved into top 3 for the first time` for
the first-time top-three condition.

The implementation does not guarantee AI completeness, ranking correctness,
alert delivery, or successful delivery by an external email service.

## Limits and unspecified behavior

- The overview returns at most 20 latest report rows, one latest row per brand.
- A brand report returns the latest report and at most 12 history rows.
- A changelog returns at most 50 events associated with completed runs (plus
  legacy entries without a linked report, where present).
- There is no documented pagination, filtering, arbitrary-brand refresh,
  engine-selection, candidate-count, or trigger-body option.
- The serialized report does not include raw model responses, evidence or
  citations, confidence scores, or caller-defined fields or options.
- `brand_slug` is derived from the first label of the stored domain, lowercased;
  it is not an independently stored brand identifier.
- Report counts include all competitor rows for the brand, while
  `competitors_active` counts only rows with `status = 'active'`.
- The implementation does not define AI completeness, ranking correctness,
  alert delivery, or a fixed report order beyond the implemented query
  ordering. The current ordering is newest week/run for reports and newest
  `created_at`/id for changelog entries.

No additional request inputs, report fields, pagination metadata, or behavioral
guarantees are specified by this feature.
