# Alert51 integration guide for AI agents

This guide is for coding agents and the developers who use them. It describes everything needed to add Alert51 monitoring to an existing scheduled job without reading the website. Raw file: https://alert51.com/ai-instructions.md. Human docs: https://alert51.com/docs. OpenAPI spec: https://api.alert51.com/v1/openapi.json.

## What Alert51 does

Alert51 watches scheduled jobs: cron jobs, backups, CI pipeline schedules, framework schedulers and timers. After each run the job sends one HTTP check-in with its result. Alert51 stores the job's cron schedule, computes when the next run must report, and opens an incident when:

- a run reports `"status": "failure"` (the incident opens at once), or
- no check-in arrives before the deadline: the next scheduled time plus the grace period (a missed run).

Monitoring starts with the first accepted check-in for a `project` and `job` pair. That request creates the project and the monitor; nothing has to be set up in the dashboard first, and nothing is watched before that request succeeds. Notifications go to the channels configured in the dashboard (email, Telegram, webhooks).

## Rules for agents

1. Inspect the existing job before changing anything: where it is scheduled (crontab, systemd timer, Kubernetes CronJob, CI schedule, an in-process scheduler), its exact schedule and time zone, how long it usually runs, and how it reports failure (exit code, exception, return value).
2. Make the smallest integration change: one check-in after the job's work finishes, in the code path that already knows the outcome. Do not refactor the job, rename it or change its schedule.
3. Never change the job's outcome. Keep its exit code and re-raise its original exception, even if the check-in request fails. Log reporting errors and continue.
4. Use a finite HTTP timeout of about 10 seconds for the check-in request.
5. Read the token from the `ALERT51_TOKEN` environment variable or the project's existing secret store. Never hard-code, commit, print or log a real token. Use placeholders such as `a51_xxxxxxxx_your-secret` in examples and add `ALERT51_TOKEN=` to `.env.example` if the project keeps one.
6. Use the HTTP client the project already has. Do not add a dependency just for Alert51.
7. Send the check-in after the work completes, not when it starts. Alert51 has no start signal.
8. Choose stable slugs: `project` for the environment or system (for example `production`), `job` for the task (for example `db-backup`). The same pair must be used on every run.

## Get an API token

1. Sign up at https://alert51.com/signup and verify the email address.
2. Open the dashboard page API tokens (https://alert51.com/app/tokens) and create a token. Name it after where it runs, for example `backup-server-1` or `gitlab-ci`.
3. Copy the secret. It is shown once and looks like `a51_xxxxxxxx_your-secret`.
4. Store it as `ALERT51_TOKEN` in the place where the job runs: a CI masked variable, a Kubernetes Secret, a vault, a systemd `EnvironmentFile`, or an uncommitted `.env` file.

An agent cannot create tokens. Ask the user to create one and to put it in the secret store, and reference it only by name.

## Endpoint

```text
POST https://api.alert51.com/v1/check-ins
```

The same API is also served on the web origin as `POST https://alert51.com/api/v1/check-ins`. Examples in this guide build the URL as `$ALERT51_URL/v1/check-ins` with `ALERT51_URL` defaulting to `https://api.alert51.com`. Set `ALERT51_URL=https://alert51.com/api`, or `https://your-host/api` for a self-hosted instance, to use the web origin.

Headers:

- `Authorization: Bearer <token>` (required)
- `Content-Type: application/json` (required)
- `Idempotency-Key: <key>` (optional, see Idempotency)

The body is a JSON object of at most 16 KB. Unknown fields are rejected.

## Request fields

- `project` (required): slug matching `^[a-z0-9][a-z0-9_.-]{0,62}$`. Input is trimmed and lowercased.
- `job` (required): slug with the same pattern, unique inside the project.
- `status` (required): `success` or `failure`. No other values are accepted.
- `cron` (required on the first check-in): five-field cron expression, for example `0 3 * * *`. Omit it later to keep the stored schedule; a different value updates the schedule.
- `timezone` (optional): IANA time zone such as `Europe/Berlin`. Default `UTC`.
- `graceSeconds` (optional): integer from 0 to 604800 (7 days). Default 300.
- `scheduledAt` (optional): ISO 8601 date-time with an offset, the scheduled time this run belongs to. Must be within 7 days in the past and 5 minutes in the future.
- `name` (optional): display name, 1 to 120 characters. Defaults to the job slug.
- `message` (optional): up to 1000 characters, for example the error text of a failed run. Truncate longer text and never include secrets.
- `durationMs` (optional): run duration in milliseconds, a non-negative integer.

The first check-in for a job must include `cron`; without it the API answers `422 cron_required`. Send `timezone` and `graceSeconds` on the first check-in too, because the defaults (`UTC`, 300 seconds) are stored when the monitor is created. Later check-ins may send only `project`, `job` and `status`. Sending the same `cron`, `timezone` and `graceSeconds` on every run is also fine and keeps the schedule in code; Alert51 only records a schedule change when a value differs.

## Minimal curl example

First check-in, which creates the monitor:

```bash
curl --fail-with-body --silent --show-error --max-time 10 \
  -X POST "${ALERT51_URL:-https://api.alert51.com}/v1/check-ins" \
  -H "Authorization: Bearer $ALERT51_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"project":"production","job":"db-backup","status":"success","cron":"0 3 * * *","timezone":"UTC","graceSeconds":1800}'
```

Later runs can omit the schedule:

```bash
curl --fail-with-body --silent --show-error --max-time 10 \
  -X POST "${ALERT51_URL:-https://api.alert51.com}/v1/check-ins" \
  -H "Authorization: Bearer $ALERT51_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"project":"production","job":"db-backup","status":"success"}'
```

## Match the job's schedule

- `cron` must be the expression that actually triggers the job, with exactly five fields: minute, hour, day of month, month, day of week. Macros such as `@daily` and six-field expressions with seconds are rejected (`422 invalid_cron`). Write `0 0 * * *` instead of `@daily`, and drop the leading seconds field of Spring or Quartz expressions.
- `timezone` must be the zone the scheduler evaluates the expression in. Crontab uses the server's local zone unless `CRON_TZ` is set; Kubernetes CronJobs use `.spec.timeZone` or the controller's zone (usually UTC); GitHub Actions schedules are UTC; GitLab pipeline schedules have their own time zone setting. A wrong zone produces false missed-run alerts.
- `graceSeconds` is how long after the scheduled time the check-in may arrive. The check-in is sent when the job ends, so set it above the job's longest normal duration plus any start delay, for example 1800 for a backup that takes up to 20 minutes.
- If a schedule cannot be expressed in cron (for example some systemd `OnCalendar` values), use the closest cron expression and a larger grace period.
- Each check-in is assigned to the latest scheduled time at or before the time it is received plus 60 seconds of early tolerance. If runs can start late (queues, retries), send `scheduledAt` with the intended scheduled time so the run is matched to the right slot. Reports older than the latest applied one are stored as `stale` and do not change the monitor.
- The deadline is the next scheduled time after the run's slot plus `graceSeconds`. The response returns `nextRunAt` and `deadlineAt`; check them after the first check-in.

## Failures and missed runs

- Explicit failure: when the job fails and can still run code, send `"status": "failure"` with a short `message`. Alert51 opens an incident with cause `failure` at once. The next `success` resolves it.
- Missed run: if no check-in arrives by `deadlineAt`, Alert51 opens an incident with cause `missed`. This covers crashes, killed processes, stopped servers and disabled schedulers, so a job that dies without reporting is still detected.
- Do not report `success` from a code path that also runs after a failure, and do not report at the start of the job.

## Integration patterns

Shell wrapper that keeps the job's exit code:

```bash
#!/bin/sh
started=$(date +%s)
/opt/scripts/backup.sh
code=$?
if [ "$code" -eq 0 ]; then status=success; else status=failure; fi
duration_ms=$(( ($(date +%s) - started) * 1000 ))
curl --fail-with-body --silent --show-error --max-time 10 \
  -X POST "${ALERT51_URL:-https://api.alert51.com}/v1/check-ins" \
  -H "Authorization: Bearer $ALERT51_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"project\":\"production\",\"job\":\"db-backup\",\"status\":\"$status\",\"cron\":\"0 3 * * *\",\"timezone\":\"UTC\",\"graceSeconds\":1800,\"durationMs\":$duration_ms}" \
  || echo "Alert51 check-in failed" >&2
exit "$code"
```

Node.js 18 or later with the built-in `fetch`:

```javascript
async function reportToAlert51(status, startedAt, message) {
  try {
    const response = await fetch(`${process.env.ALERT51_URL ?? 'https://api.alert51.com'}/v1/check-ins`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.ALERT51_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        project: 'production',
        job: 'db-backup',
        status,
        cron: '0 3 * * *',
        timezone: 'UTC',
        graceSeconds: 1800,
        durationMs: Date.now() - startedAt,
        message: message?.slice(0, 1000),
      }),
      signal: AbortSignal.timeout(10_000),
    });
    if (!response.ok) console.error(`Alert51 check-in rejected: ${response.status} ${await response.text()}`);
  } catch (error) {
    console.error(`Alert51 check-in failed: ${error}`);
  }
}

const startedAt = Date.now();
try {
  await runBackup();
} catch (error) {
  await reportToAlert51('failure', startedAt, String(error));
  throw error;
}
await reportToAlert51('success', startedAt);
```

Python 3 with the standard library:

```python
import json
import os
import sys
import time
import urllib.request


def report_to_alert51(status, started, message=None):
    try:
        body = {
            "project": "production",
            "job": "db-backup",
            "status": status,
            "cron": "0 3 * * *",
            "timezone": "UTC",
            "graceSeconds": 1800,
            "durationMs": int((time.monotonic() - started) * 1000),
        }
        if message:
            body["message"] = message[:1000]
        request = urllib.request.Request(
            os.environ.get("ALERT51_URL", "https://api.alert51.com") + "/v1/check-ins",
            data=json.dumps(body).encode(),
            headers={"Authorization": "Bearer " + os.environ["ALERT51_TOKEN"], "Content-Type": "application/json"},
            method="POST",
        )
        with urllib.request.urlopen(request, timeout=10):
            pass
    except Exception as error:
        print(f"Alert51 check-in failed: {error}", file=sys.stderr)


started = time.monotonic()
try:
    run_backup()
except Exception as error:
    report_to_alert51("failure", started, str(error))
    raise
report_to_alert51("success", started)
```

In CI, send the check-in from a step that always runs (GitLab `after_script` with `$CI_JOB_STATUS`, GitHub Actions `if: always()` with `job.status`) and end the command with `|| true` so reporting never changes the pipeline result.

## SDKs

Alert51 has SDKs for Node.js, Java, PHP, Python and Go, but they are not published to npm, Maven Central, Packagist, PyPI or the Go module proxy yet, so there is no install command that works outside the Alert51 source repository. Use plain HTTP as shown above. If the project already contains an Alert51 SDK, use it; its usage is described at https://alert51.com/docs#sdks.

## Responses

`201 Created` means this check-in created the monitor. `200 OK` means it was recorded for an existing monitor. Both return the same JSON:

```json
{
  "monitorId": "0b7f3c52-6f1e-4c55-9a1d-3b8c2e9d4f10",
  "project": "production",
  "job": "db-backup",
  "created": true,
  "checkIn": {
    "id": "c6a1e0d4-2b9f-4c1a-8e57-91f0a3d2b6e8",
    "status": "success",
    "receivedAt": "2026-11-23T03:07:12.000Z",
    "slotAt": "2026-11-23T03:00:00.000Z",
    "outcome": "applied",
    "late": false
  },
  "schedule": { "cron": "0 3 * * *", "timezone": "UTC", "graceSeconds": 1800, "changed": false },
  "monitorStatus": "up",
  "nextRunAt": "2026-11-24T03:00:00.000Z",
  "deadlineAt": "2026-11-24T03:30:00.000Z",
  "incident": null
}
```

- `checkIn.outcome` is `applied`, `stale` (older than the latest applied report) or `paused` (the monitor is paused in the dashboard).
- `checkIn.late` is true when the check-in arrived after its slot's grace period.
- `monitorStatus` is `up`, `down` or `paused`; `incident` describes the open incident, if any.

## Errors

Errors are JSON with a stable code: `{ "error": { "code": "...", "message": "...", "details": ... }, "requestId": "..." }`. Log the status, code and `requestId`, never the token.

- `400 validation_failed`: the body or the `Idempotency-Key` header is invalid. `details` lists `{ "path", "message" }` per field. Fix the payload; do not retry.
- `401 unauthorized`: the token is missing, invalid or revoked. Do not retry; ask the user to check `ALERT51_TOKEN`.
- `403 quota_exceeded`: the account's plan limit for monitors or projects is reached. Do not retry; ask the user to remove a monitor or upgrade.
- `409 idempotency_key_reuse`: the `Idempotency-Key` was already used with a different body.
- `413 payload_too_large`: the body is larger than 16 KB.
- `422 cron_required`, `invalid_cron`, `invalid_timezone`, `scheduled_at_out_of_range`: the schedule fields are wrong. Fix them; do not retry.
- `429 rate_limited`: too many requests. The API allows 3 requests per second per token, and the edge may also limit by client IP. Wait the number of seconds in the `Retry-After` header (the API also returns it as `error.details.retryAfterSeconds`); a 429 from the edge may not have a JSON body.
- `5xx`, timeouts and network errors are temporary. Retry at most once or twice with a short backoff and the same `Idempotency-Key`, within the job's own time budget, and then give up and log. Never block or fail the job because Alert51 is unreachable.

## Idempotency

Send an `Idempotency-Key` header (1 to 255 visible ASCII characters) to make retries safe. The same key with the same body within 24 hours returns the original response with the header `Idempotent-Replayed: true` and records nothing new. The same key with a different body returns `409 idempotency_key_reuse`. Build the key from something unique per run, such as the job name plus the scheduled time or the CI run ID, for example `db-backup-2026-11-23T03:00Z`.

## Verification checklist

Use a dedicated test job (for example `project` `staging` or `job` `db-backup-test`) and a test token, a test notification destination, or a local Alert51 instance, so simulated failures do not page anyone.

1. Send the first check-in with `cron`, `timezone` and `graceSeconds`. Expect `201` and `"created": true`.
2. Check that `schedule` echoes the intended values and that `nextRunAt` and `deadlineAt` match the job's next scheduled time and that time plus the grace period. A check-in sent by hand outside the scheduled window is matched to the previous scheduled time and reported with `"late": true`; that is expected for a manual test.
3. Send a later check-in without `cron`. Expect `200` and `"created": false`.
4. Simulate a failure (make the test job exit non-zero or raise). Expect a `failure` check-in, an open incident in the response, and the job's original exit code or exception unchanged.
5. Send a check-in with an invalid token. Expect `401`, and confirm the job still finishes with its own result.
6. Point `ALERT51_URL` at an unreachable address and confirm the job ends within the timeout with its own result.
7. Delete or pause the test monitor in the dashboard when done, and confirm the real job's monitor appears after its first real run.
