# Webhooks and jobs

Source: https://docs.askaniela.com/guide/webhooks/

Use jobs for lists larger than the synchronous batch (`POST /v1/judge/batch`, up to 10 pages). A job runs
in a background worker; you poll its status or receive a signed webhook when it finishes. Reports are stored
in the job's project and are available through `GET /v1/reports/{id}`.

API keys need the `jobs` scope. Jobs are project-scoped: a job from another project returns `404 job_not_found`.

## Create a job

```bash
curl -X POST https://api.askaniela.com/v1/jobs \
  -H "Authorization: Bearer gsj_..." -H "Content-Type: application/json" \
  -d '{"items": [{"url": "https://example.com/"}, {"text": "Pasted page text"}],
       "rules": ["SP-KWS-REPEAT", "QR-INCOHERENT"],
       "webhook_url": "https://example.org/hooks/gsj"}'
```

Body: `items` (each `url`, `html` or `text`; up to 1000), optional `rules`,
`explain`, `webhook_url`, `project_id` (or the `X-Project-ID` header; an API key uses its project).
Response `202 {"job_id": "job_…", "status": "queued"}`.

Limits: `html`/`text` up to 2,000,000 characters per item and 20,000,000 per job (`413 item_too_large`); active
jobs and site audits are limited per organization and per project, see [Active jobs limit](#active-jobs-limit). A job has a time limit that grows with the number of pages, pauses not counted. When it is reached and
more than half of the pages were checked, the job ends as `done` with `partial` set; otherwise as `failed` (`error`
says it timed out). A job that checks no page for 30 minutes ends as `failed` (`error`: "No progress for 30 min…").
In every case only pages with a report are charged and the webhook is still sent. Rules disabled in
the catalog are rejected up front (`400 rule_disabled`).

### Active jobs limit

A job (`POST /v1/jobs`) or site audit (`POST /v1/audits/site`, `POST /v1/audits/{id}/start`) is active while it is
`queued`, `running`, `pausing`, `paused` or `cancelling`. Two limits apply at the same time:

| Limit | Default | Counts |
|---|---|---|
| per organization | 2 | active jobs and site audits of all projects of the organization |
| per project | 5 | active jobs and site audits of one project |

With the default values the organization limit is reached first. A new job or audit over either limit gets
`429 too_many_active_jobs` with `Retry-After: 30`; wait for one to finish. Paused jobs keep their place. The current
values are on the **Limits** page of the developer panel. Draft audits (`start: false`) are not active and do not count.

`webhook_url` must be `https` with a public host name: IP literals, `localhost`, internal names and URLs with
credentials are rejected (`400 invalid_webhook_url`). At delivery time the host is resolved again and every
address must be public; the request goes to the checked address, without following redirects.

## Poll the status

`GET /v1/jobs/{job_id}`:

| Field | Meaning |
|---|---|
| `status` | one of 8 states, see [Job statuses](#job-statuses) |
| `done` / `total` | items processed so far (with or without error) |
| `failed` | items that ended with an error; `errors[]` = `{index, error}` |
| `report_ids` | public ids of stored reports (`rep_…`) in item order (fetch with `GET /v1/reports/{id}`) |
| `webhook_status` | HTTP status returned by your webhook (0 = not reached, `null` = not sent yet) |
| `paused_at`, `refund_usd` | start of the current pause; estimate returned to the balance if you cancel now |
| `partial` | `{checked, total, reason}` when the job ended early with a partial result (`status: done`; `reason: timeout` = job time limit, `reason: stall` = no finished evaluation call for the stall window); `null` otherwise. `error` stays `null` |

### Job statuses

| `status` | Final | Meaning |
|---|---|---|
| `queued` | no | accepted, waiting for a worker |
| `running` | no | pages are being fetched and judged |
| `pausing` | no | pause requested; pages in progress finish, new ones do not start |
| `paused` | no | stopped for now; `POST /v1/jobs/{id}/resume` puts it back in the queue |
| `cancelling` | no | cancel requested while running; pages in progress finish, then the job is settled |
| `done` | yes | every item was processed; some may still have failed (`failed > 0`). With `partial` set: the time limit was reached after more than half of the pages (by default), the remaining items were not processed and not charged |
| `failed` | yes | every item failed, the job crashed, made no progress for 30 minutes, or reached its time limit with half of the pages or fewer (`error`) |
| `cancelled` | yes | stopped for good; judged pages keep their reports, pages not judged go back to the balance |

Transitions: `queued` → `running` → `done` or `failed`; `POST /v1/jobs/{id}/pause` moves `queued` → `paused` or
`running` → `pausing` → `paused`; `resume` moves `paused` → `queued`; `POST /v1/jobs/{id}/cancel` moves `queued` or
`paused` → `cancelled`, or `running`/`pausing` → `cancelling` → `cancelled`. A finished job returns
`409 job_not_controllable`. Paused jobs still count towards the [active jobs limit](#active-jobs-limit). Poll until the
status is final (`done`, `failed` or `cancelled`). `GET /v1/jobs/{job_id}/results` lists `{index, report_id, error, url}`;
`GET /v1/jobs` lists recent jobs of your projects. Errors and results carry the item `url` (when given).

## Webhook

When a job reaches a final status (`done`, `failed` or `cancelled`), the server sends one `POST webhook_url` with
event `job.finished`. The per-job `webhook_url` means "the pages are assessed": parts computed after them (for
example a fix plan ordered with the job) may still be running, so check `completeness` in `GET /v1/audits/{id}` before
reading them (see [When the audit is ready](https://docs.askaniela.com/guide/site-audits.md#when-the-audit-is-ready)). Organization webhooks wait for
those parts, see [When the event is sent](#when-the-event-is-sent). `job` is the same object as `GET /v1/jobs/{id}`, without `progress`. `kind` is `job` here;
`id` and `audit` are filled only in [organization webhooks](https://docs.askaniela.com/guide/developer-portal.md#organization-webhooks), which also
receive `job.paused`, `job.resumed` and `job.cancelled`, and which are the only webhooks for site audits
(`POST /v1/audits/site`) - see [Site audits in webhooks](#site-audits-in-webhooks). Example body:

```json
{
  "event": "job.finished",
  "kind": "job",
  "job": {
    "id": "job_3m2k7q9x4w1p8r5t",
    "project_id": "prj_8d4n2v6c1x9b3z7q",
    "created_by": null,
    "status": "done",
    "total": 2,
    "done": 2,
    "failed": 0,
    "report_ids": ["rep_5h2j8k4m1n7p3q9r", "rep_6t3w9y2u5i8o1p4a"],
    "errors": [],
    "error": null,
    "webhook_status": null,
    "created_at": "2026-10-20T19:46:57.599129Z",
    "started_at": "2026-10-20T19:46:57.754792Z",
    "finished_at": "2026-10-20T19:47:34.565301Z",
    "progress": null,
    "paused_at": null,
    "refund_usd": null
  },
  "audit": null,
  "id": null
}
```

Headers:

| Header | Value |
|---|---|
| `X-GSPAMJUDGE-Event` | `job.finished` |
| `X-GSPAMJUDGE-Delivery` | delivery id, the same for all retries of one delivery |
| `X-GSPAMJUDGE-Timestamp` | Unix time in seconds (new on each retry) |
| `X-GSPAMJUDGE-Signature` | `sha256=` + hex HMAC-SHA256 of `timestamp + "." + raw body` with the webhook secret |

Receivers must:

1. verify the signature against the **raw** body and compare in constant time;
2. reject the request when `|now - timestamp| > 300` seconds (replay protection);
3. deduplicate by `X-GSPAMJUDGE-Delivery` - a retry after a lost response arrives with the same id.

Delivery is **at least once**. For the per-job `webhook_url` the delivery id (also the body `id`) is fixed per job
(`<job id>:job.finished`): if our worker restarts during delivery, the webhook is sent again later with the same id.

```python
import hashlib, hmac, time

def valid(secret: bytes, timestamp: str, body: bytes, signature: str) -> bool:
    expected = "sha256=" + hmac.new(secret, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
    return abs(time.time() - int(timestamp)) <= 300 and hmac.compare_digest(expected, signature)
```

Return any `2xx` quickly. Other responses and network errors are retried 3 times with backoff (1, 2, 4 s).
The per-job `webhook_url` is signed with a server secret that is not shown to customers (when signing is
unavailable, requests with `webhook_url` are rejected with `503 webhooks_unavailable`). To verify signatures, use an
[organization webhook](https://docs.askaniela.com/guide/developer-portal.md#organization-webhooks): its signing secret (`whsec_…`) is on the endpoint
page. A per-project secret for `webhook_url` is planned.

## Site audits in webhooks

A site audit (`POST /v1/audits/site`) runs as a job, so it ends with the same `job.finished` event. There is no
per-audit `webhook_url`: register an [organization webhook](https://docs.askaniela.com/guide/developer-portal.md#organization-webhooks). Its body is
`{"event": "job.finished", "data": {…}}`, where `data` is the object above plus:

| Field | Meaning |
|---|---|
| `kind` | `site` for `POST /v1/audits/site`, `job` for `POST /v1/jobs` (also in `job.paused`, `job.resumed`, `job.cancelled`) |
| `audit.id`, `audit.kind`, `audit.title`, `audit.status` | audit id (`aud_…`), kind, site host, final status |
| `audit.pages`, `audit.hits` | pages with a report; pages with a confirmed spam finding |
| `audit.level`, `audit.quality_level`, `audit.helpful_level` | site levels: `high`, `medium`, `low` or `unknown` |
| `audit.policies` | spam policies with a confirmed finding |
| `audit.signals` | strongest signal per assessed kind: `{"spam": {"max_signal": 87, "level": "high"}, "quality": {…}, "helpful": {…}}`. `max_signal` is 0-100 (signal strength, not a percentage), `level` is `high`, `medium` or `low`. Only kinds checked in this audit appear |
| `audit.report_url` | the report in the app |
| `audit.api_url`, `audit.export_url`, `audit.csv_url`, `audit.pdf_url` | `GET /v1/audits/{id}` and its JSON, CSV and PDF exports (API key needed; exports answer `202` while the file is built) |
| `audit.completeness` | state of the parts computed after page assessment (summary, fix plan, categories, topicality, Visibility): `complete`, `incomplete` or `null` (no parts tracked) |
| `audit.missing` | parts without a result after all attempts, when `audit.completeness` is `incomplete` (e.g. `["visibility"]`) |

`audit` is `null` if the audit could not be read when the event was sent; find it in `GET /v1/audits` by `job_id`.

### When the event is sent

For an audit, `status: done` means that the pages are assessed; the summary, fix plan and add-ons are computed after
that (`completeness.state: finishing` in `GET /v1/audits/{id}`). The organization webhook `job.finished` waits for
them: it is sent once, when `completeness` becomes `complete` or `incomplete` (the same moment as the "audit ready"
e-mail), so the audit is ready to read when the event arrives. If a part needs a retry, the event can come minutes
after `status` turned `done`. An audit without such parts (`completeness: null`) sends the event right away.
`job.paused`, `job.resumed` and `job.cancelled` are not delayed.
Raw scores are never sent. The developer panel page **Webhooks** shows a full example and the signature check in Python
and JavaScript.
