openapi: 3.1.0
info:
  title: Monitive API
  version: 0.1.0
  description: |
    API-first uptime monitoring for developers, deploy pipelines, and AI agents.

    ## Authentication

    All `/api/v1` endpoints require a Bearer token — either an API key (`mk_live_*`)
    or a session token obtained via GitHub OAuth. The `/mcp` endpoint additionally
    accepts OAuth 2.1 JWT access tokens (`eyJ...`) issued via the self-hosted
    authorization server documented under the `OAuth` tag.

    ```
    Authorization: Bearer mk_live_abc123...
    ```

    ## Rate limits

    200 requests/minute per account. Exceeding the limit returns `429` with a
    `Retry-After` header.

    Responses that pass through the per-account rate-limiter carry the
    `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`
    headers (decimal integers; `Reset` is a Unix epoch second at which
    the bucket would be full again). In practice this is every
    authenticated response under `/api/v1/*` whose request reached the
    handler — earlier failures from the auth middleware (e.g. 401 missing
    credentials, 403 suspended account) return before the limiter runs
    and do NOT carry the trio. Routes mounted outside `/api/v1`
    (notably `GET /api/v1/events/stream`, which has its own SSE
    middleware stack) are not subject to this limiter and likewise do
    not emit these headers. Successful responses on
    `POST /api/v1/monitors` reflect the **global** 200/min bucket; the
    per-route 20/min creation limit only surfaces its own headers when
    it 429s. The trio is documented once here rather than referenced
    into every individual response — see `components.headers` for the
    schemas.

    One exception: once a request presenting an API key enters an
    authenticated route group through a registered route or mounted
    subtree, while that key remains in the bounded pre-auth cache
    (entries expire after 5 minutes, but may be evicted sooner once the
    cache is at capacity), the global bucket is charged BEFORE
    authentication and authorization run (issue #47) — so for that
    cached key only, a `401` (key revoked while still cached), `403`,
    `500`, or a `404` for an unmatched path inside a mounted subtree
    also carries the `X-RateLimit-*` trio and spends one token. `429`
    still comes first whenever the bucket is already empty. An uncached
    key (first seen, expired, or evicted early at capacity), a session
    token, an OAuth JWT, and any path outside every authenticated group
    are all unaffected.

    ## Browser push notifications

    Subscriptions registered via `POST /api/v1/push/subscribe` receive
    fire-and-forget Web Push notifications on monitor state transitions
    (down/up/flapping); per-monitor 5-minute throttle. The push-subscription
    endpoint is unchanged; dispatch is internal to `internal/push.Dispatcher`.
    This release (issue #558) adds `blocked` to monitor status values and a
    `monitor.blocked` webhook event carrying `help_url`; clients with closed
    enums must accept both.
  contact:
    name: Monitive
    url: https://monitive.com
  license:
    name: Proprietary
    identifier: LicenseRef-Proprietary
servers:
  - url: https://api.monitive.com
    description: Production
  - url: https://api.uptimemonitoring.com
    description: Production (legacy host)
paths:
  /:
    get:
      operationId: getServiceInfo
      summary: Service info
      description: Returns the service name and docs URL.
      tags: [Public]
      security: []
      responses:
        "200":
          description: Service info.
          content:
            application/json:
              schema:
                type: object
                properties:
                  service:
                    type: string
                    example: uptimemonitoring-dispatcher
                  docs:
                    type: string
                    example: https://monitive.com/docs/
        "405":
          $ref: "#/components/responses/MethodNotAllowed"
        "500":
          $ref: "#/components/responses/InternalError"
  /healthz:
    get:
      operationId: healthCheck
      summary: Health check
      description: >-
        Returns 200 if the service is running. Used by load balancers and by the post-deploy smoke check, which also asserts `commit` against the commit it just deployed.
      tags: [Public]
      security: []
      responses:
        "200":
          description: Healthy.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: ok
                  commit:
                    type: string
                    description: >-
                      The 40-char git commit this binary was built from, or "dev" for a build with no -X main.commitSHA stamp.
                    example: 8bade47d6d9db61a607781f04aefb9349f01d28d
        "405":
          $ref: "#/components/responses/MethodNotAllowed"
        "500":
          $ref: "#/components/responses/InternalError"
  /oauth/github/login:
    get:
      operationId: oauthGitHubLogin
      summary: Start GitHub OAuth flow
      description: |
        Redirects the user to GitHub's authorization page. Sets an `oauth_state`
        cookie for CSRF protection. After authorization, GitHub redirects to
        `/oauth/github/callback`.

        Requests scope `read:user user:email` (issue #390) — `user:email`
        lets the callback read `GET /user/emails` to discover GitHub's
        verified primary address, now REQUIRED for sign-in (issue #462; see
        `/oauth/github/callback`). Every account sees GitHub's consent
        screen once more on their next sign-in or link.

        Issue #405: an accepted `app_origin` is stored in an
        `oauth_app_origin` cookie (`Path=/oauth`, HttpOnly, `SameSite=Lax`,
        10 minutes) so the callback lands on that origin's `/callback`.
        Without one, any stale `oauth_app_origin` cookie is cleared.

        Issues #460 and #529: `GITHUB_REDIRECT_URI` is a fixed,
        GitHub-registered callback URL pinned to the canonical host
        (`https://api.monitive.com`) regardless of which host this request
        arrived on. A request on the configured OAuth issuer alias host
        (`https://api.uptimemonitoring.com`) is redirected straight to the
        identical path and query on the canonical host instead — no
        cookie is set and GitHub is never contacted on the alias host —
        so a sign-in started on either host completes the same way.

        Issue #540: an optional `migration_token` (a Monitive Classic
        migration-link token) is carried to the callback in the `oauth_migration_token`
        cookie. See the `migration_token` parameter and the callback's
        migration paragraph.
      tags: [OAuth]
      security: []
      parameters:
        - name: app_origin
          in: query
          required: false
          schema:
            type: string
          example: https://issue-194-x-um-app.monitive.workers.dev
          description: |
            The SPA origin to land the finished sign-in on (issue #405).
            Honored only when it equals `FRONTEND_URL`'s origin or, while
            `PREVIEW_APP_ORIGIN_SUFFIX` is set, is `https://` plus exactly
            one DNS label plus that suffix (no port, path, or userinfo),
            or byte-for-byte equals an entry of `EXTRA_APP_ORIGINS` (issue
            #521 — exact `https://host[:port]` origins, compared
            case-sensitively).
            An accepted value is stored in the `oauth_app_origin` cookie
            (`Path=/oauth`); anything else is ignored and never echoed.
        - name: migration_token
          in: query
          required: false
          schema:
            type: string
            pattern: "^[A-Za-z0-9_-]{43}$"
          description: |
            Optional Monitive Classic migration-link token (issue #540):
            exactly 43 characters of `[A-Za-z0-9_-]`. A valid value is
            stored in the `oauth_migration_token` cookie (`Path=/oauth`,
            HttpOnly, `SameSite=Lax`, 10 minutes, no Domain) for the
            callback to check against Classic. A malformed value is
            ignored, clears any stale cookie of that name, and is never
            echoed. The value is redacted from this server's request log.
      responses:
        "302":
          description: Redirect to GitHub authorization page.
        "500":
          $ref: "#/components/responses/InternalError"
  /oauth/github/callback:
    get:
      operationId: oauthGitHubCallback
      summary: GitHub OAuth callback (sign-in or identity link)
      description: |
        Handles the redirect from GitHub after authorization. In sign-in
        mode, verifies the state parameter, exchanges the code for an
        access token, upserts the account, and redirects to the frontend
        with a one-time auth code.

        Issue #390 added a fetch of GitHub's verified primary email address
        via `GET /user/emails`; issue #462 made that fetch REQUIRED — a
        GitHub sign-in without a verified primary address is refused
        outright, in sign-in mode only (never link mode):

          - No verified primary at all (GitHub answered the request and
            reported none): refuses with `error=github_email_unverified`,
            before `SignInWithGitHub` is ever called and before an auth
            code is minted. Applies even to an existing user who already
            has a saved address — the rule is about what GitHub reports
            for this sign-in.
          - The fetch itself failed (timeout, transport error, a blocked
            target, a non-200, or a malformed/oversized response — GitHub
            gave no definitive answer either way): falls back to checking
            whether this GitHub ID already has a confirmed email on file.
            If so, sign-in proceeds (a repeat sign-in on an existing row);
            otherwise refuses with `error=github_email_unavailable`. This
            lets an established user ride out a GitHub API outage or rate
            limit without being locked out, while a brand-new or
            still-email-less user cannot be confirmed this way.
          - A verified primary is found, and nobody holds it yet: sign-in
            proceeds; an unclaimed address is saved onto the new user in
            the same transaction.
          - The address is already a verified email identity on an
            EXISTING user who has no GitHub identity of their own: the
            sign-in is merged into that user's existing account instead of
            creating a new one — the caller lands on the matched user's
            account, with the GitHub identity now attached to it. If that
            account is suspended, the callback redirects with
            `error=account_suspended`, the same as an email sign-in into a
            suspended account, and nothing is linked.
          - The address already belongs to a DIFFERENT user who already
            has their own GitHub identity: no merge; the sign-in creates an
            ordinary new user and account, with no email of its own. The
            adopt call that records `account.github_email_skipped` on the
            new account runs best-effort, after sign-in has already
            succeeded: a timeout, store error, or panic there is logged
            and swallowed, so a successful sign-in in this case is not a
            guarantee that the event was recorded.

        A merged or newly-adopted address enrolls the member in the
        account's default-enabled weekly and monthly uptime reports and
        becomes visible to the account's owner(s), the same as adding an
        email through `POST /api/v1/me/identities/email/start`+`/verify`.

        In identity-link mode (issue #325 — an `oauth_github_link` cookie
        set by a prior `POST /oauth/github/link`), redeems the ticket
        instead — every outcome, success or failure, redirects to
        `{FRONTEND_URL}/settings?linked=github` or
        `{FRONTEND_URL}/settings?link_error=<code>`, and sign-in is never
        attempted. Mirrors `/oauth/google/callback`'s link-mode shape
        exactly.

        **Disposable addresses (issue #613):** in sign-in mode only, a
        verified primary email whose domain, or any parent domain, is on
        the embedded disposable-email list skips legacy routing and the
        company-domain gate and may only sign in to an existing user. A
        sign-in that would create a new user redirects with
        `error=disposable_email` and creates nothing. Link mode is
        unaffected, and this never triggers the email sign-in cooldown.

        Where a sign-in-mode redirect lands, success (`?code=`) or error
        (`?error=`) alike (issue #405): a valid OAuth-bridge `return_to`
        first; else the `app_origin` the login accepted (per
        `/oauth/github/login`'s `app_origin` rule — `FRONTEND_URL`, a
        preview origin, or an `EXTRA_APP_ORIGINS` entry; from the
        `oauth_app_origin` cookie, re-checked here), as
        `<app_origin>/callback`; else `{FRONTEND_URL}/callback`. The
        `oauth_app_origin` cookie is cleared on every exit. Link mode
        ignores it.

        **Legacy Monitive routing (issue #467):** when configured, sign-in
        mode runs a signed lookup against legacy Monitive before resolving
        the identity. A legacy-only identity gets the `200 text/html`
        auto-submitting handoff form below instead of a redirect, and
        `SignInWithGitHub` is never called. An identity known to both
        legacy and this binary instead gets `302` to
        `{app}/signin/choose#choice=<tok>`. A legacy lookup failure with no
        existing account for this identity redirects with
        `error=legacy_unavailable`, same shape as every other refusal
        code; with an existing account, sign-in proceeds through an
        existing-only variant that creates nothing new. See
        `internal/api/DECISIONS.md`.

        **Company-domain gate (issue #471):** when configured, and only
        on an ordinary account-creating sign-in (never on the GitHub
        `/user/emails`-outage fallback, and never when legacy routing
        just resolved an existing-only fallthrough), a freshly verified
        email whose domain is not a free/consumer mail domain and already
        belongs to another member gets `302` to
        `{app}/signin/company#choice=<tok>&domain=<domain>` instead of an
        ordinary sign-in — redeemed by
        `POST /oauth/company-domain/choice`. Off by default
        (`COMPANY_DOMAIN_MATCH_ENABLED` unset). See
        `internal/api/DECISIONS.md`.

        **Migration link (issue #540):** the callback reads and clears the
        `oauth_migration_token` cookie on every exit. When legacy routing is
        configured and this sign-in reaches it, a valid token is first checked
        against Classic's migration resolve. An eligible token signs in to Swift
        with no handoff page and no chooser, and adds nothing to the redirect.
        An ineligible or failed token routes exactly as a sign-in without one,
        and appends `&migration_reason=<reason>` to the app-bound
        `/callback?code=` and `/callback?error=` redirects and to the
        `/signin/choose#choice=` and `/signin/company#choice=` fragments —
        never to the OAuth-bridge `return_to` redirect or the handoff page.
        `<reason>` is one of `unknown_link`, `already_moved`, `expired`,
        `not_owner`, `not_free`, `not_exported`, `billing_unavailable`, or
        `unavailable` (the resolve call failed). Link mode never uses the token.
      tags: [OAuth]
      security: []
      parameters:
        - name: code
          in: query
          required: true
          schema:
            type: string
          description: Authorization code from GitHub.
        - name: state
          in: query
          required: true
          schema:
            type: string
          description: CSRF state parameter (must match the `oauth_state` cookie).
      responses:
        "200":
          description: |
            Legacy-only identity (issue #467): an auto-submitting HTML form
            that POSTs the field `token` to the legacy handoff URL, with a
            `noscript` fallback button. Its own CSP (`form-action` limited
            to the handoff URL's origin and the Classic app origin that its
            response redirects to, `script-src` limited to this page's one
            inline script by sha256 hash), `Referrer-Policy:
            no-referrer`, and `Cache-Control: no-store`.
          content:
            text/html:
              schema:
                type: string
        "302":
          description: Redirect to frontend with auth code or error, to the settings page (link mode), to the legacy-handoff chooser (issue #467, known to both), or to the company-domain screen (issue #471).
        "400":
          description: Missing or invalid state/code parameter.
  /oauth/github/link:
    post:
      operationId: oauthGitHubLink
      summary: Start a GitHub identity link
      description: |
        The sole entry point for starting a GitHub identity link (issue
        #325), mirroring `/oauth/google/link` exactly. The SPA submits, as
        a top-level form POST (never a GET query string), the
        `link_ticket` returned by `POST /api/v1/me/identities/github`.

        Validates the ticket read-only (no redemption yet — that happens
        at `/oauth/github/callback`). A malformed, wrong-length, unknown,
        expired, already-consumed, or wrong-provider (e.g. a Google-minted
        ticket) ticket clears any stale `oauth_github_link` cookie and
        redirects straight to
        `{FRONTEND_URL}/settings?link_error=link_invalid` without
        contacting GitHub. A valid ticket sets an `oauth_github_link`
        cookie (`Path=/oauth/github`, 10 minutes) and redirects to
        GitHub's authorization page exactly like `/oauth/github/login`.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [link_ticket]
              properties:
                link_ticket:
                  type: string
      responses:
        "302":
          description: Redirect to GitHub's authorization page, or (invalid ticket) straight to the settings page.
  /oauth/exchange:
    post:
      operationId: oauthExchange
      summary: Exchange auth code for session token
      description: |
        Exchanges a one-time auth code (from the OAuth callback redirect) for a
        session token. Auth codes expire after 60 seconds and can only be used once.
        The returned session token lasts 30 days from its most recent use (sliding —
        each use more than an hour after the last extends it another 30 days), as a
        best-effort refresh: an occasional failure to extend is logged server-side
        and does not fail the request, leaving the session valid on its prior expiry
        until the next qualifying use tries the extension again. The token survives
        a dispatcher restart; it is persisted server-side as a hash, never in a
        recoverable form.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code:
                  type: string
                  description: One-time auth code from the OAuth callback redirect.
      responses:
        "200":
          description: Session token and account info.
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
                    description: Session token for Bearer authentication.
                  account:
                    $ref: "#/components/schemas/Account"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          description: Invalid or expired auth code.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
  /oauth/email/start:
    post:
      operationId: oauthEmailStart
      summary: Start email sign-in (link or code)
      description: |
        Sends a sign-in email containing both a link (`{FRONTEND_URL}/signin/email#token=<tok>`,
        the token lives only in the URL fragment, which keeps it out of the
        landing-page request URL and ordinary access logs — verification
        itself sends it to this API in a POST body, which the request
        logger does not log) and a six-digit code, both valid for 10
        minutes. Returns `202` with
        an identical body for a known or unknown address — this endpoint
        never reveals whether an address has signed in before.

        Disabled unless `EMAIL_SIGNIN_ENABLED` is set at boot (`503` when
        disabled). Rate limited per address, per caller IP, and with a
        process-wide backstop; see `internal/api/DECISIONS.md` for the
        exact values. `return_to` is honored only when it matches the
        configured OAuth-bridge finalize prefix, mirroring
        `/oauth/github/login`'s `return_to` handling.

        **Disposable addresses (issue #613):** an address whose domain, or
        any parent domain, is on the embedded disposable-email list gets
        `422` with the fixed message below, no email is sent, and no
        challenge is created. The answer is the same whether or not the
        address already has an account. That rejection also starts a
        24-hour sign-up cooldown for the caller's IP: every further
        `start` from that IP gets `429` with `Retry-After` until it ends,
        before the request body is even read. The cooldown is in memory,
        cleared by a restart, never extended by a refused request, and
        never applies to `/oauth/email/verify` or to OAuth sign-in.

        Issue #540: an optional `migration_token` (a Monitive Classic
        migration-link token) is stored with the challenge for
        `/oauth/email/verify` to check against Classic. Any string that is not a
        valid token is ignored, with the same `202` body; only a non-string
        value is a `400`.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:
                  type: string
                  format: email
                return_to:
                  type: string
                  description: Only honored when it matches the configured OAuth-bridge finalize prefix.
                migration_token:
                  type: string
                  description: |
                    Optional Monitive Classic migration-link token (issue
                    #540): exactly 43 characters of `[A-Za-z0-9_-]`. Stored
                    with the challenge when valid; any other string is
                    ignored silently. Never logged.
      responses:
        "202":
          description: Byte-identical for a known or unknown address.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: sent
        "400":
          $ref: "#/components/responses/BadRequest"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: The address is on a disposable-email domain (issue #613).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: Use a permanent email address to sign up for Monitive.
        "429":
          description: |
            Rate limited (per address, per IP, or the process-wide
            backstop), or the caller's IP is inside the 24-hour sign-up
            cooldown a disposable-address rejection started (issue #613).
            A disposable request that loses a race to start that cooldown
            also gets this response. `Retry-After` carries the seconds
            remaining, and the body is
            `{"error":"too many sign-in requests; retry later"}`.
          headers:
            Retry-After:
              description: Seconds until the limiting window ends.
              schema:
                type: integer
        "503":
          description: Email sign-in disabled, or the transport (SendGrid) failed to send.
  /oauth/email/verify:
    post:
      operationId: oauthEmailVerify
      summary: Verify an email sign-in link or code
      description: |
        Accepts exactly ONE of two bodies: `{"token": "..."}` (the link's
        fragment token) or `{"email", "code"}` (the six-digit code). Every
        failure case — unknown, expired, wrong code, already consumed,
        locked out after 5 wrong attempts, or malformed — returns the
        identical `401` body, so a caller cannot distinguish them. There is
        no GET route for this endpoint — a link scanner or prefetcher that
        merely opens the emailed link cannot burn the challenge.

        On success returns `redirect_to`, the same shape
        `/oauth/github/callback` produces: either the dashboard's
        `/callback?code=...` or, if the original `start` call's `return_to`
        is still valid against the OAuth-bridge finalize prefix, that URL
        with `?code=...` appended.

        Issue #405: when there is no valid bridge `return_to` and the
        request's `Origin` header is an allowed app origin other than
        `FRONTEND_URL`'s own (a branch preview, while
        `PREVIEW_APP_ORIGIN_SUFFIX` is set, or an exact `EXTRA_APP_ORIGINS`
        entry, issue #521), `redirect_to` is
        `<Origin>/callback?code=...` instead. An absent or refused `Origin`
        changes nothing, and never affects a failure response. The emailed
        link always stays on `FRONTEND_URL`, so a preview or extra app
        signs in by typing the six-digit code.

        **Legacy Monitive routing (issue #467):** when configured, a
        signed lookup against legacy Monitive runs before the challenge is
        consumed. An identity legacy doesn't know gets the unchanged
        `redirect_to` body above. A legacy-only or known-to-both identity
        instead needs the `X-Monitive-Client: legacy-handoff-1` request
        header — without it, both get `503 {"error":"legacy_unavailable"}`
        and the code is NOT consumed (retryable with the header). With the
        header: a legacy-only identity gets `{"handoff":{"action","token"}}`
        and the challenge IS consumed, creating no account; a known-to-both
        identity gets `{"choice":"<tok>"}`, redeemed by
        `POST /oauth/legacy/choice`. A legacy lookup failure with no
        existing account refuses with `legacy_unavailable` regardless of
        the header; with an existing account, verification proceeds
        through an existing-only variant that creates nothing new.

        **Company-domain gate (issue #471):** when configured, and only
        when either legacy routing is off or just resolved an ordinary,
        account-creating outcome, a domain match (same rule as
        `/oauth/github/callback`'s own company-domain paragraph) returns
        `{"company_domain":{"domain":"<domain>","choice":"<tok>"}}`
        instead of consuming the challenge — redeemed by
        `POST /oauth/company-domain/choice`. The challenge itself stays
        live and usable until that redemption (or its own expiry).

        **Migration link (issue #540):** when the start call carried a valid
        `migration_token` and legacy routing is configured, the token is checked
        against Classic's migration resolve before the legacy lookup. An
        eligible token signs in to Swift (`redirect_to`) with no `handoff` or
        `choice`, and adds nothing to the body. An ineligible or failed token
        routes exactly as without one, and every `200` body — `redirect_to`,
        `choice`, `company_domain` and `handoff` alike — also carries
        `"migration": {"eligible": false, "reason": "<reason>"}`
        (`LegacyMigrationOutcome`). Error bodies never carry it.
      tags: [OAuth]
      security: []
      parameters:
        - name: X-Monitive-Client
          in: header
          required: false
          schema:
            type: string
            enum: [legacy-handoff-1]
          description: |
            Declares the caller understands the `choice`/`handoff` response
            shapes (issue #467). Only consulted when legacy-handoff routing
            is configured; any other value (including absent) counts as
            not capable and gates those two shapes behind a `503`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                token:
                  type: string
                  description: The link's fragment token. Mutually exclusive with email/code.
                email:
                  type: string
                  format: email
                code:
                  type: string
                  description: Six-digit code. Requires email; mutually exclusive with token.
      responses:
        "200":
          description: Sign-in succeeded, or (issue #467) the identity needs a legacy chooser/handoff and the capability header was present. Any of these bodies also carries `migration` when an ineligible or failed migration token was presented (issue #540).
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    required: [redirect_to]
                    properties:
                      redirect_to:
                        type: string
                        format: uri
                      migration:
                        $ref: "#/components/schemas/LegacyMigrationOutcome"
                  - type: object
                    required: [choice]
                    properties:
                      choice:
                        type: string
                        description: Single-use token for POST /oauth/legacy/choice, valid up to 5 minutes.
                      migration:
                        $ref: "#/components/schemas/LegacyMigrationOutcome"
                  - type: object
                    required: [company_domain]
                    properties:
                      company_domain:
                        type: object
                        description: Issue #471. choice is a single-use token for POST /oauth/company-domain/choice, valid up to 5 minutes (capped at the challenge's own expiry).
                        properties:
                          domain:
                            type: string
                          choice:
                            type: string
                      migration:
                        $ref: "#/components/schemas/LegacyMigrationOutcome"
                  - type: object
                    required: [handoff]
                    properties:
                      handoff:
                        type: object
                        properties:
                          action:
                            type: string
                            format: uri
                          token:
                            type: string
                      migration:
                        $ref: "#/components/schemas/LegacyMigrationOutcome"
        "401":
          description: Invalid, expired, wrong, reused, locked, or malformed — identical body for every case.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: The resolved account is suspended.
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          description: Rate limited (per caller IP, or the process-wide backstop).
        "503":
          description: Email sign-in disabled, or (issue #467) the identity needs legacy routing and either the capability header is missing or the legacy lookup failed.
  /oauth/google/login:
    get:
      operationId: oauthGoogleLogin
      summary: Start Google OAuth flow (sign-in)
      description: |
        Redirects to Google's authorization page (`scope=openid email`,
        `prompt=select_account`). Sets an `oauth_google_state` cookie
        (`Path=/oauth/google`) for CSRF protection, distinct from GitHub's
        `oauth_state` cookie.

        Not mounted at all unless `GOOGLE_CLIENT_ID`/`GOOGLE_CLIENT_SECRET`/
        `GOOGLE_REDIRECT_URI` are all configured — `404` otherwise.

        This route is sign-in only. A stray `link_ticket` query parameter is
        ignored outright and any stale `oauth_google_link` cookie is
        cleared — identity-link starts only via `POST /oauth/google/link`,
        never a GET query string (a bearer ticket in a URL would stay live
        in server/proxy access logs for the full 10-minute window it
        remains valid).

        Issue #405: an accepted `app_origin` is stored in an
        `oauth_google_app_origin` cookie (`Path=/oauth/google`, HttpOnly,
        `SameSite=Lax`, 10 minutes) so the callback lands on that origin's
        `/callback`. Without one, any stale `oauth_google_app_origin` cookie
        is cleared.

        Issue #540: an optional `migration_token` (a Monitive Classic
        migration-link token) is carried to the callback in the `oauth_google_migration_token`
        cookie. See the `migration_token` parameter and the callback's
        migration paragraph.
      tags: [OAuth]
      security: []
      parameters:
        - name: return_to
          in: query
          required: false
          schema:
            type: string
          description: |
            Only honored when it matches the configured OAuth-bridge finalize
            prefix. When honored it takes precedence over `app_origin`
            (including an `EXTRA_APP_ORIGINS` entry).
        - name: app_origin
          in: query
          required: false
          schema:
            type: string
          example: https://issue-194-x-um-app.monitive.workers.dev
          description: |
            The SPA origin to land the finished sign-in on (issue #405).
            Honored only when it equals `FRONTEND_URL`'s origin or, while
            `PREVIEW_APP_ORIGIN_SUFFIX` is set, is `https://` plus exactly
            one DNS label plus that suffix (no port, path, or userinfo),
            or byte-for-byte equals an entry of `EXTRA_APP_ORIGINS` (issue
            #521 — exact `https://host[:port]` origins, compared
            case-sensitively).
            An accepted value is stored in the `oauth_google_app_origin`
            cookie (`Path=/oauth/google`); anything else is ignored and
            never echoed.
        - name: migration_token
          in: query
          required: false
          schema:
            type: string
            pattern: "^[A-Za-z0-9_-]{43}$"
          description: |
            Optional Monitive Classic migration-link token (issue #540):
            exactly 43 characters of `[A-Za-z0-9_-]`. A valid value is
            stored in the `oauth_google_migration_token` cookie (`Path=/oauth/google`,
            HttpOnly, `SameSite=Lax`, 10 minutes, no Domain) for the
            callback to check against Classic. A malformed value is
            ignored, clears any stale cookie of that name, and is never
            echoed. The value is redacted from this server's request log.
      responses:
        "302":
          description: Redirect to Google's authorization page.
        "404":
          description: Google sign-in not configured.
  /oauth/google/link:
    post:
      operationId: oauthGoogleLink
      summary: Start a Google identity link
      description: |
        The sole entry point for starting an identity link (issue #316 fold
        finding 53dbd2c17572ecf3). The SPA submits, as a top-level form POST
        (never a GET query string, so the bearer ticket never appears in the
        request-URI-keyed request logger), the `link_ticket` returned by
        `POST /api/v1/me/identities/google`.

        Validates the ticket read-only (no redemption yet — that happens at
        `/oauth/google/callback`). A malformed, wrong-length, unknown,
        expired, or already-consumed ticket clears any stale
        `oauth_google_link` cookie and redirects straight to
        `{FRONTEND_URL}/settings?link_error=link_invalid` without contacting
        Google. A valid ticket sets an `oauth_google_link` cookie
        (`Path=/oauth/google`, 10 minutes) and redirects to Google's
        authorization page exactly like `/oauth/google/login`.

        Not mounted unless Google sign-in is configured — `404` otherwise.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [link_ticket]
              properties:
                link_ticket:
                  type: string
      responses:
        "302":
          description: Redirect to Google's authorization page, or (invalid ticket) straight to the settings page.
        "404":
          description: Google sign-in not configured.
  /oauth/google/callback:
    get:
      operationId: oauthGoogleCallback
      summary: Google OAuth callback (sign-in or identity link)
      description: |
        Handles the redirect from Google. In sign-in mode, behaves like
        `/oauth/github/callback`: exchanges the code, fetches the Google
        `sub`/`email`/`email_verified`/`hd` claims, resolves or creates the
        account, and redirects to the frontend with a one-time auth code.
        A genuinely first sign-in whose `email_verified` claim is the
        literal `true` and whose address is `gmail.com`/`googlemail.com`,
        or matches a Google Workspace/Cloud `hd` claim case-insensitively,
        links onto whichever existing user already holds that address as a
        verified email identity, but only when that holder has no Google
        identity of their own (issue #392) — every other verified address
        still creates a new user, exactly as an unverified one does, and so
        does a holder who already has a DIFFERENT Google identity attached:
        that case creates a separate Google-only user rather than linking.
        Raw claims are never stored; only the narrowed, normalized address
        is, and only on the row it attaches to.

        In identity-link mode (an `oauth_google_link` cookie set by a prior
        `POST /oauth/google/link`), redeems the ticket instead — every
        outcome, success or failure, redirects to
        `{FRONTEND_URL}/settings?linked=google` or
        `{FRONTEND_URL}/settings?link_error=<code>`, and `SignInWithGoogle`
        is never called. Every failure that happens before the ticket is
        redeemed (invalid state, a missing authorization code, or a Google
        token-exchange/userinfo failure) is normalized to the documented
        link-mode codes — `link_invalid` or `internal_error` — rather than
        leaking the raw sign-in error code.

        **Disposable addresses (issue #613):** in sign-in mode only, the
        authoritative address above, or otherwise the raw `email` claim,
        is checked against the embedded disposable-email list (the domain
        or any parent domain). A match skips legacy routing, the
        company-domain gate and the pending signup recipient seed, and may
        only sign in to an existing user; a sign-in that would create a new
        user redirects with `error=disposable_email` and creates nothing.
        Link mode is unaffected.

        Where a sign-in-mode redirect lands, success (`?code=`) or error
        (`?error=`) alike (issue #405): a valid OAuth-bridge `return_to`
        first; else the `app_origin` the login accepted (per
        `/oauth/google/login`'s `app_origin` rule — `FRONTEND_URL`, a
        preview origin, or an `EXTRA_APP_ORIGINS` entry; from the
        `oauth_google_app_origin` cookie, re-checked here), as
        `<app_origin>/callback`; else `{FRONTEND_URL}/callback`. The
        `oauth_google_app_origin` cookie is cleared on every exit,
        including a state mismatch. Link mode ignores it.

        **Legacy Monitive routing (issue #467):** when configured AND the
        resolved Google email claim already clears the strict
        authoritativeness rule above (issue #392 — an unauthoritative
        claim never drives a lookup or handoff), sign-in mode runs the
        same signed legacy lookup `/oauth/github/callback` runs. A
        legacy-only identity gets the `200 text/html` auto-submitting
        handoff form instead of a redirect; a known-to-both identity gets
        `302` to `{app}/signin/choose#choice=<tok>`; a legacy lookup
        failure refuses with `error=legacy_unavailable` unless an existing
        account is found, in which case sign-in proceeds through an
        existing-only variant that creates nothing new. See
        `internal/api/DECISIONS.md`.

        **Company-domain gate (issue #471):** the same rule
        `/oauth/github/callback` documents, gated identically on the
        #392 authoritativeness check — an unauthoritative Google email
        claim never reaches the company-domain check either.

        **Migration link (issue #540):** the callback reads and clears the
        `oauth_google_migration_token` cookie on every exit. When legacy routing is
        configured and this sign-in reaches it, a valid token is first checked
        against Classic's migration resolve. An eligible token signs in to Swift
        with no handoff page and no chooser, and adds nothing to the redirect.
        An ineligible or failed token routes exactly as a sign-in without one,
        and appends `&migration_reason=<reason>` to the app-bound
        `/callback?code=` and `/callback?error=` redirects and to the
        `/signin/choose#choice=` and `/signin/company#choice=` fragments —
        never to the OAuth-bridge `return_to` redirect or the handoff page.
        `<reason>` is one of `unknown_link`, `already_moved`, `expired`,
        `not_owner`, `not_free`, `not_exported`, `billing_unavailable`, or
        `unavailable` (the resolve call failed). Link mode never uses the token.
      tags: [OAuth]
      security: []
      parameters:
        - name: code
          in: query
          required: true
          schema:
            type: string
        - name: state
          in: query
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Legacy-only identity (issue #467) — see `/oauth/github/callback`'s `200` response for the exact shape.
          content:
            text/html:
              schema:
                type: string
        "302":
          description: Redirect to the frontend (sign-in) or settings page (link), success or error either way, to the legacy-handoff chooser (issue #467, known to both), or to the company-domain screen (issue #471).
        "404":
          description: Google sign-in not configured.
  /oauth/microsoft/login:
    get:
      operationId: oauthMicrosoftLogin
      summary: Start Microsoft OAuth flow (sign-in)
      description: |
        Redirects to Microsoft's `common`-tenant authorization page
        (`scope=openid email`, `prompt=select_account`). Sets an
        `oauth_microsoft_state` cookie (`Path=/oauth/microsoft`) for CSRF
        protection, distinct from GitHub's and Google's own state cookies.

        Not mounted at all unless `MICROSOFT_CLIENT_ID`/
        `MICROSOFT_CLIENT_SECRET`/`MICROSOFT_REDIRECT_URI` are all
        configured — `404` otherwise.

        This route is sign-in only. A stray `link_ticket` query parameter is
        ignored outright and any stale `oauth_microsoft_link` cookie is
        cleared — identity-link starts only via `POST /oauth/microsoft/link`,
        never a GET query string.

        An accepted `app_origin` is stored in an `oauth_microsoft_app_origin`
        cookie (`Path=/oauth/microsoft`, HttpOnly, `SameSite=Lax`, 10
        minutes) so the callback lands on that origin's `/callback`.
        Without one, any stale `oauth_microsoft_app_origin` cookie is
        cleared — same rule as `/oauth/google/login`'s own `app_origin`.

        Issue #540: an optional `migration_token` (a Monitive Classic
        migration-link token) is carried to the callback in the `oauth_microsoft_migration_token`
        cookie. See the `migration_token` parameter and the callback's
        migration paragraph.
      tags: [OAuth]
      security: []
      parameters:
        - name: return_to
          in: query
          required: false
          schema:
            type: string
          description: |
            Only honored when it matches the configured OAuth-bridge finalize
            prefix. When honored it takes precedence over `app_origin`
            (including an `EXTRA_APP_ORIGINS` entry).
        - name: app_origin
          in: query
          required: false
          schema:
            type: string
          example: https://issue-194-x-um-app.monitive.workers.dev
          description: |
            The SPA origin to land the finished sign-in on, matching
            `/oauth/google/login`'s own `app_origin` rule exactly.
        - name: migration_token
          in: query
          required: false
          schema:
            type: string
            pattern: "^[A-Za-z0-9_-]{43}$"
          description: |
            Optional Monitive Classic migration-link token (issue #540):
            exactly 43 characters of `[A-Za-z0-9_-]`. A valid value is
            stored in the `oauth_microsoft_migration_token` cookie (`Path=/oauth/microsoft`,
            HttpOnly, `SameSite=Lax`, 10 minutes, no Domain) for the
            callback to check against Classic. A malformed value is
            ignored, clears any stale cookie of that name, and is never
            echoed. The value is redacted from this server's request log.
      responses:
        "302":
          description: Redirect to Microsoft's authorization page.
        "404":
          description: Microsoft sign-in not configured.
  /oauth/microsoft/link:
    post:
      operationId: oauthMicrosoftLink
      summary: Start a Microsoft identity link
      description: |
        The sole entry point for starting an identity link, mirroring
        `/oauth/google/link` exactly. The SPA submits, as a top-level form
        POST, the `link_ticket` returned by
        `POST /api/v1/me/identities/microsoft`.

        Validates the ticket read-only (no redemption yet — that happens at
        `/oauth/microsoft/callback`). A malformed, wrong-length, unknown,
        expired, or already-consumed ticket clears any stale
        `oauth_microsoft_link` cookie and redirects straight to
        `{FRONTEND_URL}/settings?link_error=link_invalid` without contacting
        Microsoft. A valid ticket sets an `oauth_microsoft_link` cookie
        (`Path=/oauth/microsoft`, 10 minutes) and redirects to Microsoft's
        authorization page exactly like `/oauth/microsoft/login`.

        Not mounted unless Microsoft sign-in is configured — `404`
        otherwise.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [link_ticket]
              properties:
                link_ticket:
                  type: string
      responses:
        "302":
          description: Redirect to Microsoft's authorization page, or (invalid ticket) straight to the settings page.
        "404":
          description: Microsoft sign-in not configured.
  /oauth/microsoft/callback:
    get:
      operationId: oauthMicrosoftCallback
      summary: Microsoft OAuth callback (sign-in or identity link)
      description: |
        Handles the redirect from Microsoft. Unlike Google, there is no
        separate userinfo call: every claim this endpoint needs (`sub`,
        `email`, `tid`, `aud`, `exp`, `ver`, `iss`) is read directly from
        the `id_token` the token endpoint returns, with NO signature
        verification — permitted by OIDC Core §3.1.3.7 for a confidential
        client receiving the token directly from the token endpoint over
        TLS. The token is rejected (`error=microsoft_error`) if `aud` does
        not match the configured client ID, `exp` has passed, `nbf` is in
        the future, `ver` is not `"2.0"`, `tid` is not a GUID, `iss` does
        not equal `https://login.microsoftonline.com/<tid>/v2.0`, or `sub`
        is empty or over 255 bytes.

        In sign-in mode, resolves or creates the account and redirects to
        the frontend with a one-time auth code. A genuinely first sign-in
        whose `tid` is Microsoft's consumer MSA tenant AND whose `email`
        claim's domain is `outlook.com`/`hotmail.com`/`live.com`/`msn.com`
        links onto whichever existing user already holds that address as a
        verified email identity, but only when that holder has no
        Microsoft identity of their own — mirroring Google's own narrowing
        (issue #392) exactly. A work or school tenant's `email` claim is
        NEVER trusted for linking, regardless of the `xms_edov` claim —
        see `internal/api/DECISIONS.md` for why `xms_edov` is deliberately
        never consulted (it proves tenant-level domain ownership, not
        mailbox control, and trusting it would allow an account-takeover
        class sometimes called "nOAuth").

        In identity-link mode (an `oauth_microsoft_link` cookie set by a
        prior `POST /oauth/microsoft/link`), redeems the ticket instead —
        every outcome, success or failure, redirects to
        `{FRONTEND_URL}/settings?linked=microsoft` or
        `{FRONTEND_URL}/settings?link_error=<code>`, and
        `SignInWithMicrosoft` is never called.

        **Disposable addresses (issue #613):** the same rule as
        `/oauth/google/callback`'s, applied to the trusted address or
        otherwise the raw `email` claim: a sign-in that would create a new
        user redirects with `error=disposable_email`.

        Where a sign-in-mode redirect lands, and the legacy-routing
        behavior, both mirror `/oauth/google/callback` exactly, substituting
        provider `"microsoft"`. The company-domain gate is dispatched the
        same way but can never actually fire here: it only ever sees the
        narrowed `verifiedEmail` above, and every domain that narrowing can
        produce (`outlook.com`/`hotmail.com`/`live.com`/`msn.com`) is a known
        free/consumer domain (`internal/freemail`), which the gate always
        excludes. A work or school Microsoft sign-in — the only case with a
        company-owned domain — never reaches the gate at all, unlike
        Google's Workspace/Cloud `hd`-claim case.

        **Migration link (issue #540):** the callback reads and clears the
        `oauth_microsoft_migration_token` cookie on every exit. When legacy routing is
        configured and this sign-in reaches it, a valid token is first checked
        against Classic's migration resolve. An eligible token signs in to Swift
        with no handoff page and no chooser, and adds nothing to the redirect.
        An ineligible or failed token routes exactly as a sign-in without one,
        and appends `&migration_reason=<reason>` to the app-bound
        `/callback?code=` and `/callback?error=` redirects and to the
        `/signin/choose#choice=` and `/signin/company#choice=` fragments —
        never to the OAuth-bridge `return_to` redirect or the handoff page.
        `<reason>` is one of `unknown_link`, `already_moved`, `expired`,
        `not_owner`, `not_free`, `not_exported`, `billing_unavailable`, or
        `unavailable` (the resolve call failed). Link mode never uses the token.
      tags: [OAuth]
      security: []
      parameters:
        - name: code
          in: query
          required: true
          schema:
            type: string
        - name: state
          in: query
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Legacy-only identity (issue #467) — see `/oauth/github/callback`'s `200` response for the exact shape.
          content:
            text/html:
              schema:
                type: string
        "302":
          description: Redirect to the frontend (sign-in) or settings page (link), success or error either way, to the legacy-handoff chooser, or to the company-domain screen.
        "404":
          description: Microsoft sign-in not configured.
  /oauth/legacy/choice:
    post:
      operationId: oauthLegacyChoice
      summary: Redeem a legacy-handoff chooser token (issue #467)
      description: |
        Redeems the single-use token minted when a sign-in identity is
        known to both legacy Monitive and this binary — returned as
        `{"choice":"<tok>"}` by `/oauth/email/verify`, or carried in the
        `/signin/choose#choice=<tok>` fragment after a GitHub/Google
        callback's `302`.

        Requires the `X-Monitive-Client: legacy-handoff-1` header on every
        request — missing or wrong, this always answers `503
        legacy_unavailable` and the choice token is NOT taken (retryable
        with the header).

        `pick:"legacy"` returns the same `{"handoff":{"action","token"}}`
        shape `/oauth/email/verify` returns for a legacy-only identity (on
        the email path, consuming the underlying challenge first, still
        creating no account). `pick:"new"` runs the ordinary sign-in the
        person chose and returns `{"redirect_to"}`.

        Mounted only when legacy-handoff routing is configured — `404`
        otherwise.
      tags: [OAuth]
      security: []
      parameters:
        - name: X-Monitive-Client
          in: header
          required: true
          schema:
            type: string
            enum: [legacy-handoff-1]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [choice, pick]
              properties:
                choice:
                  type: string
                pick:
                  type: string
                  enum: [legacy, new]
      responses:
        "200":
          description: The chosen path's result.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    properties:
                      redirect_to:
                        type: string
                        format: uri
                  - type: object
                    properties:
                      handoff:
                        type: object
                        properties:
                          action:
                            type: string
                            format: uri
                          token:
                            type: string
        "401":
          description: Unknown, already-used, or expired choice token.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: The resolved account is suspended (pick:new only).
        "404":
          description: Legacy-handoff routing not configured.
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "503":
          description: Missing/wrong capability header, or the chosen path otherwise failed closed.
  /oauth/company-domain/choice:
    post:
      operationId: oauthCompanyDomainChoice
      summary: Redeem a company-domain gate token (issue #471)
      description: |
        Redeems the single-use token minted when a freshly verified
        email's domain already belongs to another member — returned as
        `{"company_domain":{"domain","choice"}}` by
        `/oauth/email/verify`, or carried in the
        `/signin/company#choice=<tok>&domain=<domain>` fragment after a
        GitHub/Google callback's `302`. A SEPARATE token space from
        `/oauth/legacy/choice` — a legacy token here, or a
        company-domain token there, both `401`.

        `pick:"new"` runs the ordinary, account-creating sign-in the
        person chose and returns `{"redirect_to"}`, same shape as every
        other sign-in front door. `pick:"other"` returns `204` with
        nothing created and the token burned; for an email-backed token
        this also consumes the underlying email challenge first, so the
        original link/code can't be replayed into a second choice or a
        sign-in — a transient failed consume leaves the token live and
        returns `503` instead, so the same request can be retried rather
        than being told the abort succeeded while the credential is still
        usable; if the token's own (shorter) deadline has already passed
        by the time the failure is reported, it is burned instead and
        `401` is returned, since a retry would be refused as expired
        anyway. No capability header is required (unlike
        `/oauth/legacy/choice` — this feature has no fake-legacy-server
        contract to protect).

        Mounted only when the gate is configured
        (`COMPANY_DOMAIN_MATCH_ENABLED`) — `404` otherwise.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [choice, pick]
              properties:
                choice:
                  type: string
                pick:
                  type: string
                  enum: [new, other]
      responses:
        "200":
          description: pick:"new" succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  redirect_to:
                    type: string
                    format: uri
        "204":
          description: pick:"other" — nothing created.
        "401":
          description: Unknown, already-used, or expired choice token; also returned for a legacy token presented here. Also returned for pick:"other" when the underlying email challenge's consume outcome is unknown (the commit may have actually succeeded) — the token is burned rather than retried, since a retry would otherwise redeem an already-dead challenge. Also returned for pick:"other" when a transient consume failure is reported after the token's own deadline has already passed — burned rather than restored, since the promised retry would be refused as expired anyway.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: The resolved account is suspended (pick:new only).
        "404":
          description: Company-domain gate not configured.
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "503":
          description: pick:"other" failed to consume the underlying email challenge with a confirmed-not-committed error; the token is still live and the request can be retried.
  /.well-known/oauth-protected-resource:
    get:
      operationId: oauthPRMRoot
      summary: Root protected resource metadata for /mcp (RFC 9728)
      description: |
        Returns the same host-aware protected-resource metadata document as
        `/.well-known/oauth-protected-resource/mcp`. MCP clients use this root
        path as the RFC 9728 fallback when they don't follow the suffixed URL
        from the `WWW-Authenticate` challenge.
      tags: [OAuth]
      security: []
      responses:
        "200":
          description: Protected resource metadata document.
          content:
            application/json:
              schema:
                type: object
                required:
                  - resource
                  - authorization_servers
                  - bearer_methods_supported
                  - scopes_supported
                  - resource_documentation
                properties:
                  resource:
                    type: string
                    format: uri
                    example: https://api.monitive.com/mcp
                  authorization_servers:
                    type: array
                    items:
                      type: string
                      format: uri
                    example: ['https://api.monitive.com']
                  bearer_methods_supported:
                    type: array
                    items:
                      type: string
                    example: [header]
                  scopes_supported:
                    type: array
                    items:
                      type: string
                    example: [mcp]
                  resource_documentation:
                    type: string
                    format: uri
                    example: https://monitive.com/docs/mcp/
        "404":
          description: OAuth AS not configured (OAUTH_SIGNING_KEY_PEM_FILE unset).
  /.well-known/oauth-protected-resource/mcp:
    get:
      operationId: oauthPRM
      summary: Protected resource metadata for /mcp (RFC 9728)
      description: |
        Returns the protected-resource metadata document for the `/mcp`
        endpoint. MCP clients fetch this to discover the authorization
        server URL.
      tags: [OAuth]
      security: []
      responses:
        "200":
          description: Protected resource metadata document.
          content:
            application/json:
              schema:
                type: object
                required:
                  - resource
                  - authorization_servers
                  - bearer_methods_supported
                  - scopes_supported
                  - resource_documentation
                properties:
                  resource:
                    type: string
                    format: uri
                    example: https://api.monitive.com/mcp
                  authorization_servers:
                    type: array
                    items:
                      type: string
                      format: uri
                    example: ['https://api.monitive.com']
                  bearer_methods_supported:
                    type: array
                    items:
                      type: string
                    example: [header]
                  scopes_supported:
                    type: array
                    items:
                      type: string
                    example: [mcp]
                  resource_documentation:
                    type: string
                    format: uri
                    example: https://monitive.com/docs/mcp/
        "404":
          description: OAuth AS not configured (OAUTH_SIGNING_KEY_PEM_FILE unset).
  /.well-known/oauth-authorization-server:
    get:
      operationId: oauthASMetadata
      summary: Authorization server metadata (RFC 8414)
      description: |
        Returns the authorization-server metadata document. Advertises all
        OAuth 2.1 endpoints (registration, authorize, token, keys, revoke),
        supported grants, response types, code-challenge methods, and
        token-endpoint auth methods.
      tags: [OAuth]
      security: []
      responses:
        "200":
          description: Authorization server metadata document.
          content:
            application/json:
              schema:
                type: object
                required:
                  - issuer
                  - authorization_endpoint
                  - token_endpoint
                  - registration_endpoint
                  - revocation_endpoint
                  - jwks_uri
                  - response_types_supported
                  - grant_types_supported
                  - code_challenge_methods_supported
                  - token_endpoint_auth_methods_supported
                  - scopes_supported
                  - service_documentation
                properties:
                  issuer:
                    type: string
                    format: uri
                  authorization_endpoint:
                    type: string
                    format: uri
                  token_endpoint:
                    type: string
                    format: uri
                  registration_endpoint:
                    type: string
                    format: uri
                  revocation_endpoint:
                    type: string
                    format: uri
                  jwks_uri:
                    type: string
                    format: uri
                  response_types_supported:
                    type: array
                    items: {type: string}
                  grant_types_supported:
                    type: array
                    items: {type: string}
                  code_challenge_methods_supported:
                    type: array
                    items: {type: string}
                  token_endpoint_auth_methods_supported:
                    type: array
                    items: {type: string}
                  scopes_supported:
                    type: array
                    items: {type: string}
                  service_documentation:
                    type: string
                    format: uri
                    example: https://monitive.com/docs/mcp/
        "404":
          description: OAuth AS not configured (OAUTH_SIGNING_KEY_PEM_FILE unset).
  /.well-known/http-message-signatures-directory:
    get:
      operationId: webBotAuthKeyDirectory
      summary: Probe signing key directory (Web Bot Auth)
      description: |
        The JWKS of the probe signing public keys (Ed25519 only), which
        Cloudflare fetches to verify Monitive's probes under its
        verified-bots request-signature method (Web Bot Auth, issue #557).
        It lists one key, or two during a rotation overlap: the current
        key first.

        Each response is signed per RFC 9421 by every listed key, with one
        `binding<n>` entry per key in both `Signature-Input` and
        `Signature`. Each signature covers only `("@authority";req)` (the
        request's `Host`, lowercased, with the default port removed) and
        carries the parameters `alg="ed25519"`, `keyid` (the key's RFC 7638
        JWK SHA-256 thumbprint), a fresh `nonce`,
        `tag="http-message-signatures-directory"`, `created`, and
        `expires` (`created` + 300 seconds), in that order. Each response
        is signed afresh, so it is sent with `Cache-Control: no-store`.

        No authentication. Only GET is served; HEAD is not.
      tags: [Public]
      security: []
      responses:
        "200":
          description: The signed key directory.
          headers:
            Signature-Input:
              description: |
                One RFC 9421 entry per listed key, for example
                `binding0=("@authority";req);alg="ed25519";keyid="<thumbprint>";nonce="<nonce>";tag="http-message-signatures-directory";created=1750105829;expires=1750106129`.
              schema:
                type: string
            Signature:
              description: One `binding<n>=:<base64 Ed25519 signature>:` entry per listed key.
              schema:
                type: string
            Cache-Control:
              description: Always `no-store`, because each response carries a fresh nonce and timestamps.
              schema:
                type: string
          content:
            application/http-message-signatures-directory+json:
              schema:
                type: object
                required: [keys]
                properties:
                  keys:
                    type: array
                    minItems: 1
                    maxItems: 2
                    items:
                      type: object
                      required: [kty, crv, x]
                      properties:
                        kty:
                          type: string
                          enum: [OKP]
                        crv:
                          type: string
                          enum: [Ed25519]
                        x:
                          type: string
                          description: Unpadded base64url of the raw 32-byte public key.
              example:
                keys:
                  - kty: OKP
                    crv: Ed25519
                    x: JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs
        "400":
          $ref: "#/components/responses/BadRequest"
        "404":
          description: Key directory not configured (WEB_BOT_AUTH_PRIVATE_KEY unset).
        "405":
          $ref: "#/components/responses/MethodNotAllowed"
        "500":
          $ref: "#/components/responses/InternalError"
  /locations:
    get:
      operationId: listProbeLocations
      summary: Probe IP address list
      description: |
        The IPv4 addresses Monitive's probes send checks from, for
        customers who allowlist them (issue #563). The list holds every
        enabled probe in the `probes` table, each address once, IPv4 only,
        sorted numerically by octet. Disabled probes are not listed.

        The format matches Monitive Classic's
        `https://api-eu.monitive.com/locations`, so a consumer switches by
        changing the host: `text/plain; charset=utf-8`, one address per
        line, each line ending in `\n`, and nothing else in the body. With
        no enabled probe, the response is `200` with an empty body.

        The table is read on every request, so a probe change shows up
        without a restart once caches expire.

        No authentication. Only GET is served; HEAD is not.
      tags: [Public]
      security: []
      responses:
        "200":
          description: The probe IP list, as `text/plain; charset=utf-8`.
          headers:
            Cache-Control:
              description: Always `public, max-age=300`.
              schema:
                type: string
          content:
            text/plain:
              schema:
                type: string
              example: "192.0.2.1\n198.51.100.9\n"
        "405":
          $ref: "#/components/responses/MethodNotAllowed"
        "500":
          $ref: "#/components/responses/InternalError"
  /oauth2/register:
    post:
      operationId: oauthRegister
      summary: Dynamic client registration (RFC 7591)
      description: |
        Register a new OAuth client. Returns a `client_id` (and `client_secret`
        for confidential clients). Public clients (PKCE-only) set
        `token_endpoint_auth_method: "none"` and receive no secret.

        Anyone may register a client. Holding a `client_id` confers no
        privilege without a successful authorize flow.

        Rate limited per caller IP (10/hour), counting every JSON attempt
        presented to it, not just successes, plus a 100/hour process-wide
        backstop that counts only attempts the per-IP limiter admits — a
        request the per-IP limiter rejects does not consume backstop
        capacity. `Content-Type` must be `application/json` — checked before
        either limiter is consulted, so a non-JSON request spends neither
        limiter's capacity. Clients that never complete a token grant are
        deleted after 30 days.

        Each `redirect_uris` entry must be loopback `http` (`127.0.0.1`,
        `[::1]`, `localhost`), a reverse-DNS custom scheme, or `https` on an
        approved host (`claude.ai`, `chatgpt.com`, `glama.ai`; exact host
        match, no subdomains). Web-hosted MCP clients need approval; contact
        hello@monitive.com.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: |
                All string fields must be valid UTF-8 with no null bytes.
                URL fields (`client_uri`, `redirect_uris[]`) must additionally
                be free of ASCII control characters (U+0000..U+001F, U+007F).
                Violations return HTTP 400 with the RFC 7591 envelope
                `{"error":"invalid_client_metadata","error_description":"…"}`.
              required: [redirect_uris]
              properties:
                client_name:
                  type: string
                client_uri:
                  type: string
                  format: uri
                redirect_uris:
                  type: array
                  items: {type: string, format: uri}
                grant_types:
                  type: array
                  items: {type: string}
                  default: [authorization_code, refresh_token]
                response_types:
                  type: array
                  items: {type: string}
                  default: [code]
                token_endpoint_auth_method:
                  type: string
                  enum: [none, client_secret_post, client_secret_basic]
                  default: none
                scope:
                  type: string
                  default: mcp
      responses:
        "201":
          description: Client registered.
          content:
            application/json:
              schema:
                type: object
                properties:
                  client_id:
                    type: string
                  client_secret:
                    type: string
                    description: Returned only for confidential clients; shown once.
                  client_id_issued_at:
                    type: integer
                  redirect_uris:
                    type: array
                    items: {type: string}
                  grant_types:
                    type: array
                    items: {type: string}
                  response_types:
                    type: array
                    items: {type: string}
                  token_endpoint_auth_method:
                    type: string
                  scope:
                    type: string
        "400":
          description: |
            `invalid_client_metadata` (invalid metadata) or
            `invalid_redirect_uri` (a redirect URI is invalid or its `https`
            host is not approved; the description names the host).
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          description: |
            Rate limit exceeded — either the per-IP cap (10/hour) or the
            process-wide backstop (100/hour), whichever rejected first (the
            backstop is checked before the per-IP limiter). `Retry-After` is
            the ceiling of the remaining window in seconds (never truncated,
            so a 2.8s wait renders as `3`, not `2` — unlike `/feed/{token}`'s
            handler, which truncates).
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds until the rejecting limiter's window resets, rounded up.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  error_description:
                    type: string
              example:
                error: too_many_requests
                error_description: too many client registrations from this address; retry later
  /oauth2/authorize:
    get:
      operationId: oauthAuthorize
      summary: OAuth 2.1 authorization endpoint
      description: |
        Initiates the authorization-code flow (PKCE S256 mandatory). When
        the user has no active dispatcher session, redirects to the sign-in
        page — `OAUTH_LOGIN_URL` when the operator has set it (with
        `return_to=<finalize>` appended to that URL's own query), else the
        pre-#315 GitHub-only bridge (`/oauth/github/login?return_to=...`) —
        and resumes via `/oauth2/authorize/finalize` after the bridge
        completes (by GitHub callback or, when `OAUTH_LOGIN_URL` points at
        a page offering it, email sign-in). On success, redirects the
        browser to `redirect_uri` with `code` and echoed `state`.
      tags: [OAuth]
      security: []
      parameters:
        - in: query
          name: client_id
          required: true
          schema: {type: string}
        - in: query
          name: redirect_uri
          required: true
          schema: {type: string, format: uri}
        - in: query
          name: response_type
          required: true
          schema: {type: string, enum: [code]}
        - in: query
          name: code_challenge
          required: true
          schema: {type: string}
        - in: query
          name: code_challenge_method
          required: true
          schema: {type: string, enum: [S256]}
        - in: query
          name: scope
          schema: {type: string, default: mcp}
        - in: query
          name: state
          schema: {type: string}
      responses:
        "200":
          description: |
            Reserved. The endpoint always redirects (302) or errors (400);
            no 200 body is returned in normal operation.
        "302":
          description: Redirect to GitHub login or to `redirect_uri` with code/error.
        "400":
          description: |
            Invalid request (missing or invalid params). Also returned, as
            JSON and never as a redirect, as `invalid_redirect_uri` when the
            client's registered redirect URIs include a URI that is not
            allowed, such as an `https` host not on the approved list.
  /oauth2/token:
    post:
      operationId: oauthToken
      summary: OAuth 2.1 token endpoint
      description: |
        Exchanges an authorization code (with PKCE verifier) or a refresh
        token for a JWT access token + refresh token. Refresh tokens
        rotate: the presented token is revoked and a new one is returned.
        JWT claims: `iss`, `sub` (= account ID), `aud=mcp`, `exp` (~1 h),
        `iat`, `jti`, `client_id`, `scope`.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type]
              properties:
                grant_type:
                  type: string
                  enum: [authorization_code, refresh_token]
                code:
                  type: string
                redirect_uri:
                  type: string
                  format: uri
                code_verifier:
                  type: string
                refresh_token:
                  type: string
                client_id:
                  type: string
                client_secret:
                  type: string
      responses:
        "200":
          description: Token response.
          content:
            application/json:
              schema:
                type: object
                properties:
                  access_token:
                    type: string
                  token_type:
                    type: string
                    enum: [Bearer]
                  expires_in:
                    type: integer
                  refresh_token:
                    type: string
                  scope:
                    type: string
        "400":
          description: |
            `invalid_grant` / `invalid_request` / `unauthorized_client`.
            `unauthorized_client` is also returned, without consuming the
            code or revoking the refresh token, when the client's registered
            redirect URIs include a URI that is not allowed.
        "401":
          description: invalid_client.
        "500":
          description: |
            Two distinct `server_error` shapes share this status,
            distinguishable by the `error_description` body:

            1. **Generic pre-persistence failure** — token minting (JWT
               signing, random token generation) failed before any commit
               was attempted. `error_description: "could not mint tokens"`.
               No authorization code was consumed and no refresh token was
               revoked; safe to retry with the same grant.
            2. **Commit outcome unknown** (e.g. a connection drop
               mid-commit) — the presented authorization code or refresh
               token may already be consumed/revoked even though this
               request failed. `error_description` explicitly says the
               outcome is unknown and tells the client to restart the
               authorization flow. This is an advisory distinction, not an
               RFC 6749 retry guarantee (RFC 6749 does not classify
               `server_error` as non-retryable, and OAuth client libraries
               commonly auto-retry any 5xx regardless of the `error`
               field) — resending the same grant after this response can
               fail with `invalid_grant` if the ambiguous commit actually
               landed, but this API cannot force a well-behaved client to
               avoid that resend.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    enum: [server_error]
                  error_description:
                    type: string
              examples:
                genericFailure:
                  summary: Generic pre-persistence failure (no grant consumed)
                  value:
                    error: server_error
                    error_description: could not mint tokens
                commitOutcomeUnknown:
                  summary: Commit outcome unknown (grant may already be consumed)
                  value:
                    error: server_error
                    error_description: >-
                      token issuance outcome unknown; the authorization code may already be consumed; restart the authorization flow
        "503":
          description: |
            `temporarily_unavailable` — a transient backend error left the
            presented code/refresh token untouched (the transaction rolled
            back). Safe to retry.
  /oauth2/revoke:
    post:
      operationId: oauthRevoke
      summary: OAuth 2.1 token revocation (RFC 7009)
      description: |
        Revokes an access or refresh token belonging to the authenticated
        client. Always responds 200 for tokens owned by the caller, even
        when the token is already gone (RFC 7009 §2.2 anti-probing). Token
        type is advisory via `token_type_hint`; the server falls back to
        JWT shape sniffing and tries the other type if the hint misses.

        Client authentication is required (per RFC 7009): pass `client_id`
        with optional `client_secret` via HTTP Basic, `client_secret_post`
        form fields, or just `client_id` for public clients registered with
        `token_endpoint_auth_method: "none"`. Tokens belonging to a
        different client are silently ignored (still 200, anti-probing) but
        not revoked.
      tags: [OAuth]
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [token, client_id]
              properties:
                token:
                  type: string
                token_type_hint:
                  type: string
                  enum: [access_token, refresh_token]
                client_id:
                  type: string
                client_secret:
                  type: string
      responses:
        "200":
          description: Revocation request acknowledged (also returned for tokens not owned by the caller, per anti-probing).
        "400":
          description: Invalid request — missing token, malformed body.
        "401":
          description: Client authentication failed — missing/wrong client credentials.
        "503":
          description: Backend unavailable — the revocation may not have completed; the client should retry.
  /oauth2/keys:
    get:
      operationId: oauthJWKS
      summary: JSON Web Key Set
      description: |
        Returns the public RSA key used to sign JWT access tokens, in JWKS
        format. v1 publishes a single key; rotation is a planned follow-up.
      tags: [OAuth]
      security: []
      responses:
        "200":
          description: JWKS document.
          content:
            application/json:
              schema:
                type: object
                properties:
                  keys:
                    type: array
                    items:
                      type: object
                      properties:
                        kty: {type: string, enum: [RSA]}
                        alg: {type: string, enum: [RS256]}
                        use: {type: string, enum: [sig]}
                        kid: {type: string}
                        n: {type: string}
                        e: {type: string}
        "404":
          description: OAuth AS not configured (OAUTH_SIGNING_KEY_PEM_FILE unset).
  /api/v1/keys:
    get:
      operationId: listKeys
      summary: List API keys
      description: |
        Returns all API keys for the authenticated account, ordered by creation
        date (newest first). Key hashes and plaintexts are never exposed.
      tags: [Keys]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: List of API keys.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/APIKey"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      operationId: createKey
      summary: Create API key
      description: |
        Creates a new API key. The plaintext key is returned **once** in the `key`
        field — it cannot be retrieved again. Max 10 keys per account.
      tags: [Keys]
      security:
        - bearerAuth: []
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                label:
                  type: string
                  minLength: 3
                  maxLength: 100
                  description: |
                    Optional human-readable label for the key. Trimmed of
                    surrounding whitespace before persistence. Must be 3..100
                    characters after trimming, or omitted entirely.
                  example: production
      responses:
        "201":
          description: Key created. The `key` field contains the plaintext (shown once).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/APIKeyCreated"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "409":
          description: Account has reached the 10-key limit.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: key limit reached
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          description: |
            Two distinct failure shapes share this status, distinguishable
            by the `error` body:

            1. **Generic pre-persistence failure** — key material generation
               or an unclassified store error before any commit was
               attempted. Body: `{"error": "internal error"}`. No key was
               written; safe to retry.
            2. **Commit outcome unknown** (e.g. a connection drop
               mid-commit) — the message names the candidate key's ID and
               prefix; a key with that ID/prefix may or may not have been
               created. A `GET /api/v1/keys` that doesn't show it is not
               proof it was never created (a commit can become visible
               moments after a read on another connection), and this stays
               true even after waiting and listing again: negative reads
               remain inconclusive. Do not automatically create another
               key. If the candidate does appear and another usable key
               already exists, revoke the candidate directly; if it is the
               account's only key, authenticate via a dashboard session
               (not the withheld candidate) to create and verify a
               replacement first — `DELETE /api/v1/keys/{keyID}` refuses to
               remove an account's last key regardless of whether its
               plaintext was ever received.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                genericFailure:
                  summary: Generic pre-persistence failure (no key written)
                  value:
                    error: internal error
                commitOutcomeUnknown:
                  summary: Commit outcome unknown (candidate may exist)
                  value:
                    error: >-
                      key creation outcome unknown: a key with id 42 and prefix mk_live_ab12cd may or may not have been created. Listing keys and not seeing it does not prove it was not created, even after waiting and listing again — negative reads remain inconclusive. Do not automatically create another key. If it does appear and you already have another usable key, revoke the candidate directly. If it is your only key, deleting it will fail with 409 cannot delete last key: first sign in to the dashboard (GitHub OAuth session, not this key) and create a verified replacement key there, then revoke the candidate. Otherwise contact an operator to confirm the outcome before creating a replacement.
  /api/v1/keys/{keyID}:
    delete:
      operationId: deleteKey
      summary: Delete API key
      description: |
        Deletes an API key. Deletion is rejected while the account has only
        one `api_keys` row, but that guard counts raw rows, not usable
        (non-revoked) keys — a key freshly rotated out and still in its
        grace window still counts. Confirm a working replacement key before
        revoking a candidate key.
      tags: [Keys]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/keyID"
      responses:
        "204":
          description: Key deleted.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Key not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Cannot delete the last key on the account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: cannot delete last key
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/keys/{keyID}/rotate:
    post:
      operationId: rotateKey
      summary: Rotate API key
      description: |
        Creates a new key and schedules the old key for revocation after a 5-minute
        grace window. During the grace window both keys are valid. After the window,
        the old key stops working. The rotated key counts toward the 10-key limit
        during the grace period.
      tags: [Keys]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/keyID"
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                label:
                  type: string
                  minLength: 3
                  maxLength: 100
                  description: |
                    Optional label for the new key. Trimmed of surrounding
                    whitespace before persistence. Must be 3..100 characters
                    after trimming, or omitted entirely.
      responses:
        "201":
          description: New key created. The `key` field contains the plaintext (shown once).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/APIKeyCreated"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Key not found, belongs to another account, or already revoked.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Account has reached the 10-key limit.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: key limit reached
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          description: |
            Two distinct failure shapes share this status, distinguishable
            by the `error` body:

            1. **Generic pre-persistence failure** — key material generation
               or an unclassified store error before any commit was
               attempted. Body: `{"error": "internal error"}`. No rotation
               was committed — the old key is untouched; safe to retry.
            2. **Commit outcome unknown** (e.g. a connection drop
               mid-commit) — the message names the old key's ID and the
               candidate replacement's ID/prefix — the old key may already
               be revoked (entering its 5-minute grace window) and the new
               key may or may not have been created. A `GET /api/v1/keys`
               that doesn't show the new key is not proof it was never
               created, even after waiting and listing again: negative
               reads remain inconclusive. Retrying this same rotation (same
               old key ID) is safe and cannot mint a second replacement —
               it either mints exactly one new key (the ambiguous attempt
               rolled back) or fails with 404 (the ambiguous attempt
               already landed, in which case the ID/prefix named in this
               message is the real replacement). Before revoking the
               candidate, confirm you have a working replacement key —
               deletion is only rejected while the account has a single
               `api_keys` row, and that count includes an old key still in
               its post-rotation grace window, so the guard does not always
               prevent ending up without a usable key.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                genericFailure:
                  summary: Generic pre-persistence failure (no rotation committed)
                  value:
                    error: internal error
                commitOutcomeUnknown:
                  summary: Commit outcome unknown (candidate replacement may exist)
                  value:
                    error: >-
                      key rotation outcome unknown: the old key (id 41) may already be revoked and entering its 5-minute grace window, and a new key with id 42 and prefix mk_live_ab12cd may or may not have been created. Listing keys and not seeing the new key does not prove it was not created, even after waiting and listing again — negative reads remain inconclusive. Retrying this same rotation (same old key ID) is safe and will not create a second replacement: it will either succeed with exactly one new key (the first attempt rolled back) or fail with 404 key not found (the first attempt already landed — in that case the key with id 42 and prefix mk_live_ab12cd above is your real replacement; if you still need its plaintext, rotate again using that key's ID before the old key's 5-minute grace window expires). Before revoking the new key, confirm you have a working replacement: the last-key guard only blocks deletion when the account has a single api_keys row, which still counts an old key inside its grace window, so it will not always stop you from ending up without a usable key.
  /api/v1/monitors:
    get:
      operationId: listMonitors
      summary: List monitors
      description: |
        Returns all monitors for the authenticated account with current status,
        ordered by creation date (newest first). Each item also carries
        `flapping` (issue #453), mirroring `GET /monitors/{id}`'s
        `state.flapping`.
      tags: [Monitors]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: List of monitors with inline status.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/MonitorListItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "405":
          $ref: "#/components/responses/MethodNotAllowed"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      operationId: createMonitor
      summary: Create monitor
      description: |
        Creates a new uptime monitor. `type` must be `http`, `tcp`, or
        `ping`; `dns` and `ssl` are defined in the wire format but rejected
        with `400` (issue #209 — see "Invalid request" below). The
        per-account cap is the plan's `limits.max_monitors` (100 on free;
        see `GET /api/v1/account`). Duplicate URLs within the same account
        are rejected.

        `recipient_ids` (issue #329) selects which recipients the new
        monitor is created with — see `MonitorCreateInput`. Omitted or
        `null` attaches the account's default recipients (`recipients.is_default`),
        unchanged from pre-#329 behavior. An explicit array (including `[]`)
        attaches exactly that set instead: validated like
        `PUT /monitors/{id}/recipients` (positive ids, no duplicates — `400`
        before any write) and ownership-checked against the calling account
        (`400` on a foreign or nonexistent id, before the monitor-limit and
        duplicate-URL checks, so a bad id is reported even for an account
        already at its cap).

        `recipients` (issue #338) is `recipient_ids`'s alternative form,
        letting each attached pair set its own `grace_s` (the alert grace
        period, renamed from `down_delay_s` by issue #504 — `down_delay_s`
        is still accepted as a deprecated alias, equal values on both keys
        are accepted, differing values are `400`) at create time — see
        `MonitorRecipients`. Mutually exclusive with `recipient_ids`:
        specifying both is `400`. `recipients: null` is `400` (unlike
        `recipient_ids: null`, which keeps its "attach defaults" meaning).
        `grace_s` is fixed at 120 seconds on the free and complimentary
        plans — a different value is `422`, naming the fixed value; paid
        plans accept any of the 15 values (issue #593).

        The dispatcher synchronously runs an immediate test check against
        the configured URL before returning, so the create response carries
        `state.status` of `up`, `down` or `blocked` instead of `unknown`.
        `blocked` means every probe that checked the URL was answered with a
        bot-protection challenge (HTTP 403 with a challenge signature); the
        site is not reported as down, and an allowlisting notice is sent
        instead (see `monitor.blocked`). `blocked` also means the site's
        robots.txt does not allow Monitive to check the URL (issue #621); the
        check is then never sent. The check
        uses the same probe path as `POST /api/v1/monitors/{id}/test`. If
        the probe is unavailable, the kill switch is engaged, or the URL
        fails the dispatch-time SSRF guard (DNS rebind between validation
        and dispatch), the create still succeeds and `state.status` is
        `unknown` — the next scheduled tick will populate it.

        Per-account scan heuristic: a 10-minute port-fan window and a
        separate 30-minute burst host-fan window track each
        newly-created monitor — and, identically, every
        `PUT /api/v1/monitors/{monitorID}` that changes `url` or `type`
        (issue #335; see that endpoint's description) — and branches on two
        signatures:
        - **Port-fan** (≥6 distinct ports, by default — `SCAN_PORTFAN_THRESHOLD`
          — on ≤2 hosts, by default — `SCAN_PORTFAN_HOSTS`): scanner-shaped →
          account suspended (403), all monitors purged, security alert fired.
          A `tcp` monitor's port — already checked against the TCP
          allowlist below — counts toward a separate, wider ceiling,
          `SCAN_PORTFAN_TCP_THRESHOLD` (default 12, issue #331 — unset
          tracks the greater of 12 and the effective
          `SCAN_PORTFAN_THRESHOLD`); `http`/`ping` targets always trip at
          the stricter `SCAN_PORTFAN_THRESHOLD` (6), even mixed with `tcp`
          targets on the same host.
        - **Host-fan** counts distinct registrable domains (eTLD+1; IP
          literals count individually; sibling subdomains fold together).
          The inclusive 30-minute burst allowance is the account's resolved
          `limits.host_fan_threshold`: `max_monitors` by default or a valid
          complimentary override. A fixed rolling 24-hour allowance of
          `2 * max_monitors` also applies. `SCAN_WINDOW`, when explicitly
          set, overrides both short windows; `SCAN_HOSTFAN_THRESHOLD` is only
          a compatibility fallback for legacy internal calls. Exceeding
          either host allowance returns 429 + Retry-After and reports the
          allowance/window whose required expiry is later. Account is NOT
          suspended. Deletion does not free tracker capacity; repeating an
          already-counted domain remains one domain. Trackers are process-local,
          clear on restart, and are not coordinated across replicas.

        Subject to two independent per-account rate limits. A request consumes
        one token from each:
          - Global cap: 200 requests/minute on any authed `/api/v1/*` route
            (envelope: `account rate limit exceeded; retry in <N>s`).
          - Creation cap: 20 `POST /api/v1/monitors` per minute
            (envelope: `monitor creation rate limit exceeded; retry in <N>s`).
        Either rejection responds 429 with an integer `Retry-After` header.
      tags: [Monitors]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MonitorCreateInput"
      responses:
        "201":
          description: |
            Monitor created. `state.status` carries `up`, `down` or
            `blocked` (bot protection challenged the immediate test check;
            not reported as down) from the immediate test check. `unknown` indicates a best-effort skip
            (probe unavailable, kill switch active, or SSRF rebind detected
            at dispatch time); the next scheduled tick populates it.

            Soft-cap notice: when the post-insert per-account monitor count
            is strictly greater than the account's resolved
            `soft_cap_monitors` and at or below its resolved `max_monitors`
            (issue #507 — see `GET`/`PATCH /api/v1/account`'s `limits`
            object for the account's actual values; every account defaults
            to 50/100, free-plan numbers used as the example below, but a
            `complimentary` account's admin-set overrides can differ), the
            response carries an additional `notice` object (`code:
            soft_cap_reached`). Creates at or below the soft cap produce a
            response with no `notice` field at all (omitempty). A create
            that would land over `max_monitors` returns 409 (see "Monitor
            limit reached").
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitorDetail"
              examples:
                created:
                  summary: 1st-50th create on the free plan (at/below the soft cap) — no soft-cap notice
                  value:
                    monitor:
                      id: 12345
                      account_id: 42
                      name: my site
                      url: https://example.com
                      type: http
                      interval_sec: 300
                      enabled: true
                    state:
                      monitor_id: 12345
                      status: up
                    regions_degraded: false
                    effective_interval_sec: 300
                softCapReached:
                  summary: 51st create on the free plan (one past its soft cap) — soft-cap notice attached
                  value:
                    monitor:
                      id: 12651
                      account_id: 42
                      name: monitor-51
                      url: https://example.com/51
                      type: http
                      interval_sec: 300
                      enabled: true
                    state:
                      monitor_id: 12651
                      status: up
                    regions_degraded: false
                    effective_interval_sec: 300
                    notice:
                      code: soft_cap_reached
                      message: "Your plan includes 50 monitors. You can add 49 more. Email hello@monitive.com with your use case. It helps us design fair pricing."
                      monitors_current: 51
                      soft_cap: 50
                      hard_cap: 100
                tcpCreated:
                  summary: tcp monitor on a whitelisted port
                  value:
                    monitor:
                      id: 12652
                      account_id: 42
                      name: example https port
                      url: tcp://example.com:443
                      type: tcp
                      interval_sec: 60
                      enabled: true
                    state:
                      monitor_id: 12652
                      status: up
                    regions_degraded: false
                    effective_interval_sec: 60
        "400":
          description: |
            Invalid request — including an unsupported `type` (issue #209),
            a `tcp` URL using a non-whitelisted port or wrong scheme, a
            `body_match` on a `tcp` monitor, and URLs that match the public
            hostname blocklist (`.gov`, `.mil`, major social platforms,
            known critical infrastructure).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                unsupportedType:
                  summary: type is defined but not yet serviced
                  value:
                    error: "type 'ssl' is not available yet; the check engine currently supports: http, ping, tcp"
                undefinedType:
                  summary: type is not a recognized value
                  value:
                    error: "type must be one of: http, tcp, ping, dns, ssl (currently available: http, ping, tcp)"
                tcpDisallowedPort:
                  summary: tcp URL uses a non-whitelisted port
                  value:
                    error: "port 11211 is not allowed for TCP monitors; allowed ports: 21, 22, 25, 80, 110, 143, 443, 465, 587, 993, 995, 2222, 3000, 3306, 5000, 5432, 6379, 8000, 8080, 8443, 8888, 27017"
                tcpBodyMatch:
                  summary: body_match set on a tcp monitor
                  value:
                    error: "body_match is not applicable to tcp monitors"
                blocklistedHostname:
                  summary: Hostname on public blocklist
                  value:
                    error: "url rejected: hostname cdc.gov is on the public blocklist (matches .gov)"
                recipientIDsDuplicate:
                  summary: recipient_ids contains a duplicate (issue #329)
                  value:
                    error: "recipient_ids must not contain duplicates"
                recipientIDsNotPositive:
                  summary: recipient_ids contains a non-positive id (issue #329)
                  value:
                    error: "recipient_ids must all be positive"
                recipientIDsNotOwned:
                  summary: recipient_ids names an id not owned by this account (issue #329)
                  value:
                    error: "one or more recipient_ids are not owned by this account"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "422":
          description: |
            A `recipients` entry's `grace_s`/`down_delay_s` is well-shaped
            but not one of the values the account's plan allows (issue
            #504). Free and complimentary plans require `120` seconds; paid
            plans accept any of the 15 allowed values (issue #593). No
            monitor is created. Also a refused `regions` selection (issue
            #572): `[]`, an unknown or duplicate region, or selected regions
            holding fewer than 3 enabled probes in total. Nothing is
            written.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                graceNotAllowed:
                  summary: grace_s is not the fixed plan value
                  value:
                    error: "grace_s is fixed at 120 seconds on your plan"
                regionsBelowProbeMinimum:
                  summary: the selected regions hold too few probes
                  value:
                    error: "regions [SA] have 1 enabled probe; select regions with at least 3 probes in total"
                regionsEmpty:
                  summary: an empty regions array
                  value:
                    error: "regions must not be empty; omit regions or send null to check from all regions"
        "409":
          description: |
            Monitor limit reached (body `MonitorLimitError`, issue #512),
            duplicate URL, or non-GET cap (body `Error`). Clients matching
            on `error: "monitor limit reached"` keep working: the string is
            unchanged, and the extra fields are additive.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/MonitorLimitError"
                  - $ref: "#/components/schemas/Error"
              examples:
                monitorLimit:
                  summary: Account at its plan's monitor cap
                  value:
                    error: monitor limit reached
                    limit: 100
                    current: 100
                    plan: free
                    hint: "Your plan includes 50 monitors, and this account has no room for more. Email hello@monitive.com to raise the limit."
                duplicateURL:
                  summary: A monitor with this URL already exists
                  value:
                    error: a monitor with this URL already exists
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          description: |
            Rate limit exceeded. Three possible causes, distinguishable by
            `X-RateLimit-Reason` header (absent on token-bucket rejections):

            1. **Global cap** (200/min per account): `error` contains
               `"account rate limit exceeded; retry in <N>s"`.
               `X-RateLimit-Limit: 200`.
            2. **Creation cap** (20/min per account): `error` contains
               `"monitor creation rate limit exceeded; retry in <N>s"`.
               `X-RateLimit-Limit: 20`.
            3. **Host-fan**: more distinct registrable domains than the
               account's inclusive `limits.host_fan_threshold` in the
               30-minute burst window, or more than `2 * max_monitors` in
               the fixed rolling 24-hour window. Body is the `HostFanError` schema with
               `retry_after_seconds` and `limit`. `X-RateLimit-Reason:
               host_fan`. Account is NOT suspended. `X-RateLimit-Limit`/
               `X-RateLimit-Window` and the body's `limit`/`window_seconds`
               reflect the allowance and controlling window actually applied.

            The `Retry-After` header is present in all three cases (integer
            >= 1). Retry after that many seconds; for case 3 the account
            will accept the request once enough qualifying domains age out.
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds until the next allowed request.
            X-RateLimit-Limit:
              $ref: "#/components/headers/XRateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/XRateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/XRateLimitReset"
            X-RateLimit-Reason:
              schema:
                type: string
                enum: [host_fan]
              description: Present only on host-fan rejections.
            X-RateLimit-Window:
              schema:
                type: integer
              description: Sliding-window length in seconds (present on host-fan rejections).
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/HostFanError"
              examples:
                creationCap:
                  summary: Creation rate cap (20/min)
                  value:
                    error: monitor creation rate limit exceeded; retry in 2s
                hostFanBurst:
                  summary: Ninth domain exceeds an inclusive burst allowance of 8
                  value:
                    error: "too many distinct domains in a rolling window; slow monitor creation or target changes and retry"
                    limit: 8
                    window_seconds: 1800
                    retry_after_seconds: 347
                hostFanDaily:
                  summary: Daily allowance controls the retry
                  value:
                    error: "too many distinct domains in a rolling window; slow monitor creation or target changes and retry"
                    limit: 200
                    window_seconds: 86400
                    retry_after_seconds: 7200
  /api/v1/monitors/{monitorID}:
    get:
      operationId: getMonitor
      summary: Get monitor
      description: |
        Returns a monitor with its full runtime state including evidence
        buffer. The response also carries a top-level `paused_at`
        (issue #457), `null` unless the monitor is currently paused — see
        `MonitorDetail`.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "200":
          description: Monitor with state.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitorDetail"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Monitor not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
    put:
      operationId: updateMonitor
      summary: Update monitor
      description: |
        Partially updates a monitor. Only include fields you want to change.
        Unchanged fields retain their current values. An explicit
        `"type"` other than `http`, `tcp`, or `ping` is rejected with `400`
        (issue #209), the same rule `POST /api/v1/monitors` enforces;
        omitting `type` leaves the stored value untouched and re-validates
        nothing about it.

        Per-account scan heuristic (issue #335): a request that changes
        `url` or `type` is evaluated by the identical port-fan/host-fan
        heuristic `POST /api/v1/monitors` uses — see that endpoint's
        description for the exact signatures, the `SCAN_PORTFAN_TCP_THRESHOLD`
        TCP-widened ceiling, and the sliding window. A request that leaves
        both `url` and `type` unchanged never consults the heuristic at
        all. A port-fan trip returns `403` (see "Account suspended" below);
        a host-fan trip returns `429` with the same `HostFanError` body and
        headers `POST /api/v1/monitors` documents (see "Rate limit
        exceeded" below) — this endpoint's 429 never includes the
        creation-cap case, since there is no per-route creation limiter on
        `PUT`.

        Resume cap (issue #595): enabling a paused monitor (`"enabled": true`
        on a disabled monitor) is refused with `409` and a
        `MonitorLimitError` body when the account already has
        `limits.max_monitors` enabled monitors. Nothing is written. Pause a
        different monitor first to make room. Every other update — a
        rename, a pause, or an edit to a monitor that stays paused — never
        checks this cap.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MonitorInput"
      responses:
        "200":
          description: Monitor updated.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitorDetail"
        "400":
          description: |
            Invalid request — including an unsupported `type` (issue #209)
            and the same field-level and URL rules `POST /api/v1/monitors`
            enforces.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                unsupportedType:
                  summary: type is defined but not yet serviced
                  value:
                    error: "type 'ssl' is not available yet; the check engine currently supports: http, ping, tcp"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Monitor not found.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "422":
          description: |
            A refused `regions` selection (issue #572): `[]`, an unknown or
            duplicate region, or selected regions holding fewer than 3
            enabled probes in total. Checked only when `regions` is a
            non-null array, after the monitor is found (a missing monitor
            is still `404`). Nothing is written.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                regionsBelowProbeMinimum:
                  summary: the selected regions hold too few probes
                  value:
                    error: "regions [SA] have 1 enabled probe; select regions with at least 3 probes in total"
        "409":
          description: |
            Conflict. The update would enable a paused monitor while the
            account already has `limits.max_monitors` enabled monitors
            (body `MonitorLimitError`, issue #595); or (body `Error`) the
            new URL duplicates another monitor on this account, the non-GET
            cap is reached, or the monitor was modified concurrently by
            another request and retries were exhausted — retry the request
            with a fresh read in the latter case.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/MonitorLimitError"
                  - $ref: "#/components/schemas/Error"
              examples:
                resumeAtCap:
                  summary: Resuming a paused monitor at the plan's cap
                  value:
                    error: monitor limit reached
                    limit: 100
                    current: 100
                    plan: free
                    hint: "Your plan includes 50 monitors, and this account has no room for more. Email hello@monitive.com to raise the limit."
                updateConflict:
                  summary: Concurrent modification, retries exhausted
                  value:
                    error: monitor update conflict; retry the request
                duplicateURL:
                  summary: A monitor with this URL already exists
                  value:
                    error: a monitor with this URL already exists
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/MonitorUpdateRateLimited"
    delete:
      operationId: deleteMonitor
      summary: Delete monitor
      description: |
        Deletes a monitor and all associated data (recipient attachments,
        incidents, delivery log, runtime state). Attached recipients
        themselves are NOT deleted — only this monitor's attachment to
        them.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "204":
          description: Monitor deleted.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Monitor not found.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/status-pages:
    get:
      operationId: listStatusPages
      summary: List the account's group status pages (issue #642)
      description: |
        Viewer role. Returns the account's group status pages, newest first
        by `(created_at, id)`. A group status page groups several of the
        account's monitors as components; it is separate from each
        monitor's own free status page (`/monitors/{monitorID}/status-page`).
        `url` is present only while a page is published; the page token is
        never returned on its own.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: The account's group status pages.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroupList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      operationId: createStatusPage
      summary: Create a group status page (issue #642)
      description: |
        Owner role. Creates a page with a fresh token, which it keeps across
        unpublish. `published` defaults to `false` when omitted; an explicit
        `true` publishes the page at create and the response carries its
        `url`. A free or complimentary account holds one page, a paid
        account ten; the limit is counted under the account row lock and a
        create at it is `409`. `422` names the field: a title outside 1 to
        120 characters, an about text over 280 characters, a `brand_color`
        that isn't `#RRGGBB` (checked before the plan), a `brand_color` on a
        plan without branding (Pro and Business have it), or
        `show_response_times: true` on a plan without it (every paid plan
        has it). A `null` `brand_color` and `show_response_times: false` are
        always accepted. `brand_foreground` and `brand_background`, the
        retired two-color keys (issue #649), are `422`
        `unknown field: <key>`, whatever their value; every other unknown
        key is `400`. Components are set through
        `PUT /api/v1/status-pages/{pageID}/components`; a `components` key
        here is `400`, as is any other unknown key, a wrong type, a `null`
        title, `published` or `show_response_times`, and a string
        containing a null byte.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StatusPageGroupCreate"
      responses:
        "201":
          description: The created page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: The account already holds its plan's number of group status pages.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageLimitError"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            A field rule or a plan gate failed; the error names the field.
            Also sent for a retired `brand_foreground` or `brand_background`
            key.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/status-pages/{pageID}:
    parameters:
      - $ref: "#/components/parameters/pageID"
    get:
      operationId: getStatusPageGroup
      summary: Get one group status page (issue #642)
      description: |
        Viewer role. A page on another account is `404`, the same as a
        missing one.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: The page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      operationId: updateStatusPageGroup
      summary: Update a group status page (issue #642)
      description: |
        Owner role. Any non-empty subset of the create keys; only the sent
        keys change. The same `400` and `422` rules as create apply, and the
        off values (`brand_color: null`, `show_response_times: false`) are
        always accepted, so a downgraded account can clean up. A retired
        `brand_foreground` or `brand_background` key is `422`
        `unknown field: <key>`. A downgrade never deletes, unpublishes or
        edits a page.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StatusPageGroupUpdate"
      responses:
        "200":
          description: The updated page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            A field rule or a plan gate failed; the error names the field.
            Also sent for a retired `brand_foreground` or `brand_background`
            key.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      operationId: deleteStatusPageGroup
      summary: Delete a group status page (issue #642)
      description: |
        Owner role. Deletes the page and its components. The monitors, and
        their own status pages, are untouched.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      responses:
        "204":
          description: Deleted.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/status-pages/{pageID}/components:
    parameters:
      - $ref: "#/components/parameters/pageID"
    put:
      operationId: setStatusPageComponents
      summary: Replace a group status page's components (issue #642)
      description: |
        Owner role. Replaces the whole ordered list; an empty list clears
        it. A monitor can be on several pages, and adding it never publishes
        its own status page. An empty `display_name` or `group` is stored as
        `null`. `422` names the field: more than 50 components, a monitor
        listed twice or not on this account, a display name over 120
        characters, a group over 60, or a group on a plan without groups
        (every paid plan has them; `null` is always accepted).
      tags: [Status Pages]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StatusPageGroupComponentsInput"
      responses:
        "200":
          description: The updated page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            A component rule or a plan gate failed; the error names the field.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/status-pages/{pageID}/logo:
    parameters:
      - $ref: "#/components/parameters/pageID"
    put:
      operationId: setStatusPageLogo
      summary: Set a group status page's logo (issue #642)
      description: |
        Owner role, Pro and Business plans. The image is a PNG, JPEG or
        WebP, recognised by its magic bytes (SVG and every other type are
        refused), of 1 to 32,768 bytes. Bad base64 is `400`. The plan gate,
        an empty or oversize image, and an unrecognised type are `422`. The
        ordinary 64 KiB request cap still applies, so a body over it (an
        image larger than about 48 KiB) is `413`, not `422`. The response
        reports the logo's type and size, never its bytes.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StatusPageGroupLogoInput"
      responses:
        "200":
          description: The updated page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            The plan has no branding, or the image is empty, over 32,768
            bytes, or not a PNG, JPEG or WebP.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      operationId: deleteStatusPageLogo
      summary: Remove a group status page's logo (issue #642)
      description: |
        Owner role, on every plan, so a downgraded account can clean up.
        Idempotent: a page with no logo also returns `204`.
      tags: [Status Pages]
      security:
        - bearerAuth: []
      responses:
        "204":
          description: Removed, or there was no logo.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Status page not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/incidents:
    get:
      operationId: listIncidents
      summary: List incidents
      description: |
        Two modes, chosen by which query keys are present (issue #418).

        **Cursor list** — selected when any of `cursor`, `filter`, `monitor`
        or `tz` is present, empty values included (`?cursor=` is a first
        page). Returns `IncidentListPageResponse`:
        `{summary, days, incidents, next_cursor, as_of}`.

        - **Outages.** An outage is every incident sharing `outage_id`; its
          head is its earliest segment. An outage is ongoing when any of its
          segments is unresolved. `filter` selects whole outages by that
          state, `cause` matches the head segment's `cause_class`, and
          `monitor` (a numeric id or a monitor ref) selects one monitor.
        - **Bursts.** Two or more outages in the same section whose heads
          start in the same UTC minute form a burst; its head is its
          earliest member. Bursts change no count.
        - **Order.** Ongoing outages first, oldest first; then resolved
          outages, newest first — ordered by the head of each group (a
          burst, or a lone outage). Burst members and outage segments follow
          their head, in start order.
        - **Paging.** A page takes whole groups until it reaches `limit`, so
          it can run past `limit` to finish a burst or an outage; it never
          splits one. `next_cursor` is null on the last page. The cursor
          freezes the view at the first page: incidents created after it,
          and resolutions after it, don't change the rest of the walk, so no
          incident is skipped or repeated. New incidents appear on the next
          first page. Pass the same `filter`, `monitor` and `cause` with
          every cursor. Durations, `summary` and `days` on later pages are
          as of the first page.
        - **Retention.** The list shows outages with a segment that is open
          or resolved within the 30 days before the walk's `as_of` (its
          first page's time). That covers the rows, `days` and `summary`
          alike, under every `filter`, `cause` and `monitor`. An ongoing
          outage always appears, however old. Outages stay whole, so a
          listed outage can include segments older than 30 days. To open a
          listed row, call `GET /incidents/{id}?as_of=<the page's as_of>`,
          which applies the same cutoff, so every listed row opens. The
          window is fixed for the whole walk. Storage still holds resolved
          incidents for 95 days for uptime reports and status pages, but
          the list does not show them.
        - **Summary** counts distinct outages matching `cause` and `monitor`
          (never `filter`: `all`, `ongoing` and `resolved` return the same
          summary) inside the same 30-day window as the rows and `days`.
        - **Days** has one entry per local date (in `tz`) a resolved outage
          on the page's HEAD (its earliest segment) started on, newest
          first; an ongoing outage, pinned above the day-grouped list,
          never has a day entry, and a later segment of a multi-segment
          outage never contributes a date of its own — every row of an
          outage is listed under its head's day. An outage outside the
          window adds no day entry; an in-window outage whose head is
          older than 30 days is counted on its head's day, like its rows.
          `incidents` counts the
          resolved outages matching the filters whose head started that
          day, across the whole walk, not just the page. `down_s`/
          `maintenance_s` cover only those outages, over their full
          durations (not clipped to the day), so a resolved outage from an
          earlier day adds nothing to a later one, a 23:50–00:20 outage
          reads 1800 on its start day, and an outage whose later segment
          starts the next day still reads its whole span on the head's day
          only — the next day gets no entry for it at all.

        A request mixing a cursor-list key with `offset`, `monitor_id`,
        `type`, `started_after` or `started_before` is a 400. In this mode a
        malformed query string is a 400. A `monitor` ref with another
        account's handle, or an unknown number, is a 404; an unknown
        numeric id just matches nothing.

        **Legacy offset mode (deprecated, kept for one release)** — when none
        of those keys is present. Returns `{incidents, total, limit, offset}`
        ordered by start time, newest first. A resolved incident older than
        30 days is never returned in this mode (issue #357) — a visibility
        floor enforced at read time, independent of how long the row is
        physically kept (95 days; see internal/retention/DECISIONS.md). An
        open incident is never hidden by this floor, however old it is.

        The legacy offset mode returns each incident's onset `evidence`
        snapshot, as it did before issue #419, because um-app's live list
        still reads it from this mode. The cursor list returns no evidence.
        Neither mode returns the resolve-time `recovery_evidence` snapshot
        (issue #421); fetch it per incident with `getIncident`.
      tags: [Incidents]
      security:
        - bearerAuth: []
      parameters:
        - name: cursor
          in: query
          schema:
            type: string
          description: >-
            Cursor list. Opaque `next_cursor` from the previous page; empty or absent means the first page. A malformed value returns 400.
        - name: filter
          in: query
          schema:
            type: string
            enum: [all, ongoing, resolved]
            default: all
          description: >-
            Cursor list. Selects whole outages by outage state. Any other value, empty included, returns 400.
        - name: monitor
          in: query
          schema:
            type: string
          description: >-
            Cursor list. One monitor, as a numeric id or a monitor ref (`<handle>-<number>`). A malformed value returns 400; a ref with another handle or an unknown number returns 404.
        - name: tz
          in: query
          schema:
            type: string
            default: UTC
          description: >-
            Cursor list. IANA time zone that `days[]` groups by, for example `Europe/Bucharest`. An empty, `Local` or unknown name returns 400.
        - name: cause
          in: query
          schema:
            type: string
            enum: [dns, tls, timeout, connection, http_4xx, http_5xx, keyword]
          description: >-
            Filter by cause class (issue #419), exact match; both modes. An empty or unknown value returns 400. Legacy mode matches each incident and `total` counts only matching incidents; the cursor list matches an outage's head segment, and `summary` and `days` follow it. Incidents with no cause class can't be selected.
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
          description: >-
            Page size (1-100). Defaults to 30 in the cursor list, where a page can run past it to finish a burst or an outage, and to 50 in legacy mode.
        - name: monitor_id
          in: query
          deprecated: true
          schema:
            type: integer
            format: int64
          description: Legacy mode only. Filter by monitor ID.
        - name: type
          in: query
          deprecated: true
          schema:
            type: string
            enum: [down, flapping]
          description: Legacy mode only. Filter by incident type.
        - name: started_after
          in: query
          deprecated: true
          schema:
            type: string
            format: date-time
          description: Legacy mode only. Only incidents started after this time (RFC3339).
        - name: started_before
          in: query
          deprecated: true
          schema:
            type: string
            format: date-time
          description: Legacy mode only. Only incidents started before this time (RFC3339).
        - name: offset
          in: query
          deprecated: true
          schema:
            type: integer
            minimum: 0
            default: 0
          description: Legacy mode only. Number of items to skip.
      responses:
        "200":
          description: >-
            The cursor list (`IncidentListPageResponse`) when a cursor-list key is present, otherwise the legacy paginated list.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IncidentListPageResponse"
                  - type: object
                    description: Legacy offset mode (deprecated).
                    required: [incidents, total, limit, offset]
                    properties:
                      incidents:
                        type: array
                        items:
                          $ref: "#/components/schemas/IncidentListItem"
                      total:
                        type: integer
                        description: Total matching incidents (for pagination).
                      limit:
                        type: integer
                      offset:
                        type: integer
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Cursor list only — `monitor` is a ref that doesn't resolve on this account (`monitor not found`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          description: Internal error.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/incidents/{incidentID}:
    get:
      operationId: getIncident
      summary: Get incident
      description: |
        Returns a single incident and its timeline, assembled at read time
        (issue #423): the incident itself (with its onset `evidence` and,
        if it resolved to up, its `recovery_evidence`), the outage's alert
        deliveries, the outage's other segments, and the account's other
        incidents that started within 60 seconds of this one. Nothing is
        copied onto the incident: a delivery's `status` is read live and
        can change between two requests.

        This endpoint applies its 30-day visibility floor (issue #357) per
        outage (issue #449): an incident opens when its outage — every
        row on the account sharing its outage id, itself included — has a
        segment that is open or resolved within 30 days of the anchor.
        The anchor is the `as_of` query parameter when given and no more
        than 24 hours old, else the request time. Pass the cursor list
        page's `as_of` within 24 hours of receiving it when opening a
        listed row, and every row that page lists opens; without it, or
        once it is more than 24 hours old, a row from an older walk can
        404. An outage resolved entirely more than 30 days before the
        anchor 404s as if it did not exist. The floor and the anchor also
        apply to `segments` and `related_incidents`. Another account's
        incident 404s, by numeric id and by ref alike.
      tags: [Incidents]
      security:
        - bearerAuth: []
      parameters:
        - name: incidentID
          in: path
          required: true
          schema:
            type: string
            pattern: "^([0-9]+|[0-9a-hjkmnp-tv-z]{6}-[1-9][0-9]*)$"
          description: >-
            Numeric incident id or ref (issue #412), e.g. "k7q2mx-3". A ref whose handle belongs to a different account, or whose number doesn't resolve, 404s the same as a nonexistent numeric id.
        - name: as_of
          in: query
          schema:
            type: string
            format: date-time
          description: >-
            Optional RFC3339 anchor for the 30-day visibility floor (issue #449): pass the cursor list page's `as_of` (URL-encoded) when opening a listed row, so the floor uses that walk's exact cutoff and every listed row opens. Omitted, the floor anchors at the request time. A value in the future is a 400 (`as_of must not be in the future`), as is an unparsable or empty value (`invalid as_of (use RFC3339)`). The floor applies per outage, to `segments` and `related_incidents` too. A value older than 24 hours before the server's current time is silently ignored — treated the same as an omitted parameter, not rejected — so it cannot widen the floor toward the 95-day physical retention (issue #449 fold, 2026-11-05); it anchors the floor only — the body is always read live.
      responses:
        "200":
          description: Incident details and timeline.
          content:
            application/json:
              schema:
                type: object
                required: [incident, deliveries, segments, related_incidents]
                properties:
                  incident:
                    description: >-
                      The incident, in the shape `GET /incidents`' legacy offset mode lists (`IncidentListItem`), not the cursor list's `IncidentPageItem`. Its onset `evidence` and, if this segment resolved to up, its `recovery_evidence` live here.
                    allOf:
                      - $ref: "#/components/schemas/IncidentDetail"
                  deliveries:
                    type: array
                    description: >-
                      This account's alert deliveries (every recipient type) whose outage matches the incident's `outage_id`, ordered by `created_at` ascending, then id. At most 100 rows, with no pagination. Read live, so `status` may change between requests. Always present; `[]` when empty.
                    items:
                      $ref: "#/components/schemas/WebhookDelivery"
                  segments:
                    type: array
                    description: >-
                      The other incidents of the same outage (same `outage_id`) on the same monitor, excluding this one, ordered by `started_at` ascending, then id. Each carries its own `evidence` and `recovery_evidence`, so opening any segment shows the outage's onset and recovery evidence. Under the same per-outage 30-day floor and anchor as the incident; at most 100 rows. Always present; `[]` for a single-segment outage.
                    items:
                      $ref: "#/components/schemas/Incident"
                  related_incidents:
                    type: array
                    description: >-
                      Incidents on this account, on any monitor, whose `started_at` is within 60 seconds either side of this incident's (inclusive), excluding this incident's own outage — so nothing here also appears in `segments`. Ordered by `started_at` ascending, then id. Under the same per-outage 30-day floor and anchor as the incident; at most 100 rows. Always present; `[]` when empty.
                    items:
                      $ref: "#/components/schemas/Incident"
        "400":
          description: >-
            Invalid request. `invalid incident ID` (non-numeric id, checked first), `invalid as_of (use RFC3339)` (empty or unparsable `as_of`), or `as_of must not be in the future` (an `as_of` after the server's current time, refused before any read).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Incident not found.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          description: Internal error.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/incidents/{incidentID}/acknowledge:
    post:
      operationId: acknowledgeIncident
      summary: Acknowledge an incident's outage (issue #420)
      description: |
        Acknowledges the whole outage the incident belongs to — every
        incident sharing its `outage_id`, across a down-to-flapping handoff
        included — on behalf of the calling user (the session user, the JWT
        user, or an API key's creator). Viewer role and above.

        Sets `acknowledged_at` and `acknowledged_by` on every still-unacked
        row of the outage. Idempotent: a second acknowledgement, by any
        member, is a no-op that keeps the first ack (first ack wins), and
        the response still carries it. A resolved outage may be
        acknowledged through the API (the signed emailed link is the one
        refused after resolve). An acknowledgement is a marker only until
        reminder alerts exist: it stops nothing today, and the recovery
        ("up") alert is always sent.

        Side effects: the acknowledgement write only — no audit row, no SSE
        event, no alert.
      tags: [Incidents]
      security:
        - bearerAuth: []
      parameters:
        - name: incidentID
          in: path
          required: true
          schema:
            type: string
            pattern: "^([0-9]+|[0-9a-hjkmnp-tv-z]{6}-[1-9][0-9]*)$"
          description: >-
            Numeric incident id or ref (issue #412), e.g. "k7q2mx-3". A ref whose handle belongs to a different account, or whose number doesn't resolve, 404s the same as a nonexistent numeric id.
      responses:
        "200":
          description: The incident, re-read after the write, carrying the outage's (first) acknowledgement.
          content:
            application/json:
              schema:
                type: object
                required: [incident]
                properties:
                  incident:
                    $ref: "#/components/schemas/Incident"
        "400":
          description: '`invalid incident ID` (non-numeric id, checked first).'
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: >-
            The account is suspended, or the calling user holds no membership on the account (`forbidden`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: >-
            Incident not found — a missing incident, another account's incident, or an outage entirely past the 30-day visibility floor, the same rule `GET /incidents/{incidentID}` applies.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          description: Internal error.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/me:
    get:
      operationId: getMe
      summary: Get the signed-in user's identities
      description: |
        Works with any authentication method (session, API key, or OAuth
        JWT) — keys off the request's resolved user, not the account. `401`
        if no user could be resolved at all.

        The response shape (issue #325) depends on the credential:
        - A dashboard **session** gets the full cross-account view:
          `memberships` lists EVERY account the user belongs to,
          `current_account_id` is the account this request authenticated
          against, and `default_account_id` is the user's own stored
          default (`null` if unset).
        - An **API key** or **OAuth JWT** gets only the CURRENT account's
          own entry in `memberships` (never another account) and
          `current_account_id`; `default_account_id` is **omitted
          entirely**, not merely `null` — neither credential may enumerate
          the user's other accounts or observe the user-global default.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Identity presence for the resolved user.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    format: int64
                  github_username:
                    type: ["string", "null"]
                  email:
                    type: ["string", "null"]
                  has_google:
                    type: boolean
                  has_microsoft:
                    type: boolean
                  display_name:
                    description: >-
                      The stored real name (issue #495) — the provider's `name` claim at a GitHub/Google/Microsoft sign-in or identity link, cleaned and capped at 200 characters. `null` until a sign-in or link has supplied one.
                    type: ["string", "null"]
                  initials:
                    description: >-
                      Display initials derived from `display_name` when set, else from the same handle (`github_username`, falling back to the local part of `email`) an incident acknowledgement's `initials` uses — the two are always consistent for the same user.
                    type: string
                  current_account_id:
                    type: integer
                    format: int64
                  default_account_id:
                    description: Present only for a dashboard session.
                    type: ["integer", "null"]
                    format: int64
                  memberships:
                    type: array
                    items:
                      type: object
                      properties:
                        account_id:
                          type: integer
                          format: int64
                        handle:
                          type: string
                          description: >-
                            The account's six-character ref-prefix (issue #412), e.g. "k7q2mx".
                        label:
                          type: string
                          description: |
                            The account's earliest owner's `github_username`
                            when non-empty, else `"account <id>"` — never an
                            email address.
                        role:
                          type: string
                          enum: [owner, member, viewer]
                        suspended:
                          type: boolean
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/me/account:
    post:
      operationId: switchAccount
      summary: Switch the signed-in session's current account
      description: |
        Session-only, but returns `422 {"error":"session_required"}` for a
        non-session caller — deliberately NOT the `403` every other
        session-only route in this file uses, per issue #325's acceptance
        criteria. Re-validates `account_id` as a current, non-suspended
        membership for the caller (`403 {"error":"forbidden"}` on either
        failure), persists it as the user's new default, and moves the
        session's own current account — both under one per-session mutex,
        so two concurrent switches on the same token can't leave the
        session and the durable default disagreeing. A session token that
        vanishes (logout, expiry) between the start of the switch and the
        session update returns `401`; the database write has already
        landed and is not undone.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [account_id]
              properties:
                account_id:
                  type: integer
                  format: int64
      responses:
        "200":
          description: Switched.
          content:
            application/json:
              schema:
                type: object
                properties:
                  account_id:
                    type: integer
                    format: int64
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          description: The session token vanished mid-switch.
        "403":
          description: Target is not a current membership, or is suspended.
        "422":
          description: Caller did not authenticate via a dashboard session.
  /api/v1/account/discard-empty:
    post:
      operationId: discardEmptyAccount
      summary: Discard the caller's own account if it is still empty (issue #471, part 2)
      description: |
        Session-only — `403 {"error":"session_required"}` for an API key
        or OAuth JWT (the ordinary `auth.RequireSession` 403, not
        `/api/v1/me/account`'s own `422`). Owner-gated (`403
        {"error":"forbidden"}` for a non-owner session). Always ends the
        calling session first — before the owner check — so a non-owner's
        `403` and a successful discard alike invalidate the token; a
        follow-up request with the same token gets `401`.

        Deletes the account only if it is still genuinely empty: zero
        monitors, zero members other than the caller, and zero unexpired
        invites. Responds `200 {"deleted":true}` on an actual delete,
        `200 {"deleted":false}` when the account still exists but fails a
        precondition — this is not an error. The `users` row is kept; on
        the next sign-in, the person has no membership and the
        company-domain gate (if configured) or an ordinary fresh account
        applies, same as any first sign-in.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Discard attempted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: boolean
        "403":
          description: Not a dashboard session, or not an owner.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/account/attribution:
    post:
      operationId: setAccountAttribution
      summary: Store the sign-up's marketing attribution, once (issue #510)
      description: |
        um-app calls this once, right after the first sign-in, with the
        attribution the marketing site recorded (the `mnv_attr` cookie or
        `_a` query parameter). The field set and limits are exactly legacy
        Monitive core's `teams.attribution`, so the two map one to one.

        Session-only — `403 {"error":"session_required"}` for an API key
        or an OAuth JWT. Owner-gated — `403 {"error":"forbidden"}` for a
        non-owner session. Neither 403 spends account rate-limit quota,
        with one exception: an API key the pre-authentication cache
        already recognizes is charged before authentication runs, so it
        spends quota and, once the account's bucket is exhausted, gets
        `429` instead of the `403`.

        Write-once: the value is stored only if the account has none yet
        AND was created less than 24 hours ago (by server time). Otherwise
        nothing changes and the response is `200 {"stored": false}` — the
        documented "done" status; treat it exactly like `true`. On a
        store, an `account.attribution_set` event is written (payload:
        the stored field names only, never values).

        Validation runs before the write-once check, so an invalid body is
        always `422`, even on an account that already has attribution.
        Unknown keys are dropped silently. A known key set to `null`, or a
        string that is blank after trimming, counts as absent. String
        lengths are counted in Unicode characters after trimming; a NUL
        character is rejected. A body with no accepted field left is
        `422 {"error":"no attribution field provided"}`.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              description: |
                Only the properties below are read; any other key is
                dropped silently.
              properties:
                referrer:
                  type: ["string", "null"]
                  maxLength: 2048
                utm_source:
                  type: ["string", "null"]
                  maxLength: 255
                utm_medium:
                  type: ["string", "null"]
                  maxLength: 255
                utm_campaign:
                  type: ["string", "null"]
                  maxLength: 255
                utm_content:
                  type: ["string", "null"]
                  maxLength: 255
                utm_term:
                  type: ["string", "null"]
                  maxLength: 255
                landing_page:
                  type: ["string", "null"]
                  maxLength: 2048
                first_visit:
                  type: ["string", "null"]
                  format: date-time
                  description: |
                    RFC 3339 timestamp, not before `2000-01-01T00:00:00Z`
                    and not in the future. Stored normalized to UTC.
                visit_count:
                  type: ["integer", "null"]
                  format: int64
                  minimum: 1
                  description: A JSON integer literal (no fraction, no exponent, not a string).
      responses:
        "200":
          description: |
            `stored: true` — this call stored the attribution.
            `stored: false` — nothing changed, because attribution was
            already stored or the account is at least 24 hours old; this
            is the documented "done" status.
          content:
            application/json:
              schema:
                type: object
                required: [stored]
                properties:
                  stored:
                    type: boolean
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: |
            `session_required` for an API key or OAuth JWT, `forbidden`
            for a non-owner session, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            Validation failed: a known field of the wrong JSON type, a
            string over its limit, a NUL character, a `first_visit` that is
            not RFC 3339, before 2000-01-01, or in the future, a
            `visit_count` that is not an integer of at least 1, or no
            accepted field at all. Nothing is stored.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/billing:
    get:
      operationId: getBilling
      summary: Paddle settings and paid plan prices for the checkout (issue #597)
      description: |
        What um-app needs to open Paddle.js and show the paid plans: the
        Paddle environment, the client-side token, and the six plan and
        interval entries with their Paddle price IDs and monitor caps. The
        client token and price IDs are publishable values Paddle.js needs
        at runtime; um-app reads them here, never from its bundle.

        Every role, on a dashboard session or an API key (an OAuth JWT gets
        `401`, as on every REST route). `404` — the same plain body an
        unknown path gets — when billing is off for the account (see
        `billing_enabled` on `GET /api/v1/account`) or when this deployment
        has no Paddle settings. Sends no request to Paddle.
      tags: [Billing]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: |
            `plans` always holds six entries, in the order basic/month,
            basic/year, pro/month, pro/year, business/month, business/year.
          content:
            application/json:
              schema:
                title: BillingInfo
                type: object
                required: [environment, client_token, plans]
                properties:
                  environment:
                    type: string
                    enum: [sandbox, live]
                    description: Paddle's environment, for `Paddle.Environment.set()`.
                  client_token:
                    type: string
                    description: Paddle's client-side token, for `Paddle.Initialize()`.
                  plans:
                    type: array
                    items:
                      title: BillingPlan
                      type: object
                      required: [plan, interval, price_id, soft_cap_monitors, max_monitors]
                      properties:
                        plan:
                          type: string
                          enum: [basic, pro, business]
                        interval:
                          type: string
                          enum: [month, year]
                        price_id:
                          type: string
                          description: The configured Paddle price ID (`pri_…`).
                        soft_cap_monitors:
                          type: integer
                          description: The plan's advertised monitor count.
                        max_monitors:
                          type: integer
                          description: The plan's hard monitor cap.
              example:
                environment: sandbox
                client_token: test_0123456789abcdef
                plans:
                  - {plan: basic, interval: month, price_id: pri_01basicmonth, soft_cap_monitors: 100, max_monitors: 200}
                  - {plan: basic, interval: year, price_id: pri_01basicyear, soft_cap_monitors: 100, max_monitors: 200}
                  - {plan: pro, interval: month, price_id: pri_01promonth, soft_cap_monitors: 250, max_monitors: 500}
                  - {plan: pro, interval: year, price_id: pri_01proyear, soft_cap_monitors: 250, max_monitors: 500}
                  - {plan: business, interval: month, price_id: pri_01businessmonth, soft_cap_monitors: 1000, max_monitors: 2000}
                  - {plan: business, interval: year, price_id: pri_01businessyear, soft_cap_monitors: 1000, max_monitors: 2000}
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Billing is off for this account, or Paddle is not configured.
          content:
            text/plain:
              schema:
                type: string
                example: "404 page not found"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
  /api/v1/billing/checkout:
    post:
      operationId: createBillingCheckout
      summary: Create a Paddle checkout transaction for the account (issue #597)
      description: |
        Creates a Paddle transaction for one paid plan and interval, bound
        to the calling account, and returns its ID; um-app opens it with
        `Paddle.Checkout.open({transactionId})`. The server sets the price,
        the Paddle customer and `custom_data.account_id`, so a browser can
        never attach a purchase to another account. Nothing about the
        account's plan changes here: a completed purchase is applied later,
        from Paddle's webhooks.

        Session-only — `403 {"error":"session_required"}` for an API key
        or an OAuth JWT. Owner-gated — `403 {"error":"forbidden"}` for a
        member or viewer session. Neither 403 spends account rate-limit
        quota, with the same pre-authentication-cache exception as
        `POST /api/v1/account/attribution`. Then, in order:

        1. `404` (plain body) when billing is off for the account, before
           the body is read; also when this deployment has no Paddle
           settings.
        2. `400 {"error":"invalid plan or interval"}` unless `plan` is
           exactly `basic`, `pro` or `business` and `interval` exactly
           `month` or `year`.
        3. The account's Paddle customer is reused when one is stored.
           Otherwise the customer holding the signed-in owner's verified
           email is found in Paddle, or created with that email only, and
           stored for the account. An owner with no verified email gets
           `409 {"error":"email_required"}` with no request to Paddle; a
           Paddle customer already linked to another account gets
           `409 {"error":"customer_in_use"}`.
        4. `409 {"error":"subscription_exists"}` when that customer has an
           `active`, `trialing`, `past_due` or `paused` subscription.
        5. A new transaction with one item (the configured price, quantity
           one), the customer and `custom_data: {"account_id": "<id>"}`.

        Any Paddle failure is `502 {"error":"billing provider error"}`. Not
        idempotent: every `201` is a new, unpaid transaction.
      tags: [Billing]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              title: BillingCheckoutRequest
              type: object
              additionalProperties: true
              description: Any other key is ignored.
              required: [plan, interval]
              properties:
                plan:
                  type: string
                  enum: [basic, pro, business]
                interval:
                  type: string
                  enum: [month, year]
            example:
              plan: pro
              interval: month
      responses:
        "201":
          description: The transaction was created.
          content:
            application/json:
              schema:
                title: BillingCheckoutResponse
                type: object
                required: [transaction_id]
                properties:
                  transaction_id:
                    type: string
                    description: Paddle's transaction ID (`txn_…`), for `Paddle.Checkout.open()`.
              example:
                transaction_id: txn_01hv8wptq8987qeep44cyrewp9
        "400":
          description: A malformed body, or a `plan` or `interval` outside the allowed values.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: invalid plan or interval
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: |
            `session_required` for an API key or OAuth JWT, `forbidden`
            for a member or viewer session, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Billing is off for this account, or Paddle is not configured.
          content:
            text/plain:
              schema:
                type: string
                example: "404 page not found"
        "409":
          description: |
            `email_required` — the signed-in owner has no verified email;
            `customer_in_use` — the owner's Paddle customer is already
            linked to another account; `subscription_exists` — the customer
            already has an active, trialing, past-due or paused
            subscription. No transaction is created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                email_required:
                  value: {error: email_required}
                customer_in_use:
                  value: {error: customer_in_use}
                subscription_exists:
                  value: {error: subscription_exists}
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
        "502":
          description: |
            Paddle failed or could not be reached. When the failure is on
            the transaction create itself (a timeout, a transport error, a
            Paddle error status, or an oversized or malformed answer), the
            transaction might still exist in Paddle. um-api never receives
            or stores its ID, so um-app cannot open it, and it stays open
            and unpaid; an unpaid transaction changes nothing for the
            account. A failure on an earlier step creates no transaction.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: billing provider error
  /api/v1/session/sign-out:
    post:
      operationId: signOut
      summary: End the calling session on the server (issue #486)
      description: |
        Session-only — `403 {"error":"session_required"}` for an API key
        or OAuth JWT, the same `auth.RequireSession` 403
        `/api/v1/account/discard-empty` uses. Deletes only the presented
        bearer token; any other session belonging to the same user is
        left untouched. A follow-up request with the same token, to this
        route or any other, gets `401` once the token is gone.

        Ends only the calling session — there is no "sign out everywhere"
        operation. A request throttled by the per-account rate limiter
        gets `429` with the session left live; retrying is safe.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "204":
          description: Session ended.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Not a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/me/reports:
    get:
      operationId: getReportPrefs
      summary: Get the signed-in user's weekly/monthly report preferences (issue #357)
      description: |
        Session-only — `403 {"error":"session_required"}` for an API key
        or OAuth JWT, since these are a shared, account-wide credential
        and must never see or toggle one person's mail preference.
        Scoped to the session's current account and the caller's own
        user id.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: The caller's report preferences on the current account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReportPreferences"
        "403":
          description: Not a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    patch:
      operationId: setReportPrefs
      summary: Update the signed-in user's weekly/monthly report preferences (issue #357)
      description: |
        Session-only, same 403 as `GET`. Body must be a JSON object with
        at least one of `weekly`/`monthly`, each a plain JSON boolean —
        not `null`, not a string or number. Any other top-level key is
        rejected. Writes no audit event (a personal setting, not an
        account mutation).
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              minProperties: 1
              properties:
                weekly:
                  type: boolean
                monthly:
                  type: boolean
      responses:
        "200":
          description: Updated.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReportPreferences"
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: Not a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/me/identities/github:
    post:
      operationId: startGitHubLink
      summary: Start linking a GitHub identity onto the signed-in user
      description: |
        Session-only (`403 {"error":"session_required"}` for an API key or
        an OAuth JWT). Mirrors `POST /api/v1/me/identities/google` exactly,
        substituting `POST /oauth/github/link`. Always mounted — GitHub
        sign-in is never feature-flagged the way Google is.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "201":
          description: Ticket minted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  link_url:
                    type: string
                    format: uri
                  link_ticket:
                    type: string
        "403":
          description: Caller did not authenticate via a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/me/invites:
    get:
      operationId: listMyInvites
      summary: List invites addressed to the signed-in user's GitHub identity
      description: |
        Session-only (`403 {"error":"session_required"}` for an API key or
        an OAuth JWT) — neither credential may see invitations to other
        accounts. A user with no GitHub identity always gets an empty list.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Live invites, oldest first.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/UserInvite"
        "403":
          description: Caller did not authenticate via a dashboard session.
  /api/v1/me/invites/{inviteID}/accept:
    post:
      operationId: acceptInvite
      summary: Accept an invite
      description: |
        Session-only. `404 invite_not_found` for an unknown, revoked,
        expired, or not-addressed-to-this-user invite; `409 member_exists`
        if the caller is already a member (the invite is consumed either
        way); `403` `"account suspended; contact support"` if the account is
        currently suspended — the invite survives, nothing is added.
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: inviteID
          in: path
          required: true
          schema:
            type: integer
            format: int64
      responses:
        "200":
          description: Joined.
          content:
            application/json:
              schema:
                type: object
                properties:
                  account_id:
                    type: integer
                    format: int64
                  role:
                    type: string
                    enum: [owner, member, viewer]
        "403":
          description: Caller did not authenticate via a dashboard session, or the account is suspended.
        "404":
          description: Invite not found.
        "409":
          description: Caller is already a member.
  /api/v1/me/legacy-migration:
    post:
      operationId: claimLegacyMigration
      summary: Claim a Monitive Classic migration link
      description: |
        Imports the signed-in owner's eligible free Monitive Classic team
        from a migration link (issue #619). Mounted only when the legacy
        handoff is configured (otherwise `404`). Session-only and
        owner-gated — `403 {"error":"session_required"}` for an API key or
        OAuth JWT, `403 {"error":"forbidden"}` for a non-owner session; no
        refusal spends the account rate limit, except for an API key the
        pre-authentication cache already recognizes, which is charged
        before authentication runs and so, once the account's bucket is
        exhausted, gets `429` instead of the `403`. Limited to 5 claims per
        user per 10 minutes.

        Classic is sent the user's email plus one provider pair when the
        user has one: `google_sub` as `google`, else `microsoft_sub` as
        `microsoft`, else the decimal `github_id` as `github`.

        The team is imported into the current account when it holds no
        monitor, otherwise into a second account the user owns (the
        default account is unchanged). An imported email recipient whose
        address the current account already holds reuses that recipient.
        The imported monitors start without a restart. A repeat claim for
        a team already imported into an account the user belongs to
        answers the stored result and writes nothing. Nothing is written
        on any refusal. The claim itself never calls Classic's complete;
        it marks the import pending, and the cutover worker calls complete
        once every imported enabled monitor has passed a check or 15
        minutes have passed, which pauses the Classic copies (issue #541;
        see the GET).
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token:
                  type: string
                  minLength: 43
                  maxLength: 43
                  pattern: '^[A-Za-z0-9_-]{43}$'
                  description: The migration-link token. Never echoed or logged.
      responses:
        "200":
          description: Imported, or the stored result of an earlier claim.
          content:
            application/json:
              schema:
                type: object
                required: [account_id, carried, changed]
                properties:
                  account_id:
                    type: integer
                    format: int64
                    description: The account the team was imported into.
                  carried:
                    type: integer
                    description: Records carried over unchanged.
                  changed:
                    type: integer
                    description: Records carried over with a change, or dropped.
        "400":
          description: Malformed body (`invalid request body`), or invalid UTF-8.
        "401":
          description: No session.
        "403":
          description: Not a dashboard session (`session_required`), or not an owner (`forbidden`).
        "404":
          description: The legacy handoff is not configured.
        "409":
          description: |
            Refused, nothing written: `migration_refused` with Classic's
            `reason`; `blocked` with the plan report's blocked entries;
            `already_imported` (the team moved to an account the user does
            not belong to); `account_refused` (the current account is
            suspended, already holds an imported team, has another plan, or
            a monitor cap refused the team); `user_conflict` (a team
            member's address already belongs to a user); `validation` with
            the failing `rule`.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    required: [error, reason]
                    properties:
                      error:
                        type: string
                        enum: [migration_refused]
                      reason:
                        type: string
                        enum: [unknown_link, already_moved, expired, not_owner, not_free, not_exported, billing_unavailable]
                  - type: object
                    required: [error, blocked]
                    properties:
                      error:
                        type: string
                        enum: [blocked]
                      blocked:
                        type: array
                        items:
                          type: object
                          required: [kind, legacy_id, target, reason]
                          properties:
                            kind:
                              type: string
                            legacy_id:
                              type: string
                            target:
                              type: string
                            reason:
                              type: string
                            extra_reasons:
                              type: array
                              items:
                                type: string
                            regions:
                              type: array
                              items:
                                type: string
                  - type: object
                    required: [error, rule]
                    properties:
                      error:
                        type: string
                        enum: [validation]
                      rule:
                        type: string
                  - type: object
                    required: [error]
                    properties:
                      error:
                        type: string
                        enum: [already_imported, account_refused, user_conflict]
        "413":
          description: Body over 64 KB.
        "415":
          description: Content-Type is not application/json.
        "422":
          description: The token is not a well-formed migration-link token (`invalid_migration_token`); Classic is not called.
        "429":
          description: Per-user claim limit reached (`rate_limited`).
          headers:
            Retry-After:
              description: Seconds until a claim is allowed again.
              schema:
                type: integer
        "500":
          description: Internal error.
        "503":
          description: |
            Retry later: `legacy_unavailable` (Classic failed or timed out,
            sent an unusable export, or the import's DNS checks ran out of
            time), `migration_refused` with reason `billing_unavailable`, or
            `commit_unknown` (the import may have committed; a retry answers
            the stored result).
          headers:
            Retry-After:
              description: Seconds to wait before retrying (60, or 5 for `commit_unknown`).
              schema:
                type: integer
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error:
                    type: string
                    enum: [legacy_unavailable, migration_refused, commit_unknown]
                  reason:
                    type: string
                    description: With `migration_refused` only — Classic's reason, normally `billing_unavailable`.
    get:
      operationId: getLegacyMigrationStatus
      summary: Read the Classic cutover state of claimed teams
      description: |
        The claim's follow-up read (issue #541): one entry per Monitive
        Classic team imported into an account the signed-in user owns,
        newest import first, including a second account a claim created.
        Mounted only when the legacy handoff is configured (otherwise
        `404`). Session-only with no role gate —
        `403 {"error":"session_required"}` for an API key or OAuth JWT —
        then the account rate limit.

        A claim leaves its import `pending` with a deadline 15 minutes
        after the import. The cutover worker calls Classic's complete
        once every imported enabled monitor has passed a check, or once
        the deadline has passed, and the import becomes `done`: Classic
        has paused its copies of the team's monitors. When Classic says
        the team changed after the claim's export, the worker exports it
        again, lists every configuration record that changed since the
        import in `cutover_report.not_carried` (the changes are not
        carried into Swift), and completes the move (issue #626). A
        complete that fails on a timeout or a 5xx is retried with
        back-off (30 s doubling to 10 minutes) until it succeeds. A move
        Classic refuses in a way a retry can't clear (for example an
        expired link) is `stopped`: it is not retried, the Classic
        monitors are not paused, and the operator has been alerted. A
        `not_required` import (imported by the operator's importer) is
        never cut over.

        Reads the database only; never calls Classic. Never returns the
        migration token, the export hash, the import report, the attempt
        count, the Classic team id or a stop reason.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: The cutover state of every owned import; `imports` is `[]` when there are none.
          content:
            application/json:
              schema:
                type: object
                required: [imports]
                properties:
                  imports:
                    type: array
                    items:
                      type: object
                      required: [account_id, imported_at, cutover_state, cutover_deadline, cutover_at, cutover_report]
                      properties:
                        account_id:
                          type: integer
                          format: int64
                          description: The account the team was imported into.
                        imported_at:
                          type: string
                          format: date-time
                        cutover_state:
                          type: string
                          enum: [pending, done, not_required, stopped]
                          description: |
                            `done` means Classic has paused its copies of the team's
                            monitors. `stopped` means Classic refused the move in a way
                            a retry can't clear: nothing retries, the Classic monitors
                            are not paused, and the operator has been alerted; its
                            `cutover_at` and `cutover_report` are null, as for `pending`.
                        cutover_deadline:
                          type: [string, "null"]
                          format: date-time
                          description: 15 minutes after `imported_at`; null for `not_required`.
                        cutover_at:
                          type: [string, "null"]
                          format: date-time
                          description: When Classic confirmed the move; null unless `done`.
                        cutover_report:
                          type: [object, "null"]
                          description: |
                            Null unless `done`. `not_up` lists the monitors that were
                            not `up` on the first attempt at or after the deadline,
                            or is empty when every monitor passed before it.
                            `not_carried` lists the Classic configuration records
                            edited after the claim's export, which were not carried
                            into Swift; `[]` when nothing changed. A report
                            written by a version from before issue #626 lacks it.
                          required: [not_up]
                          properties:
                            not_carried:
                              type: array
                              items:
                                type: object
                                required: [kind, legacy_id, change]
                                properties:
                                  kind:
                                    type: string
                                    description: The Classic record kind, e.g. `monitors`, `recipients` or `team`.
                                  legacy_id:
                                    type: string
                                    description: The record's Classic id, as in the import report.
                                  change:
                                    type: string
                                    enum: [added, removed, changed]
                                  fields:
                                    type: array
                                    items:
                                      type: string
                                    description: With `changed` only — the changed field names, never their values.
                            not_up:
                              type: array
                              items:
                                type: object
                                required: [monitor_id, ref, status]
                                properties:
                                  monitor_id:
                                    type: integer
                                    format: int64
                                  ref:
                                    type: string
                                    description: The monitor's `<handle>-<number>` reference.
                                  status:
                                    type: string
                                    description: The monitor's status then, e.g. `down`, `unknown` or `blocked`.
        "401":
          description: Missing or invalid credentials, or no session user.
        "403":
          description: Not a dashboard session (`session_required`), or the account is suspended.
        "429":
          description: Account rate limit reached.
        "500":
          description: Internal error.
  /api/v1/account/invites:
    post:
      operationId: createInvite
      summary: Invite a GitHub user to the account
      description: |
        Owner-only. `github_username` is validated locally (1–39 bytes,
        `^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$`) before any outbound call —
        `400 invalid_github_username` on failure. A valid login is resolved
        via GitHub's public, unauthenticated `GET /users/{login}`:
        `404 github_user_not_found` if GitHub reports no such user, `502
        github_error` on any other GitHub failure. `409 member_exists` if a
        user with that GitHub ID is already a member; `409 invite_exists`
        if a live invite for them already exists. Invites expire after 7
        days.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [github_username, role]
              properties:
                github_username:
                  type: string
                role:
                  type: string
                  enum: [owner, member, viewer]
      responses:
        "201":
          description: Invite created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Invite"
        "400":
          description: Invalid GitHub username, or an invalid role.
        "404":
          description: GitHub reports no such user.
        "409":
          description: Already a member, or a live invite already exists.
        "502":
          description: GitHub lookup failed for a reason other than 404.
    get:
      operationId: listInvites
      summary: List live invites on the account
      description: Owner-only. Returns every unexpired invite, oldest first.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Live invites.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Invite"
        "403":
          description: Caller is not the account's owner.
  /api/v1/account/invites/{inviteID}:
    delete:
      operationId: revokeInvite
      summary: Revoke an invite
      description: Owner-only. `404 invite_not_found` if no such live invite exists on the account.
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: inviteID
          in: path
          required: true
          schema:
            type: integer
            format: int64
      responses:
        "204":
          description: Revoked.
        "404":
          description: Invite not found.
  /api/v1/account/members:
    get:
      operationId: listMembers
      summary: List the account's members
      description: >-
        Owner-only. Returns every `account_members` row, oldest first, each joined with enough identity to render a list without a second round trip.
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Members.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Member"
        "403":
          description: Caller is not the account's owner.
  /api/v1/account/members/{userID}:
    patch:
      operationId: changeMemberRole
      summary: Change a member's role
      description: >-
        Owner-only. Any owner may promote a member/viewer to owner, or demote another owner (issue #325) — demoting the account's SOLE remaining owner is `409 last_owner`. `404` if `userID` has no membership on the account.
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: userID
          in: path
          required: true
          schema:
            type: integer
            format: int64
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [role]
              properties:
                role:
                  type: string
                  enum: [owner, member, viewer]
      responses:
        "204":
          description: Role changed.
        "400":
          description: Invalid user ID, or an unrecognized role.
        "403":
          description: Caller is not the account's owner.
        "404":
          description: Member not found.
        "409":
          description: Demoting the account's sole remaining owner (`last_owner`).
    delete:
      operationId: removeMember
      summary: Remove a member from the account
      description: >-
        Any member may remove THEMSELF; removing anyone else requires the caller to be the account's owner (`403` otherwise). Removing the sole remaining owner is `409 last_owner`; removing a member who holds a live API key is `409 member_has_api_keys` — revoke or rotate the key first.
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: userID
          in: path
          required: true
          schema:
            type: integer
            format: int64
      responses:
        "204":
          description: Removed.
        "400":
          description: Invalid user ID.
        "403":
          description: Caller is neither the target nor the account's owner.
        "404":
          description: Member not found.
        "409":
          description: Sole remaining owner (`last_owner`), or a live API key (`member_has_api_keys`).
  /api/v1/me/identities/google:
    post:
      operationId: startGoogleLink
      summary: Start linking a Google identity onto the signed-in user
      description: |
        Session-only (`403 {"error":"session_required"}` for an API key or
        an OAuth JWT). Mints a single-use ticket and returns the
        `POST /oauth/google/link` form target plus the raw ticket — the SPA
        submits these as a top-level form POST (never a redirect carrying
        the ticket in a query string: it is a live bearer credential for 10
        minutes and must never appear in a URL or request log). The user
        then completes Google's consent screen, and the callback links the
        resulting identity onto this session's user.

        Not mounted at all unless Google sign-in is configured — `404`
        otherwise (distinct from this handler's own `503`, which covers the
        case where `GET /api/v1/me` and the email-link endpoints are
        mounted but Google specifically is not).
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "201":
          description: Ticket minted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  link_url:
                    type: string
                    format: uri
                  link_ticket:
                    type: string
        "403":
          description: Caller did not authenticate via a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Google sign-in not configured.
        "503":
          description: Google sign-in is not configured.
  /api/v1/me/identities/microsoft:
    post:
      operationId: startMicrosoftLink
      summary: Start linking a Microsoft identity onto the signed-in user
      description: |
        Session-only (`403 {"error":"session_required"}` for an API key or
        an OAuth JWT). Mirrors `POST /api/v1/me/identities/google` exactly,
        substituting `POST /oauth/microsoft/link`.

        Not mounted at all unless Microsoft sign-in is configured — `404`
        otherwise (distinct from this handler's own `503`, which covers the
        case where `GET /api/v1/me` and the email-link endpoints are
        mounted but Microsoft specifically is not).
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "201":
          description: Ticket minted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  link_url:
                    type: string
                    format: uri
                  link_ticket:
                    type: string
        "403":
          description: Caller did not authenticate via a dashboard session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Microsoft sign-in not configured.
        "503":
          description: Microsoft sign-in is not configured.
  /api/v1/me/identities/email/start:
    post:
      operationId: startEmailLink
      summary: Start linking an email identity onto the signed-in user
      description: |
        Session-only. Sends a link (`{FRONTEND_URL}/settings/email#token=<tok>`)
        and a six-digit code, both valid for 10 minutes, reusing the same
        sender/rate limiters as `/oauth/email/start`. Never reveals whether
        the address is already linked to another user — that answer only
        comes at verify, after ownership is proven.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:
                  type: string
                  format: email
      responses:
        "202":
          description: Byte-identical for a known or unknown address.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: sent
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: Caller did not authenticate via a dashboard session.
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "503":
          description: Email sign-in is disabled.
  /api/v1/me/identities/email/verify:
    post:
      operationId: verifyEmailLink
      summary: Verify and complete an email identity link
      description: |
        Session-only. Accepts exactly one of `{"token": "..."}` or
        `{"email", "code"}`, scoped to the calling session's user — a token
        or code minted for a different user always 401s, identically to any
        other invalid/expired case.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                token:
                  type: string
                email:
                  type: string
                  format: email
                code:
                  type: string
      responses:
        "200":
          description: Linked.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: linked
        "401":
          description: Invalid, expired, wrong, reused, locked, malformed, or belonging to a different session user — identical body for every case.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Caller did not authenticate via a dashboard session, or the resolved account is suspended.
        "409":
          description: identity_in_use (another user already holds this address) or identity_already_linked (this user already has an email identity).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "503":
          description: Email sign-in is disabled.
  /api/v1/account:
    get:
      operationId: getAccount
      summary: Get the authenticated account
      tags: [Account]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Account
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Account"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
    patch:
      operationId: patchAccount
      summary: Update the authenticated account's notification_email
      description: |
        Sets or clears the optional `notification_email` field on the
        authenticated account. JSON null and the empty string both clear
        the field. The body must contain exactly the
        `notification_email` key — extra keys and an absent
        `notification_email` field are rejected with HTTP 400. The
        address is validated as RFC 5322 and capped at 254 characters
        (RFC 5321). Returns the updated account on success.
      tags: [Account]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AccountPatchInput"
            examples:
              setEmail:
                summary: Set the notification email
                value:
                  notification_email: user@example.com
              clearWithNull:
                summary: Clear the notification email with null
                value:
                  notification_email: null
              clearWithEmpty:
                summary: Clear the notification email with an empty string
                value:
                  notification_email: ""
      responses:
        "200":
          description: Account
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Account"
        "400":
          description: Bad request (missing field, unknown field, invalid address, over-length, invalid UTF-8, trailing data)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/account/usage:
    get:
      operationId: getAccountUsage
      summary: Get daily usage rows for the authenticated account
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 90
            default: 30
      responses:
        "200":
          description: Usage
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccountUsageResponse"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/account/events:
    get:
      operationId: listAccountEvents
      summary: List the authenticated account's audit events
      description: |
        Returns the per-account audit log written transactionally with every
        monitor / webhook / api-key mutation plus account-level signals
        (suspension, notification_email change). Newest-first by
        `(created_at DESC, id DESC)`. Paginated by opaque cursor — see the
        `cursor` parameter and the `next_cursor` response field.

        Rows become eligible for deletion after 90 days by a best-effort
        daily sweep (not a maximum age — see internal/retention). `since`
        filters older than the 90-day cutoff are rejected with HTTP 400.
      tags: [Account]
      security:
        - bearerAuth: []
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
          description: Page size. Max 200.
        - name: cursor
          in: query
          required: false
          schema:
            type: string
          description: |
            Opaque base64url cursor returned as `next_cursor` from a previous
            response. Pass back verbatim — the value is URL-safe and must
            NOT be percent-encoded by the client. Treat as opaque; do not
            inspect or mutate.
        - name: event_type
          in: query
          required: false
          style: form
          explode: true
          schema:
            type: array
            items:
              type: string
              enum:
                - monitor.created
                - monitor.updated
                - monitor.deleted
                - webhook.created
                - webhook.updated
                - webhook.deleted
                - recipient.created
                - recipient.updated
                - recipient.deleted
                - recipient.confirmed
                - recipient.unsubscribed
                - monitor.recipients_set
                - apikey.created
                - apikey.rotated
                - apikey.deleted
                - account.suspended
                - account.unsuspended
                - account.notification_email_changed
                - account.email_cap_hit
                - account.member_role_changed
                - account.member_removed
                - account.invite_created
                - account.invite_revoked
                - account.invite_accepted
                - monitor.status_page_enabled
                - monitor.status_page_disabled
                - status_page.created
                - status_page.updated
                - status_page.components_set
                - status_page.logo_set
                - status_page.logo_removed
                - status_page.deleted
                - account.identity_linked
                - account.github_email_skipped
                - account.plan_changed
                - account.attribution_set
                - account.billing_preview_changed
                - account.plan_shrunk
          description: |
            Filter to specific event types. Repeatable — providing multiple
            values returns the union (OR). Unknown values return 400.
            `webhook.*` are historic (pre-#212) and kept for the 90-day
            retention window; new writes produce `recipient.*` and
            `monitor.recipients_set` instead. `recipient.confirmed`,
            `recipient.unsubscribed`, and `account.email_cap_hit` are
            issue #321 (email recipients) additions. `account.identity_linked`
            (issue #316, Google/email identity linking) and
            `account.github_email_skipped` (issue #390, GitHub email
            adoption/merge) were both previously omitted from this filter
            enum even though the store could already write
            `account.identity_linked` rows — a pre-#390 binary's unfiltered
            `GET /api/v1/account/events` (no `event_type` param) still
            serialized those rows, since filtering is the only place this
            enum was enforced; see internal/api/DECISIONS.md.
            `account.plan_changed` (issue #507) is written by the
            operator-only plan endpoint; payload is
            `{from, to, max_monitors, soft_cap_monitors, host_fan_threshold}`
            (`host_fan_threshold` added by issue #512). The Monitive
            Classic import writes the same shape (`from` `"free"`, the
            override keys null). The billing worker (issue #598) writes
            `{from, to, source: "paddle", subscription_id}`, attributed to
            `system`, only when a Paddle subscription actually changes the
            plan; `from`/`to` may then be `"basic"`, `"pro"` or
            `"business"`.
            `account.attribution_set` (issue #510) is written once, by
            `POST /api/v1/account/attribution`, when a sign-up attribution
            is stored; payload is `{fields: [...]}` — the stored keys'
            names only, never their values.
            `account.billing_preview_changed` (issue #592) is written by the
            admin-only billing-preview endpoint on every call, a no-op
            re-set included; payload is `{from, to}`, both booleans.
            `account.plan_shrunk` (issue #595) is written by the plan-shrink
            step when it paused a monitor or reset a grace value; payload is
            `{plan, monitors_paused, grace_reset}`, attributed to `system`.
            The six `status_page.*` events (issue #642) are written by the
            group status page endpoints under `/api/v1/status-pages`, with
            `ref_type` `status_page` and `ref_id` the page id; payloads are
            `{title}` (created, deleted), `{fields}` (updated: the sent
            keys' names only, never their values), `{count}`
            (components_set), `{content_type, bytes}` (logo_set), and `{}`
            (logo_removed).
        - name: ref_type
          in: query
          required: false
          schema:
            type: string
            enum: [monitor, webhook, recipient, apikey, status_page]
          description: |
            Filter to events referring to a specific entity type. Must be
            paired with `ref_id`; providing one without the other returns 400.
        - name: ref_id
          in: query
          required: false
          schema:
            type: integer
            format: int64
          description: |
            Filter to events for a specific entity ID. Must be paired with
            `ref_type`.
        - name: since
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: |
            Inclusive lower bound on `created_at` (RFC3339). Values older than
            the 90-day retention window are rejected with 400.
        - name: until
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: |
            Exclusive upper bound on `created_at` (RFC3339). Must be strictly
            after `since` when both are provided.
      responses:
        "200":
          description: Paginated audit event list.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccountEventList"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/announcements:
    get:
      operationId: listAnnouncements
      summary: List active system announcements
      tags: [Announcements]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Announcements
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AnnouncementListResponse"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/monitors/{monitorID}/webhook:
    get:
      operationId: getMonitorWebhook
      summary: "Deprecated: get the legacy single webhook configured for a monitor"
      deprecated: true
      description: |
        Deprecated alias (issue #212). Backed by recipients: returns the
        lowest-id webhook-type recipient currently attached to this
        monitor, in the legacy `{id, monitor_id, url, secret, created_at}`
        shape, `secret` included. Prefer `GET /api/v1/recipients` /
        `GET /api/v1/monitors/{monitorID}/recipients`. Kept for one
        release for pre-#212 client compatibility.
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "200":
          description: Webhook
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Webhook"
        "404":
          description: Monitor or webhook not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
    put:
      operationId: putMonitorWebhook
      summary: "Deprecated: create or replace the legacy single webhook for a monitor"
      deprecated: true
      description: |
        Deprecated alias (issue #212), backed by recipients. If this
        monitor has no attached webhook-type recipient, creates one named
        after the monitor, attaches it, and returns it (with its secret)
        in the legacy shape. If one is already attached, this updates
        ITS url and returns the SAME id and secret — including when that
        recipient is shared with other monitors via
        `PUT /api/v1/monitors/{monitorID}/recipients`, in which case the
        URL change applies to every monitor sharing it, not just this
        one. Prefer `POST /api/v1/recipients` +
        `PUT /api/v1/monitors/{monitorID}/recipients` for new
        integrations. The `url` must point to a public hostname;
        private/loopback/link-local/mDNS URLs are rejected with
        `400 {"error":"url must be a valid http(s) URL"}` (SSRF
        hardening).
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: |
                The `url` must be valid UTF-8 with no null bytes and no ASCII
                control characters (U+0000..U+001F, U+007F). Violations return
                HTTP 400.
              required: [url]
              properties:
                url:
                  type: string
                  format: uri
                  maxLength: 2048
                  example: https://example.com/uptime-webhook
      responses:
        "200":
          description: Webhook
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Webhook"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Monitor not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
    delete:
      operationId: deleteMonitorWebhook
      summary: "Deprecated: remove the legacy single webhook from a monitor"
      deprecated: true
      description: |
        Deprecated alias (issue #212). Detaches the attached webhook-type
        recipient from this monitor; deletes the recipient itself only if,
        after detaching, it is attached to no other monitor and is not
        marked `default` — a shared or default recipient survives with its
        other attachments intact. Prefer
        `PUT /api/v1/monitors/{monitorID}/recipients` to detach without
        risking deletion of a shared recipient.
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "204":
          description: Deleted
        "404":
          description: Monitor or webhook not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/recipients:
    get:
      operationId: listRecipients
      summary: List account-level recipients
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Recipients (never includes `secret`)
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Recipient"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      operationId: createRecipient
      summary: Create an account-level recipient
      description: |
        `type` is `webhook`, `email`, `slack`, or `pagerduty`. For
        `type=webhook`, the response includes `secret` — shown exactly
        once, here, and never again on any subsequent read; `config.url`
        must point to a public hostname (SSRF hardening, same rule as the
        deprecated webhook alias). For `type=email`, the response carries
        no `secret` (every email recipient shares the fixed empty string
        internally); `config.address` is required instead of `config.url`,
        and the recipient starts `status=pending` until the mailed
        confirmation link is followed — see `POST /email/confirm/{token}`
        and `POST /api/v1/recipients/{recipientID}/confirm/resend`. For
        `type=slack` (issue #359), `config.url` must be a Slack incoming
        webhook URL in the exact shape
        `https://hooks.slack.com/services/{team}/{bot}/{token}` — no port,
        userinfo, query string, or fragment, and no trailing slash;
        `config.channel` is optional (e.g. `"#ops"` or `"@alice"`) and
        overrides the incoming webhook's own default channel. The response
        never carries `secret` for a slack recipient, and `config.url` is
        always masked to `https://hooks.slack.com/services/{team}/{bot}/********`
        (or, for a stored URL that doesn't match the expected shape, the
        bare `https://hooks.slack.com/services/********`) — the real token
        is never echoed back. For `type=pagerduty` (issue #363),
        `config.integration_key` is required instead of `config.url`: the
        PagerDuty Events API v2 routing/integration key, exactly 32
        characters of `[A-Za-z0-9]`. The response never carries `secret`
        or `config.url` for a pagerduty recipient, and `config.integration_key`
        is always masked to `"********"` plus the last 4 characters (or the
        bare `"********"` for a stored key that doesn't match the expected
        shape) — the real key is never echoed back. Every trigger/resolve
        for one outage shares one `dedup_key`
        (`"<monitor_ref>-<outage number>"` as of issue #412 — was
        `"<monitor_id>-<outage_id>"`), but only `dedup_key` and
        `payload.custom_details.monitor_ref` are stable across an entire
        outage — `payload.source`, `payload.custom_details.monitor_name`,
        and the resolve's own fields do not repeat the trigger's `event`
        or `reason`. If `config.integration_key` is an Event Orchestration
        routing key, route its rules on `custom_details.monitor_ref`, or
        enable the service's Global Dedup setting, rather than on any
        field that can change mid-outage. `config` validates
        only the four reserved keys — `url`, `address`, `channel`,
        `integration_key` — against the chosen `type`: in any letter case,
        and regardless of value (including `null` or `""`), a reserved key
        the `type` does not allow (e.g. `config.address` on a webhook,
        slack, or pagerduty recipient, `config.integration_key` on any
        type but pagerduty) is rejected with 400, as are two keys that
        fold to the same reserved name (e.g. `url` and `URL`). Any other
        key in `config` is not one of the four reserved names and is
        silently ignored. `name` is required (max 255 chars); `events`
        defaults to `["down","up","flapping"]` when omitted and must be a
        non-empty subset of that set when provided.

        For `type=pagerduty`: deleting or detaching the recipient,
        changing `config.integration_key`, or deleting or disabling the
        monitor or the account does NOT resolve an incident already open
        in PagerDuty under the old key — only the customer, or the
        PagerDuty service's own auto-resolve, can close it. A delivery
        already queued before a monitor is disabled or an account is
        suspended can still send.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RecipientCreate"
      responses:
        "201":
          description: Created, with `secret`
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Recipient"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/recipients/{recipientID}:
    parameters:
      - name: recipientID
        in: path
        required: true
        schema:
          type: integer
          format: int64
    get:
      operationId: getRecipient
      summary: Get a recipient
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Recipient (never includes `secret`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Recipient"
        "404":
          description: Recipient not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
    patch:
      operationId: patchRecipient
      summary: Update a recipient
      description: |
        Only fields present in the body are changed. `type` is immutable:
        including it at all (any value) returns 400. `name`, `default`,
        `events`, and `config` each reject an explicit JSON `null` with
        400 — omit the field entirely to leave it unchanged. `events`, if
        present, must be a non-empty subset of
        `["down","up","flapping"]`. Changing `config.address` on a
        `type=email` recipient resets it to `status=pending` and sends a
        new confirmation message BEST-EFFORT — a send failure here does
        not fail the request (the response still reflects the committed
        address change), so a caller that does not see the mail arrive
        should call `POST /recipients/{recipientID}/confirm/resend` to
        retry delivery rather than re-submitting the same PATCH, which
        sends nothing on an unchanged address (see `RecipientPatch`). For
        `type=slack` (issue #359), `config.url` and `config.channel` are
        each independently optional on PATCH — at least one is required —
        and `config.channel` set to `null` or `""` clears the override
        back to the incoming webhook's own default. PATCHing back the
        masked `config.url` from a GET/POST response is rejected with 400
        (it fails the same Slack URL grammar check) and leaves the stored
        URL unchanged. Any URL or channel change on a `type=slack`
        recipient cancels its own still-queued, not-yet-claimed
        (`pending`/`retrying`) deliveries, so a destination the caller
        just replaced never receives one of those. A delivery the Worker
        has already claimed for dispatch at the moment of the PATCH still
        runs against the pre-edit destination: a successful attempt is
        recorded as `delivered` (overwriting the cancellation), but a
        failed or retryable attempt leaves the row `cancelled`, with no
        attempt count, response code, or response body recorded for that
        attempt. For `type=pagerduty` (issue #363), `config.integration_key`
        is required when `config` is present (there is no optional
        secondary field the way Slack has `channel`). PATCHing back the
        masked `config.integration_key` from a GET/POST response is
        rejected with 400 (it fails the same key-shape check) and leaves
        the stored key unchanged. A key change on a `type=pagerduty`
        recipient cancels its own still-queued, not-yet-claimed
        deliveries the same way a Slack URL/channel change does — but
        never resolves an incident the old key already opened in
        PagerDuty; only the customer or PagerDuty's own auto-resolve can
        do that. `config` applies the
        same cross-type reserved-key rejection Create does (see that
        operation's description).
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RecipientPatch"
      responses:
        "200":
          description: Updated (never includes `secret`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Recipient"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Recipient not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
    delete:
      operationId: deleteRecipient
      summary: Delete a recipient
      description: |
        Detaches the recipient from every monitor it was attached to
        (cascade) and deletes it. Deletes the recipient's own
        `pending`/`retrying` webhook_deliveries rows so nothing keeps
        retrying to a removed destination.

        **Guarded delete (issue #396).** An optional `?replaced_by=` runs
        a stricter path instead: the recipient is deleted only if a
        replacement recipient already covers every one of its live
        (`pending`/`retrying`) deliveries. Omitting `replaced_by` keeps
        the plain, unguarded behavior described above exactly.

        Four checks, all evaluated in one transaction, each failing with
        409 and its own named reason:

        - `replacement_not_ready`: the replacement must exist in the same
          account, differ from the recipient being deleted, be active
          (not disabled; not an unconfirmed email recipient), have
          `events` that are a superset of the recipient being deleted's,
          and — when the recipient being deleted is an account default —
          itself be a default too.
        - `recipient_not_active`: the recipient being deleted must itself
          be active. An inactive recipient already lost its live
          deliveries when it went inactive, so a guarded delete would
          prove nothing; use the plain `DELETE` instead.
        - `attachment_missing`: every monitor the recipient being deleted
          is attached to must have the replacement attached too, with the
          same `grace_s` (`down_delay_s`).
        - `delivery_not_covered`: every live delivery of the recipient
          being deleted must have a non-null `enqueued_at` strictly after
          the replacement's `attached_at` on that monitor (see `GET
          /api/v1/monitors/{id}/recipients`), AND a same-transition
          sibling delivery for the replacement (same monitor, event type,
          and occurrence) whose status is `pending`, `retrying`, or
          `delivered`.

        **What a 204 guarantees, and what it doesn't.** The checks hold
        at the instant the delete commits — every removed delivery had a
        replacement copy that was delivered or still live at that
        instant. It does NOT mean the deleted recipient's destination
        goes quiet immediately: an attempt the delivery worker already
        claimed before the commit can still reach it once more, signed
        with its credentials, with no delivery-log row recording it — we
        recommend keeping the old destination (and, for a secret
        rotation, the old signing secret) accepting requests for at least
        five minutes after the 204. After the commit, the replacement is
        an ordinary recipient — a later edit to it (unsubscribe, delete,
        narrowed `events`, changed Slack/PagerDuty configuration) affects
        its own deliveries the same as for any recipient.

        **Drain recipe.** Before calling this with `replaced_by`: create
        and attach the replacement everywhere the original recipient is
        attached (same `events`, same `grace_s`/`down_delay_s`, same default
        status), then scan
        `GET /api/v1/webhook-deliveries?recipient_id={id}&status=pending&status=retrying&order=id`
        until `next_cursor` is `null` and every returned row's
        `enqueued_at` is non-null and greater than the replacement's
        `attached_at` on its monitor. Until the guarded delete returns
        204, avoid detaching, unsubscribing, deleting (without
        `replaced_by`), or otherwise editing the original recipient in
        any way that removes or cancels its live deliveries — the guard
        can only see rows that still exist, and any of those actions
        empties the scan and lets a later guarded delete succeed with the
        alert already silently lost.
      security:
        - bearerAuth: []
      parameters:
        - name: replaced_by
          in: query
          description: |
            Opt into the guarded delete (issue #396). Presence, not value,
            selects the guarded path: including the parameter at all —
            even as `?replaced_by=` or a bare `?replaced_by` — routes the
            request through the guard, and its value must then parse as
            an integer different from the path `recipientID`; otherwise
            400. Omitting the parameter entirely keeps the plain,
            unguarded delete. The query string itself is parsed strictly:
            a malformed query string (e.g. an unescaped `;` as in
            `?replaced_by=9;foo=bar`) is rejected with 400 before
            `replaced_by`'s presence is even checked, so a malformed query
            can never be mistaken for an absent parameter and fall
            through to the unguarded delete.
          schema:
            type: integer
            format: int64
      responses:
        "204":
          description: Deleted
        "400":
          description: |
            The query string was malformed, or `replaced_by` was present
            but empty, not an integer, or equal to the path
            `recipientID`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Recipient not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: |
            Guarded delete only (`replaced_by` present) — one of the four
            checks failed. `error` is the failed check's name:
            `replacement_not_ready`, `recipient_not_active`,
            `attachment_missing`, or `delivery_not_covered`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/recipients/{recipientID}/confirm/resend:
    parameters:
      - name: recipientID
        in: path
        required: true
        schema:
          type: integer
          format: int64
    post:
      operationId: resendRecipientConfirmation
      summary: Resend an email recipient's confirmation message (issue #321)
      description: |
        `type=email` only. Two-phase: stages a new confirmation token,
        sends it, then activates on success — a transient send failure
        never invalidates a previously-mailed link still in the
        recipient's inbox. Rate-limited to 5 per address per hour,
        process-wide across accounts.
      security:
        - bearerAuth: []
      responses:
        "202":
          description: Confirmation resent
        "404":
          description: Recipient not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: |
            Recipient is already confirmed, OR the mail was sent but the
            token it carries is no longer live (a concurrent resend or
            address change superseded it, or the recipient was deleted,
            between sending and activation) — the caller should retry the
            resend.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: Resent too recently (60s cooldown), or rate-limited
          headers:
            Retry-After:
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Sending the confirmation message failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/recipients/{recipientID}/test:
    parameters:
      - name: recipientID
        in: path
        required: true
        schema:
          type: integer
          format: int64
    post:
      operationId: testRecipient
      summary: Send a synchronous test alert to a recipient (issue #321)
      description: "Sends a labelled preview of a real down alert for one of the\naccount's own monitors (issue #425), preferring an enabled monitor\nover a paused one and, within that, a monitor the recipient is\nattached to over one it isn't, falling back to any monitor on the\naccount; sample values are status down, started now, and the cause\n`HTTP 503, expected 200`. The sample monitor may have a real open\noutage or be paused: every channel's copy states only that this is\na requested preview and never claims anything about the monitor's\nactual current state, marks the status/cause/time as sample values,\nand says so when the sample is paused. When the account has no\nmonitors, every channel sends a test that names no monitor (email\nshows \"your first monitor\" wording and a create link). Per channel:\nan email with subject `[Test] Down: <monitor>`, a test banner, and\na footer naming the covered monitors plus a manage link (email); a\nsigned `event: \"monitor.test\"` POST with `test: true` (webhook); an\nunsigned Block Kit message with a \U0001F9EA TEST banner above the down\nlayout (slack, issue #359); or a PagerDuty Events API v2\ntrigger-then-resolve pair, both carrying\n`custom_details.test: true` and, for a paused sample,\n`custom_details.monitor_paused: true` (pagerduty, issue #363) — all\ndirectly, bypassing the `webhook_deliveries` outbox and creating no\nincident.\nRate-limited to 1 per\nrecipient per minute; a failure to load the account's monitors\nreturns 500 before anything is sent or email capacity is\nreserved. A `pending` or `disabled` recipient returns\n409. For `type=slack`, a non-2xx response — 3xx included — is\nreported as `status=\"failed\"` with `response_code` and `error` set\nto Slack's own response body (e.g. `\"no_service\"`); only a\ntransport failure returns the top-level 502. For `type=webhook`,\na redirect is never followed (issue #614): a 3xx is reported as\n`status=\"failed\"` with `response_code` and `error` set to `\"The\nendpoint answered with a redirect. Use the final URL.\"` — the\n`Location` and the response body are never included — and any\nother non-2xx is `failed` with `response_code` only. For\n`type=pagerduty`, the trigger (severity `info`) is followed by an immediate resolve\nunder the identical `dedup_key`, ONLY if the trigger's response was\n2xx; a successful pair reports `status=\"accepted\"` (never\n`\"delivered\"`, since PagerDuty's Events API is asynchronous and two\n2xx responses do not prove the test incident actually closed) with\n`message` carrying that caveat. Any failure — a non-2xx trigger, a\ntransport error on either request, or a non-2xx resolve — reports\n`status=\"failed\"`; every failure except a cleanly-rejected trigger\nalso carries a warning in `error` that a test incident may remain\nopen in PagerDuty. No PagerDuty response body is ever read or\nreturned; `error`/`message` always come from fixed outcome text.\n"
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Test attempted (check `status` for the outcome)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RecipientTestResult"
        "404":
          description: Recipient not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Recipient not active (pending or disabled)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "502":
          description: No response could be obtained from the destination
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RecipientTestResult"
  /ack/{token}:
    parameters:
      - name: token
        in: path
        required: true
        schema:
          type: string
    get:
      operationId: incidentAckPage
      security: []
      summary: Render the outage-acknowledgement page (issue #420)
      description: |
        Public, unauthenticated. Renders a plain HTML page with a form that
        POSTs to this same URL. Never acknowledges anything — only `POST`
        does, so a link scanner or mail-client prefetcher that merely opens
        the link cannot acknowledge the outage.
      responses:
        "200":
          description: HTML page
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: Invalid token. The identical page a refused POST renders.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: Rate-limited (60/hour per caller IP)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      operationId: acknowledgeIncidentByLink
      security: []
      summary: Acknowledge an outage through a signed emailed link (issue #420)
      description: |
        Public, unauthenticated. Consumes the signed, single-outage
        acknowledgement token embedded in a down alert. The token is bound
        to one outage of one account, so a token naming another account's
        outage is refused, and the outage must still be ongoing — a link
        opened after the outage resolved is refused. Idempotent: a second
        POST keeps the first acknowledgement. The acknowledgement is a
        marker only until reminder alerts exist; the recovery ("up") alert
        is always sent. A forged token and a valid-but-refused token render
        the identical 404 page.
      responses:
        "200":
          description: Acknowledged (or already acknowledged).
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: |
            Invalid token, another account's outage, or a resolved outage.
            Renders the identical not-found page in every case, so a caller
            cannot distinguish them.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: Rate-limited (60/hour per caller IP; viewing and acknowledging are tracked separately).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Store failure.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
  /email/confirm/{token}:
    parameters:
      - name: token
        in: path
        required: true
        schema:
          type: string
    get:
      operationId: confirmEmailRecipientPage
      security: []
      summary: Render the email-confirmation page (issue #321)
      description: |
        Public, unauthenticated. Renders a plain HTML page with a form
        that POSTs to this same URL. Never consumes the token — only
        `POST` does, so a link scanner or mail-client prefetcher that
        merely opens the link cannot burn the one-time confirmation.
      responses:
        "200":
          description: HTML page
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: |
            Rate-limited (60/hour per caller IP). JSON, not the styled
            page — keeps the process-wide default Content-Security-Policy,
            not EmailPageCSP.
          headers:
            Retry-After:
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      operationId: confirmEmailRecipient
      security: []
      summary: Confirm an email recipient (issue #321)
      description: |
        Public, unauthenticated. Consumes the 64-hex confirmation token.
        Unknown, expired, malformed, and already-consumed tokens all
        render the identical response, so a caller cannot distinguish any
        of those cases.
      responses:
        "200":
          description: Confirmed.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: |
            Unknown, expired, malformed, or already-consumed token.
            Renders the identical not-found page in every case, so a
            caller cannot distinguish them.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: Rate-limited (60/hour per caller IP; confirm and unsubscribe are tracked separately).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Store failure.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
  /email/unsubscribe/{token}:
    parameters:
      - name: token
        in: path
        required: true
        schema:
          type: string
    get:
      operationId: unsubscribeRecipientPage
      security: []
      summary: Render the unsubscribe page (issue #321)
      description: |
        Public, unauthenticated. Renders a plain HTML page with a form
        that POSTs to this same URL. Never consumes the token.
      responses:
        "200":
          description: HTML page
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: |
            Rate-limited (60/hour per caller IP). JSON, not the styled
            page — keeps the process-wide default Content-Security-Policy,
            not EmailPageCSP.
          headers:
            Retry-After:
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      operationId: unsubscribeRecipient
      security: []
      summary: Unsubscribe an email recipient (issue #321)
      description: |
        Public, unauthenticated. Also the target of RFC 8058 one-click
        unsubscribe (`List-Unsubscribe-Post: List-Unsubscribe=One-Click`),
        which POSTs here with no human interaction — the token lives in
        the path, so no request body is required. Idempotent: a second
        POST still returns the success page. A well-formed token's own
        traffic never charges the rate limiter — RFC 8058 one-click
        requests for many unrelated recipients commonly share one
        mail-provider egress IP, and a genuinely valid unsubscribe is
        never throttled by that shared traffic alone. But the lookup is
        skipped, and this returns 429, if the caller's IP or the
        process-wide backstop is already exhausted by PRIOR invalid
        requests — checked before the store call — so a well-formed,
        genuinely valid token can still be temporarily rejected once that
        budget is already spent. Only a confirmed-invalid token (or
        malformed input, rejected up front) actually charges the limiter,
        60/hour per caller IP plus a process-wide backstop across every
        IP.
      responses:
        "200":
          description: Unsubscribed.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: Unknown or malformed token. Renders the not-found page.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: |
            Rate-limited — reachable for an unknown/malformed token, OR
            for a well-formed, genuinely valid token whose caller IP or
            the process-wide backstop is already exhausted by prior
            invalid attempts (checked before the store lookup). A valid
            token's own traffic never trips this, but it is not immune to
            an already-spent budget. Confirm and unsubscribe are tracked
            separately.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Store failure.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
  /email/reports/{type}/unsubscribe/{token}:
    parameters:
      - name: type
        in: path
        required: true
        schema:
          type: string
          enum: [weekly, monthly]
      - name: token
        in: path
        required: true
        schema:
          type: string
    get:
      operationId: reportUnsubscribePage
      security: []
      summary: Render the report-unsubscribe page (issue #357)
      description: |
        Public, unauthenticated. Renders a plain HTML page with a form
        that POSTs to this same URL. Never consumes the token. An
        invalid `type` segment renders the identical not-found page a
        confirmed-invalid token would — the two are indistinguishable.
      responses:
        "200":
          description: HTML page
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: Invalid type segment.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: |
            Rate-limited (60/hour per caller IP; tracked separately from
            the recipient confirm/unsubscribe routes). JSON, not the
            styled page — keeps the process-wide default
            Content-Security-Policy, not EmailPageCSP.
          headers:
            Retry-After:
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      operationId: reportUnsubscribe
      security: []
      summary: Unsubscribe from a weekly or monthly report (issue #357)
      description: |
        Public, unauthenticated. Also the target of RFC 8058 one-click
        unsubscribe. Idempotent: a second POST still returns the success
        page. Flips only the named `type`'s report preference on the one
        membership the token identifies — a weekly-report unsubscribe
        never touches the monthly preference, and vice versa. An invalid
        `type` or an unknown token both render the identical not-found
        page.
      responses:
        "200":
          description: Unsubscribed.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "404":
          description: Invalid type, or unknown/malformed token. Renders the not-found page.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
        "429":
          description: |
            Rate-limited — reachable for an invalid type, an
            unknown/malformed token, OR a well-formed, genuinely valid
            token/type pair whose caller IP or the process-wide backstop
            is already exhausted by prior invalid attempts (checked
            before the store lookup). A valid token/type pair's own
            traffic never trips this, but it is not immune to an
            already-spent budget. Tracked separately from the recipient
            confirm/unsubscribe routes.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Store failure.
          headers:
            Content-Security-Policy:
              $ref: "#/components/headers/EmailPageCSP"
          content:
            text/html: {}
  /api/v1/monitors/{monitorID}/recipients:
    get:
      operationId: getMonitorRecipients
      summary: List recipient ids attached to a monitor
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "200":
          description: Attached recipient ids (`[]` for none)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitorRecipients"
        "404":
          description: Monitor not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
    put:
      operationId: putMonitorRecipients
      summary: Replace the set of recipients attached to a monitor
      description: |
        Full replacement, not a merge. `recipient_ids` entries must be
        positive and unique (400 before any write, for either violation).
        An id not owned by the calling account returns 400 and writes
        nothing. Removing a recipient from the set cancels that pair's
        queued (`pending`/`retrying`) webhook_deliveries rows in the same
        transaction, not just future transitions — but this is a bound on
        enqueued state, not a guarantee about what has already left the
        wire: the same documented race as delivery supersede (see
        `docs/SPEC.md`'s outbox section) means an attempt the Worker already
        passed its liveness check for just before this transaction commits
        can still complete. Whether it is recorded in the delivery log
        depends on which update commits first: if this transaction's delete
        (scoped to `pending`/`retrying` rows) runs first, the row is gone
        and the Worker's later terminal-status update is a no-op, so the
        attempt is NOT recorded; if the Worker's terminal-status update
        lands first, the row is already `delivered` (or `failed`) and this
        transaction's delete — which only targets `pending`/`retrying` rows
        — leaves it in place, so the attempt IS recorded. Both outcomes are
        possible; this is not a guarantee either way. `{"recipient_ids":
        []}` detaches everything, after which `silent_monitors` on
        `GET /api/v1/account` counts this monitor if it is still enabled.
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MonitorRecipients"
      responses:
        "200":
          description: The resulting attached set
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitorRecipients"
        "400":
          description: Bad request (invalid id, or an id not owned by this account)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Monitor not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "422":
          description: |
            A `recipients` entry's `grace_s`/`down_delay_s` is well-shaped
            but not one of the values the account's plan allows (issue
            #504). Free and complimentary plans require `120` seconds; paid
            plans accept any of the 15 allowed values (issue #593). Nothing
            is written.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                graceNotAllowed:
                  summary: grace_s is not the fixed plan value
                  value:
                    error: "grace_s is fixed at 120 seconds on your plan"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/monitors/uptime:
    get:
      operationId: listMonitorsUptime
      summary: Batch per-day uptime grid for every (or selected) monitor on the account (issue #469)
      description: |
        The batch form of `GET /api/v1/monitors/{monitorID}/uptime`: one
        request returns every requested monitor's 30-day uptime grid, so a
        dashboard listing N monitors no longer needs N requests. Both
        routes build each monitor's array with the same per-day
        computation, so the two can never silently diverge on the
        arithmetic itself — but they are not guaranteed to return
        byte-identical output for a monitor whose state transitions
        between two separate requests, the same way two sequential calls
        to the single-monitor route aren't.

        Without `ids`, every monitor on the authenticated account is
        included (monitor creation already caps an account at 100, so
        there is no truncation). With `ids`, the account's own monitor
        roster is filtered down to that set; an id that doesn't exist, or
        belongs to another account, is silently omitted from the
        response — no error, no partial-failure signal — so the response
        can never be used to probe whether a monitor id exists or which
        account owns it.

        `ids` is a comma-separated list of positive integer monitor ids,
        deduplicated (repeating an id any number of times counts once
        toward the cap). Any malformed element — non-numeric, `<= 0`, or
        empty (a leading, trailing, or doubled comma, or the value being
        empty outright) — is a 400. More than 100 distinct ids after
        dedup is a 400.

        An empty scope (an empty account, or an `ids` set that resolves to
        nothing the caller owns) returns `{"uptime":{}}`.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - name: ids
          in: query
          required: false
          schema:
            type: string
          description: |
            Comma-separated positive integer monitor ids. Omit to return
            every monitor on the account.
          example: "101,102,103"
        - name: window
          in: query
          required: false
          schema:
            type: string
            enum: [30d]
            default: 30d
          description: Window length. Only `30d` is accepted in v1.
      responses:
        "200":
          description: >
            Map of monitor id (as a decimal string) to its 30-element per-day uptime array, today-first. Empty when the account has no monitors, or `ids` resolves to none the caller owns.

          content:
            application/json:
              schema:
                type: object
                properties:
                  uptime:
                    type: object
                    additionalProperties:
                      type: array
                      minItems: 30
                      maxItems: 30
                      items:
                        $ref: "#/components/schemas/UptimeDay"
                required: [uptime]
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/monitors/{monitorID}/uptime:
    get:
      operationId: getMonitorUptime
      summary: Per-day uptime grid for a monitor
      description: |
        Returns a 30-element array describing the monitor's uptime over
        the last 30 UTC days, ordered today-first. Each entry is computed
        from `monitor_uptime_day` (authoritative scheduled count per day)
        and from `down`-typed incidents that overlap that day.

        `pct` is `null` when `scheduled = 0` for that day — the dispatcher
        never tried to check the monitor (account suspended, kill switch
        on, monitor disabled, dispatcher down, monitor freshly created).
        The dashboard renders this as the grey/no-data state and must
        treat null as "no information", NOT as "0%". A `pct` value of `0`
        means the monitor was checked and was down for every second of
        the day.

        `pct` is normally derived purely from down-incident overlap, but
        is reconciled against `monitor_uptime_day.succeeded`: a day with
        zero successful checks is floored to `0` when corroborated as
        down — an unresolved down incident overlaps the day (any day),
        or the monitor's current resolved status is `down` and its
        current outage (the last down-transition) began before that day
        ended (only when the monitor is enabled and not currently
        flapping) — even if the `incidents` table has no row covering
        that day (a dropped runtime transition write). A currently-down
        monitor is floored across every day of its continuous outage,
        but never a day that predates the current down-period: the
        down-since timestamp bounds which days the live status describes.
        It is never floored when the monitor's resolved status is `up` or
        `blocked` (issue #558), so a day where the primary region failed every check but
        cross-region confirmation kept the monitor up still reads its
        incident-derived percentage.

        `flapping` incidents are intentionally excluded from the downtime
        math — uptime semantics treat a flapping monitor as "answering,
        just bouncing".

        Each entry also carries a `latency` daily candle — open, high,
        low, close, and average total response time in whole
        milliseconds, built only from successful checks against the
        monitor's sticky primary region (wopher's `total_ms`: the full
        request round-trip, DNS through last byte of download). `latency`
        is `null` when the
        day has no successful samples to build a candle from — this
        includes days predating the feature, and is a distinct null
        condition from `pct` (which keys off `scheduled = 0`): a day can
        have a non-null `pct` (fully scheduled, down the entire day) and
        still carry a null `latency`. `avg` is the arithmetic mean of
        the day's successful-check response times. Latency history is
        free-tier for every account — no plan gating.

        v1 supports `window=30d` only. The 30-day cap is a visibility and
        API limit, independent of the 95-day physical retention window for
        incidents and `monitor_uptime_day` (see internal/retention/
        DECISIONS.md). Wider or narrower windows are out of scope for v1.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
        - name: window
          in: query
          required: false
          schema:
            type: string
            enum: [30d]
            default: 30d
          description: Window length. Only `30d` is accepted in v1.
      responses:
        "200":
          description: 30-element array of per-day uptime entries, today-first.
          content:
            application/json:
              schema:
                type: array
                minItems: 30
                maxItems: 30
                items:
                  $ref: "#/components/schemas/UptimeDay"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Monitor not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/monitors/{monitorID}/status-page:
    get:
      operationId: getMonitorStatusPage
      summary: Get the monitor's free status-page switch state (issue #368)
      description: |
        Viewer role or higher. When the page is on, the response includes the
        server-built badge URL and embed snippets. Only owners can use `PUT` to
        publish or revoke the page.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      responses:
        "200":
          description: Current switch state.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageSettings"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: Monitor not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    put:
      operationId: setMonitorStatusPage
      summary: Turn the monitor's free status page on or off (issue #368)
      description: |
        Owner role only — publishing a public URL is an owner decision,
        the same gate as `/account/feed-token`. Repeating `{"enabled":true}`
        on an already-on page returns the same URL. `{"enabled":false}`
        revokes the URL immediately at the origin (a caching CDN in front
        of the status host may still serve the old page for up to 60
        seconds — see `STATUS_PAGE_URL`/`Free Status Page` in SPEC.md).
        Turning it back on mints a different token. The body must be
        exactly `{"enabled": <bool>}` — a missing or null `enabled`, a
        non-boolean value, or any other key is `400` and leaves the
        stored token unchanged.
      tags: [Monitors]
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [enabled]
              additionalProperties: false
              properties:
                enabled:
                  type: boolean
      responses:
        "200":
          description: Updated switch state.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageSettings"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Caller is not an owner, or the account is suspended.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Monitor not found or belongs to another account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
  /api/v1/monitors/{monitorID}/test:
    post:
      operationId: testMonitor
      summary: Dispatch an ad-hoc check from the probe fleet
      description: |
        Runs one immediate check against the monitor's configured target. Does not
        modify monitor state, evidence buffer, or incidents. Only monitors of a
        type the check engine currently supports (`http`, `ping`, `tcp`) can be
        tested; a monitor of any other type returns 400 — unreachable in
        production after issue #209, since no such monitor can be created or
        persisted, but preserved as a defensive check. Rate limited to 1 call
        per monitor per 10 seconds.
      security:
        - bearerAuth: []
      parameters:
        - $ref: "#/components/parameters/monitorID"
        - name: region
          in: query
          required: false
          schema:
            type: string
            enum: [EU, US-E, US-W, ASIA, OCE, SA]
          description: Probe region. Defaults to a random available region.
      responses:
        "200":
          description: Check completed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TestResult"
        "400":
          description: |
            Unsupported monitor type or invalid region. The unsupported-type
            body is byte-identical to `POST`/`PUT /api/v1/monitors`'s:
            `type '<type>' is not available yet; the check engine currently
            supports: http, ping, tcp`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: |
            The test was not sent, for one of two reasons:

            * The target URL resolves to a blocked address (SSRF).
            * (issue #621) The site's robots.txt does not allow Monitive to
              check this URL. Body: `robots.txt does not allow Monitive to
              check this URL; add "User-agent: Monitive" and "Allow: /" to
              robots.txt`. When robots.txt has answered with a 5xx, with no
              copy cached, for 24 hours, the body is instead `robots.txt has
              not loaded for 24 hours; make sure it loads and add
              "User-agent: Monitive" and "Allow: /" to it`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Monitor not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: |
            One of three independent rate limiters fired:

            * **Per-monitor minimum-interval limiter (`MonitorTestLimiter`)** —
              another test for the same monitor ran too recently.
              Body: `too many tests for this monitor; retry in <N>s`.
            * **Per-account dispatcher cap (`AccountRateLimiter`)** — the
              authenticated account exceeded its 200/min cap on the
              authenticated `/api/v1/*` surface. See
              `components.responses.RateLimited`.
            * **Per-domain dispatch cap (`DomainLimiter`)** — too many
              checks have been dispatched to this monitor's eTLD+1 across
              ALL accounts within the rolling window. The cap protects
              third-party sites from coordinated-monitoring overload (e.g.
              N free-tier accounts each pointing a monitor at the same
              victim). Body:
              `domain rate limit exceeded; retry in <N>s`. The bucket is
              keyed on the public-suffix-trimmed apex
              (`api.victim.com` and `www.victim.com` share one bucket).

            The `Retry-After` header gives the integer seconds until the
            next allowed dispatch under whichever limiter fired. Scales
            differ: per-monitor (~tens of seconds), per-account
            (sub-second to seconds), per-domain (up to one minute).
          headers:
            Retry-After:
              schema:
                type: integer
              description: |
                Seconds until the next allowed test under whichever
                limiter rejected the call.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                perMonitor:
                  summary: Per-monitor minimum-interval limiter
                  value:
                    error: too many tests for this monitor; retry in 8s
                perDomain:
                  summary: Per-domain cross-account limiter
                  value:
                    error: domain rate limit exceeded; retry in 42s
        "502":
          description: No healthy probe or probe-level error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
  /api/v1/webhook-deliveries:
    get:
      operationId: listWebhookDeliveries
      summary: List recent webhook delivery attempts for the authenticated account
      description: |
        Three modes, two response shapes, selected by `?order=`:

        - Default (`order` key absent entirely): offset mode. `created_at`
          descending, `?limit=`/`?offset=`, `WebhookDeliveryListResponse`.
          Unchanged since before issue #396 apart from the added
          `enqueued_at` field on each delivery. A present `order` key —
          even an empty `?order=` or a bare `?order` — never falls back
          to this mode; see below.
        - `order=id`: cursor mode (issue #396). `id` ascending,
          keyset-paginated via `?cursor=`, `WebhookDeliveryCursorListResponse`.
          Any `?offset=` (any value, including `0`) is rejected with 400.
          A malformed or empty `?cursor=` is rejected with 400 — presence
          of the parameter is checked independently of its value, so a
          present-but-empty `?order=id&cursor=` is rejected the same as a
          malformed one, not treated as "no cursor". `?cursor=` without
          `order=id` is also rejected with 400, empty value included — a
          cursor only has meaning in keyset order. `order` itself must
          be present exactly once with the value `id`; a present but
          empty `?order=`, a bare `?order`, a repeated `order=` key, or
          any other value is rejected with 400 rather than silently
          running offset mode. A malformed query string itself (e.g. an
          unescaped `;`) is rejected with 400 before any parameter is
          inspected.
        - `order=newest`: newest-first cursor mode (issue #418).
          `created_at` descending, then `id` descending, keyset-paginated
          via `?cursor=` on `(created_at, id)`,
          `WebhookDeliveryCursorListResponse`. The same `offset` and
          `cursor` presence rules as `order=id` apply. A walk returns each
          delivery at most once, and every delivery that existed when the
          walk began and still matches the filters exactly once. A
          delivery's `created_at` is its incident transition's time, not
          its insert time, so a delivery committed mid-walk can sort below
          the cursor and appear on a later page of the same walk, or only
          on a fresh walk if it sorts above. A `status` filter is
          evaluated per page, so a delivery whose status changes mid-walk
          can enter or leave the walk. An `order=id` cursor is rejected
          here, and an `order=newest` cursor under `order=id`.

        `order`, when present, must appear exactly once with the value
        `id` or `newest`.

        `?recipient_id=` filters to one recipient's own deliveries
        (`webhook_deliveries.webhook_id`), still scoped to the caller's
        account. `?status=` is repeatable (OR-union) — a single
        `status=x` behaves exactly as before issue #396.

        **Recipient-queue drain recipe.** To prove a recipient's
        pre-attachment backlog is drained before deleting it (e.g.
        rotating to a replacement recipient via
        `DELETE /api/v1/recipients/{id}?replaced_by=`): scan
        `?recipient_id={id}&status=pending&status=retrying&order=id`,
        following `next_cursor` until it is `null`. Only an empty scan
        result proves the queue is literally empty; any row the scan
        returns proves the opposite, since the status filter selects
        live rows by construction. The backlog is considered drained
        once every returned row's `enqueued_at` is non-null and greater
        than the replacement's `attached_at` on every monitor
        (`GET /api/v1/monitors/{id}/recipients`'s `attached_at` field) —
        but that timestamp comparison alone does not prove sibling
        coverage (that each row has a counterpart delivery enqueued for
        the replacement); it only establishes that a live row postdates
        the replacement's attachment. `DELETE /api/v1/recipients/{recipientID}`
        is the authoritative check for a safe rotation — it verifies
        sibling coverage server-side, in one transaction, rather than
        trusting a client-computed timestamp comparison. See that
        endpoint for the full recipe and its guarantees/limits.
      security:
        - bearerAuth: []
      parameters:
        - name: monitor_id
          in: query
          schema:
            type: integer
            format: int64
        - name: recipient_id
          in: query
          description: Filter to one recipient's deliveries (issue #396).
          schema:
            type: integer
            format: int64
        - name: status
          in: query
          style: form
          explode: true
          description: |
            Repeatable (issue #396): `status=pending&status=retrying`
            returns the OR-union. A single `status=x` behaves exactly as
            on master.
          schema:
            type: array
            items:
              type: string
              enum: [pending, retrying, delivered, failed, superseded, cancelled]
        - name: since
          in: query
          schema:
            type: string
            format: date-time
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: offset
          in: query
          description: |
            Offset-mode only. Rejected with 400 (any value, including
            `0`) when combined with `order=id` or `order=newest`.
          schema:
            type: integer
            minimum: 0
            default: 0
        - name: order
          in: query
          description: |
            Omit for the default offset-mode shape. `id` switches to
            oldest-first cursor mode (issue #396); `newest` switches to
            newest-first cursor mode (issue #418). When present, the
            parameter must appear exactly once with the value `id` or
            `newest` — an empty `?order=`, a bare `?order`, a repeated
            `order=` key, or any other value (including `created_at`) is
            rejected with 400 rather than silently falling back to offset
            mode.
          schema:
            type: string
            enum: [id, newest]
        - name: cursor
          in: query
          description: |
            Cursor-mode only (issues #396, #418) — the opaque
            `next_cursor` value from a previous page of the same mode.
            Requires `order=id` or `order=newest`.
          schema:
            type: string
      responses:
        "200":
          description: Deliveries
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/WebhookDeliveryListResponse"
                  - $ref: "#/components/schemas/WebhookDeliveryCursorListResponse"
        "400":
          description: |
            Bad request — an unknown `status` value; an `order` that is
            empty, repeated, or anything other than `id` or `newest`
            (including a bare `?order`); a malformed `cursor`, or one
            issued by the other cursor mode; `cursor` supplied without
            `order=id` or `order=newest`; or `offset` supplied together
            with either.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /feed/{token}:
    get:
      summary: Public JSON incident feed (unauthenticated, token-gated)
      security: []
      description: |
        Returns a trimmed view of recent incidents for the account owning this
        token. No sensitive configuration is exposed. Rate-limited at 20
        requests per minute per token.

        Monitors are identified by host only (issue #514): lowercase, with
        the port only when it is not the scheme's default, and never a
        path, query string, or userinfo. `monitor_url` is a deprecated
        alias equal to `monitor_host`, and `account.github_username` is
        deprecated and always the empty string. The feed never names its
        owner.
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
          description: Feed token (prefix `fd_`).
      responses:
        "200":
          description: Feed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FeedResponse"
        "403":
          description: Owning account is suspended
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Unknown or rotated token
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: Rate limit exceeded
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds until the current window ends.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /feed.xml:
    get:
      summary: Public platform-news Atom feed (unauthenticated)
      security: []
      description: |
        Public Atom XML feed rendering currently active platform announcements
        from the shared `announcements` table. No `Authorization` header is
        required. The feed contains at most 50 entries, ordered descending
        by `published_at` (with a stable secondary `id` tiebreaker).

        Active means `published_at <= now()` AND (`expires_at IS NULL` OR
        `expires_at > now()`). Empty active sets still return a valid Atom
        envelope with zero `<entry>` rows so aggregator-cache content hashes
        stay stable.

        Cache-Control is `public, max-age=300` — Cloudflare in front of the
        API will respect the hint. Announcements are not time-critical, so
        a 5-minute window is acceptable.

        `<updated>` semantics: the feed-level `<updated>` is a best-effort
        change marker, not a linearizable version counter. It is the
        GREATEST of four signals — an edit to any announcement (including
        one that unpublishes a row by pushing `published_at` into the
        future), a scheduled announcement crossing into visibility, an
        active announcement crossing into expiry, or a hard delete — and
        it never exceeds the current time. Writes to *different*
        announcement rows take no shared lock, so two concurrent edits can
        commit in an order where the marker does not advance past a value
        a reader already observed even though a new change became visible
        in that window. Treat `<updated>` as a "poll again soon" hint, not
        a guarantee that an unchanged value means nothing changed since
        your last read. Per-entry `<updated>` is the later of that
        announcement's last edit and its `published_at`, clamped so it
        never exceeds the current time — a just-published scheduled
        announcement reads `updated == published` rather than
        updated-before-published, and a row whose last-edit timestamp
        is ahead of real time (clock skew, or accumulated
        strict-advance drift) reads the current time instead of that
        future value. Timestamps use full sub-second precision (RFC
        3339 with fractional seconds) so edits within the same
        wall-clock second still render distinct values.
      responses:
        "200":
          description: Atom feed
          headers:
            Cache-Control:
              schema:
                type: string
              description: Always `public, max-age=300`.
          content:
            application/atom+xml:
              schema:
                type: string
        "500":
          description: Database error rendering the feed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /feed/{token}/rss:
    get:
      summary: Public Atom/RSS incident feed (unauthenticated, token-gated)
      security: []
      description: |
        Atom rendering of the same incidents as `GET /feed/{token}`. The
        feed title is always `Incidents`, for every owner (issue #514).
        Each entry summary names the monitor by host only, derived the
        same way as `FeedIncident.monitor_host`. Rate-limited the same as
        the JSON feed: 20 requests per minute per token.
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Atom feed
          content:
            application/atom+xml:
              schema:
                type: string
        "404":
          description: Unknown or rotated token
        "429":
          description: Rate limit exceeded
          headers:
            Retry-After:
              schema:
                type: integer
  /api/v1/account/feed-token:
    get:
      summary: Get the current feed token for the authenticated account
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Token
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FeedTokenResponse"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/account/feed-token/rotate:
    post:
      summary: Rotate the feed token (old token stops working immediately)
      security:
        - bearerAuth: []
      responses:
        "200":
          description: New token
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FeedTokenResponse"
        "401":
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/events/ticket:
    post:
      operationId: issueSSETicket
      summary: Issue a single-use SSE connection ticket
      description: |
        Mints a short-lived ticket that the dashboard exchanges for an SSE
        connection at `GET /api/v1/events/stream`. Requires Bearer auth.
        Ticket TTL is 30 seconds; tickets are single-use.
        Rate limited to 20 ticket mints per minute per credential (issue
        #339 — an API key is one credential shared by every caller who
        presents it; a session/OAuth-JWT caller is bucketed per user, not
        per account).
      tags: [Events]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Ticket issued.
          content:
            application/json:
              schema:
                type: object
                required: [ticket, expires_in]
                properties:
                  ticket:
                    type: string
                    description: Opaque single-use token, base64url encoded.
                  expires_in:
                    type: integer
                    description: Seconds until the ticket expires.
                    example: 30
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          description: |
            Per-credential ticket-mint rate limit exceeded (20
            requests/minute, fixed window, keyed the same way as the
            connection cap above — not per account). Distinct from the
            dispatcher-wide 200/min limit (`components.responses.RateLimited`)
            — this limiter only counts ticket mints. The `Retry-After`
            header gives the integer seconds until the oldest mint slides
            out of the window.
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds until the next ticket mint is allowed.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: ticket rate limit exceeded
  /api/v1/events/stream:
    get:
      operationId: subscribeSSEStream
      summary: Subscribe to the live event stream (SSE)
      description: |
        Consumes a ticket from `POST /api/v1/events/ticket` and upgrades the
        HTTP response to an SSE stream (`text/event-stream`). Each frame is a
        JSON envelope with `type`, `monitor_ref`, `occurred_at`, and a
        type-specific `data` payload — `monitor_ref` is `""` for an
        account-level event (issue #412 replaced the old nullable numeric
        `monitor_id` with this always-present string). See
        `docs/SSE_LIVE_UPDATES_SPEC.md` for the four event types and their
        payloads. Heartbeat comments
        (`: heartbeat`) are emitted every 25 seconds.

        **Credential re-checked at open AND periodically while connected
        (issue #339).** A ticket's bound credential — the account, the
        minting user, and the API key if one was presented — is re-verified
        against durable storage both when the ticket is redeemed and, once
        the stream is open, every ~30 seconds thereafter. Removing the
        minting user from the account, revoking the API key past its grace
        window, or suspending the account closes an already-open stream
        within roughly 45 seconds on a healthy connection (a 30s recheck
        interval + 5s check timeout detects the revocation and cancels the
        stream in ~35s, plus up to a further 10s write deadline for an
        in-flight write/flush to unblock and the stream to actually close)
        — not instantly, and not a hard worst case: the write deadline is
        armed only for the duration of a write+flush and cleared between
        frames, so it bounds the handler's own blocking, not a stalled
        HTTP/2 connection writer. A transient failure (e.g. a database
        hiccup) never closes an open stream on its own; it only delays how
        soon a genuine revocation takes effect.
      tags: [Events]
      security: []
      parameters:
        - name: ticket
          in: query
          required: true
          schema:
            type: string
          description: Single-use ticket from `POST /api/v1/events/ticket`.
      responses:
        "200":
          description: SSE stream opened.
          content:
            text/event-stream:
              schema:
                type: string
                description: Server-Sent Events stream.
        "401":
          description: |
            Missing, invalid, expired, or already-consumed ticket — or a
            ticket whose bound API key has been revoked. A ticket refused
            here for a revoked key is also consumed (burned): the same
            ticket value cannot be retried even within its remaining TTL.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: |
            The ticket's bound user is no longer a member of the account,
            or the account is suspended. Also consumes (burns) the
            ticket — it cannot be retried.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: |
            Max concurrent SSE connections per credential reached (10 per
            credential — an API key, or a user for session/OAuth-JWT
            auth). This is a connection-cap rejection, not a rate-window
            rejection, so `Retry-After` is intentionally **not** set:
            retry depends on a peer disconnecting (no server-side clock
            event), and a guessed value would mislead clients into tight
            retry loops. Each API key has its own independent 10-slot
            budget shared across every caller who presents it; each
            session/OAuth-JWT user has their own independent 10-slot
            budget on the account, separate from every other user on that
            account. **This budget is shared with MCP GET `/mcp`
            streams** — REST event streams and MCP streams draw from the
            same per-credential counter, so a credential with zero open
            MCP streams can still hit this 429 if its REST streams (or
            vice versa) hold every slot. This 429's body text is shared
            byte-for-byte with the MCP refusal. This route is mounted
            outside the `/api/v1/*` Bearer block, so the dispatcher-wide
            200/min limiter (`components.responses.RateLimited`) does not
            apply here — the connection cap is the only 429 source. A
            429 here does NOT consume the ticket — retry with the same
            one once a slot frees.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /api/v1/push/subscribe:
    post:
      operationId: subscribeBrowserPush
      summary: Register a browser Web Push subscription
      description: |
        Persists the browser's `PushSubscription` object so the dispatcher
        can deliver notifications on monitor state transitions. The
        `p256dh` and `auth` fields are write-only secrets used server-side
        to encrypt push payloads — they are NEVER returned in the
        response. The 64 KB body limit and the global per-account
        200/min rate limiter both apply. Per-account cap is enforced
        atomically: an account holds **exactly 20** active subscriptions
        at steady state — concurrent subscribes never produce a 21st
        row. The 21st insert evicts the oldest by `created_at` (FIFO).
        The `endpoint` must be an `https://` URL with a public hostname;
        private/loopback/link-local/mDNS endpoints are rejected with
        `400 {"error":"endpoint must be HTTPS"}` (SSRF hardening).
      tags: [Push]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PushSubscriptionRequest"
      responses:
        "201":
          description: Subscription stored.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PushSubscriptionResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "413":
          $ref: "#/components/responses/RequestEntityTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/push/subscribe/{subscriptionID}:
    delete:
      operationId: unsubscribeBrowserPush
      summary: Revoke a browser Web Push subscription
      description: |
        Removes the subscription if and only if it belongs to the calling
        account. A subscription that exists but belongs to another
        account is indistinguishable from one that does not exist —
        both return 404. This is intentional: the API does not leak
        cross-account row existence.
      tags: [Push]
      security:
        - bearerAuth: []
      parameters:
        - name: subscriptionID
          in: path
          required: true
          schema:
            type: integer
            format: int64
          description: Push subscription ID.
      responses:
        "204":
          description: Subscription deleted.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "404":
          description: No subscription matched (or it belongs to another account).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/push/subscriptions:
    get:
      operationId: listBrowserPushSubscriptions
      summary: List the calling account's active push subscriptions
      description: |
        Returns the calling account's active push subscriptions newest
        first. The `p256dh` and `auth` secrets are NEVER included in
        the response. Returns `[]` (not `null`) when the account has
        no subscriptions.
      tags: [Push]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: Subscriptions list.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/PushSubscriptionResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
  /api/v1/push/vapid-public-key:
    get:
      operationId: getBrowserPushVapidPublicKey
      summary: Fetch the dispatcher's VAPID application-server public key
      description: |
        Returns the base64url-encoded application-server public key the
        SPA must pass to `PushManager.subscribe({applicationServerKey})`
        before posting the resulting subscription to
        `POST /api/v1/push/subscribe`. The key is the public half of a
        VAPID keypair generated on the dispatcher's first boot and
        persisted thereafter — not a secret, but auth-gated so the SPA
        already has a token by the time it asks. Returns 503 in the
        defensive case where the dispatcher router is up but the
        keypair has not been initialised yet (not reachable on the
        current boot order).
      tags: [Push]
      security:
        - bearerAuth: []
      responses:
        "200":
          description: VAPID public key.
          content:
            application/json:
              schema:
                type: object
                required: [public_key]
                properties:
                  public_key:
                    type: string
                    description: |
                      Base64url-encoded (unpadded) uncompressed P-256
                      public key, ~87 characters, alphabet
                      `[-_A-Za-z0-9]`. Pass this directly as
                      `applicationServerKey` to
                      `PushManager.subscribe`.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/AccountSuspended"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          description: VAPID keypair not yet initialised.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /{token}:
    servers:
      - url: https://status.monitive.com
        description: Swift status page host (STATUS_PAGE_URL); stats.monitive.com and status.uptimemonitoring.com redirect here
    get:
      operationId: getStatusPageHTML
      summary: Public status page (issue #368)
      description: |
        Unauthenticated — the token is the only credential, same shape as
        `/feed/{token}`. Served on the shared `status.monitive.com` host
        (`STATUS_PAGE_URL`), not under `/api/v1`; Cloudflare and the origin
        send only paths matching `^/sp_[0-9a-f]{32}(/|$)` to this router,
        while every nonmatching path remains on Monitive Classic. A request
        to this path on the API host 404s. Any
        method other than `GET` on this path (`HEAD`/`POST`/`PUT`/`DELETE`)
        also 404s, never 405. A token that doesn't match the pattern below
        gets the same 404 without a database lookup. Carries `Age` (seconds
        the served copy has aged at the origin) and `Cache-Control: public,
        max-age=<N>`, where `N` is the full freshness lifetime the view was
        cached under — 60 for a settled view, 5 for one where the live
        status currently disagrees with the open incident rows — never
        reduced by `Age`, since a cache already subtracts `Age` from
        `max-age` itself; both headers are computed the same way on the
        RSS/Atom/JSON/badge siblings below.
      tags: [Public]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
            pattern: '^sp_[0-9a-f]{32}$'
      responses:
        "200":
          description: HTML status page.
          headers:
            Age:
              $ref: "#/components/headers/StatusPageAge"
            Cache-Control:
              $ref: "#/components/headers/StatusPageCacheControl"
          content:
            text/html: {}
        "404":
          $ref: "#/components/responses/StatusPageNotFound"
        "500":
          $ref: "#/components/responses/StatusPageInternalError"
        "503":
          $ref: "#/components/responses/StatusPageUnavailable"
  /{token}/feed.rss:
    servers:
      - url: https://status.monitive.com
        description: Swift status page host (STATUS_PAGE_URL); stats.monitive.com and status.uptimemonitoring.com redirect here
    get:
      operationId: getStatusPageRSS
      summary: Public status page, RSS 2.0 (issue #368)
      tags: [Public]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
            pattern: '^sp_[0-9a-f]{32}$'
      responses:
        "200":
          description: RSS 2.0 feed of down/up events, capped at 50, newest-first.
          headers:
            Age:
              $ref: "#/components/headers/StatusPageAge"
            Cache-Control:
              $ref: "#/components/headers/StatusPageCacheControl"
          content:
            application/rss+xml: {}
        "404":
          $ref: "#/components/responses/StatusPageNotFound"
        "500":
          $ref: "#/components/responses/StatusPageInternalError"
        "503":
          $ref: "#/components/responses/StatusPageUnavailable"
  /{token}/feed.atom:
    servers:
      - url: https://status.monitive.com
        description: Swift status page host (STATUS_PAGE_URL); stats.monitive.com and status.uptimemonitoring.com redirect here
    get:
      operationId: getStatusPageAtom
      summary: Public status page, Atom (issue #368)
      tags: [Public]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
            pattern: '^sp_[0-9a-f]{32}$'
      responses:
        "200":
          description: Atom feed of down/up events, capped at 50, newest-first.
          headers:
            Age:
              $ref: "#/components/headers/StatusPageAge"
            Cache-Control:
              $ref: "#/components/headers/StatusPageCacheControl"
          content:
            application/atom+xml: {}
        "404":
          $ref: "#/components/responses/StatusPageNotFound"
        "500":
          $ref: "#/components/responses/StatusPageInternalError"
        "503":
          $ref: "#/components/responses/StatusPageUnavailable"
  /{token}/status.json:
    servers:
      - url: https://status.monitive.com
        description: Swift status page host (STATUS_PAGE_URL); stats.monitive.com and status.uptimemonitoring.com redirect here
    get:
      operationId: getStatusPageJSON
      summary: Public status page, JSON (issue #368)
      tags: [Public]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
            pattern: '^sp_[0-9a-f]{32}$'
      responses:
        "200":
          description: JSON status page.
          headers:
            Age:
              $ref: "#/components/headers/StatusPageAge"
            Cache-Control:
              $ref: "#/components/headers/StatusPageCacheControl"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StatusPageJSON"
        "404":
          $ref: "#/components/responses/StatusPageNotFound"
        "500":
          $ref: "#/components/responses/StatusPageInternalError"
        "503":
          $ref: "#/components/responses/StatusPageUnavailable"
  /{token}/badge.svg:
    servers:
      - url: https://status.monitive.com
        description: Swift status page host (STATUS_PAGE_URL); stats.monitive.com and status.uptimemonitoring.com redirect here
    get:
      operationId: getStatusPageBadge
      summary: Public status page, SVG uptime badge (issue #383)
      description: |
        A static, namespaced SVG — a fixed "uptime" label plus a
        status-colored message, `<pct>%` (or `no data` when the 30-day
        average has no data yet) while the monitor is up, and
        `<pct>% · <state>` (or `no data · <state>`) in any other state,
        e.g. `99.90% · down` (issue #410); the `<title>`/`aria-label`
        always names the state — rendered
        from the same cached `View` the HTML page, RSS, Atom, and JSON
        siblings share — requests landing on the same cache entry always
        render identical state, but a rebuild after the entry's TTL
        expires (or a downstream cache holding the two URLs
        independently) can leave the badge and page briefly disagreeing
        across that boundary. Resolved, cached, and error-handled
        identically to those four siblings (same token-shape check, same
        `GetStatusPageByToken` lookup folding an unknown/off/deleted/
        suspended token into one 404, same view cache and
        `Age`/`Cache-Control` computation, recomputed from the live clock
        on every response). No
        style element, no inline style attribute, no script element, and
        no external reference — presentation attributes only, so the
        document stays inside the status host's Content-Security-Policy
        and renders safely through an image proxy such as GitHub's camo.
      tags: [Public]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
            pattern: '^sp_[0-9a-f]{32}$'
      responses:
        "200":
          description: SVG uptime badge.
          headers:
            Age:
              $ref: "#/components/headers/StatusPageAge"
            Cache-Control:
              $ref: "#/components/headers/StatusPageCacheControl"
          content:
            image/svg+xml: {}
        "404":
          $ref: "#/components/responses/StatusPageNotFound"
        "500":
          $ref: "#/components/responses/StatusPageInternalError"
        "503":
          $ref: "#/components/responses/StatusPageUnavailable"
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        API key (`mk_live_*`) or session token from OAuth exchange.
        API keys created before the switch to the `mk_live_` prefix start
        with `umk_live_`; they keep working permanently and need no change.
  parameters:
    keyID:
      name: keyID
      in: path
      required: true
      schema:
        type: integer
        format: int64
      description: API key ID.
    pageID:
      name: pageID
      in: path
      required: true
      schema:
        type: integer
        format: int64
        minimum: 1
      description: Group status page ID (issue #642).
    monitorID:
      name: monitorID
      in: path
      required: true
      schema:
        type: string
        pattern: "^([0-9]+|[0-9a-hjkmnp-tv-z]{6}-[1-9][0-9]*)$"
      description: >-
        Numeric monitor id or ref (issue #412), e.g. "k7q2mx-14". A ref whose handle belongs to a different account, or whose number doesn't resolve, 404s the same as a nonexistent numeric id.
  schemas:
    LegacyMigrationOutcome:
      type: object
      description: |
        Issue #540: why a Monitive Classic migration-link token did not
        skip legacy routing. Present only when a token was presented and was
        ineligible or could not be checked; an eligible token adds nothing.
      required: [eligible, reason]
      properties:
        eligible:
          type: boolean
          enum: [false]
        reason:
          type: string
          enum: [unknown_link, already_moved, expired, not_owner, not_free, not_exported, billing_unavailable, unavailable]
          description: One of Classic's refusal reasons, or `unavailable` when the resolve call itself failed.
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
      example:
        error: something went wrong
    HostFanError:
      description: |
        429 body returned when a host-fan allowance is exceeded on
        `POST /api/v1/monitors`, or on a `PUT /api/v1/monitors/{monitorID}`
        that changes `url` or `type` (issue #335). The account is not
        suspended; retry after `retry_after_seconds`. `limit` and
        `window_seconds` identify the controlling cap: either the account's
        inclusive plan-derived or explicit burst allowance in the 30-minute
        default burst window, or the inclusive `2 * max_monitors` allowance
        in the fixed rolling 24-hour window. If both reject, the response
        reports whichever needs the later expiry; an exact tie reports daily.
      type: object
      required: [error, limit, window_seconds, retry_after_seconds]
      properties:
        error:
          type: string
          example: "too many distinct domains in a rolling window; slow monitor creation or target changes and retry"
        limit:
          type: integer
          description: Maximum distinct registrable domains (eTLD+1) allowed in the window (inclusive).
          example: 100
        window_seconds:
          type: integer
          description: Length of the sliding window in seconds.
          example: 1800
        retry_after_seconds:
          type: integer
          description: Seconds until enough qualifying domains leave the controlling window.
          example: 347
    MonitorLimitError:
      description: |
        409 body returned by `POST /api/v1/monitors` when the account is
        at its plan's hard monitor cap (issue #512), and by
        `PUT /api/v1/monitors/{monitorID}` when it would enable a paused
        monitor while the account already has `limit` enabled monitors
        (issue #595). Nothing is written.
        `error` is unchanged from before issue #512, so clients that match
        on it keep working; the other four fields are additive.
      type: object
      required: [error, limit, current, plan, hint]
      properties:
        error:
          type: string
          enum: ["monitor limit reached"]
        limit:
          type: integer
          description: The plan's hard monitor cap — `limits.max_monitors` on `GET /api/v1/account`.
          example: 100
        current:
          type: integer
          description: >-
            On create, every monitor on the account (paused ones included) when the create was refused; on a resume, the account's other enabled monitors. Can exceed `limit` when the cap was lowered below an existing count.
          example: 100
        plan:
          type: string
          enum: [free, complimentary, basic, pro, business]
          description: The account's plan.
        hint:
          type: string
          description: >-
            How to raise the limit. Names the plan's advertised (soft-cap) number, `limits.soft_cap_monitors`, never `limit` (issue #593).
          example: "Your plan includes 50 monitors, and this account has no room for more. Email hello@monitive.com to raise the limit."
    Invite:
      type: object
      description: An owner-issued invitation, as seen by the account's owners (issue #325).
      properties:
        id:
          type: integer
          format: int64
        github_id:
          type: integer
          format: int64
        github_username:
          type: string
        role:
          type: string
          enum: [owner, member, viewer]
        created_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
          description: Always `created_at` + 7 days.
    Member:
      type: object
      description: >-
        One row of `GET /api/v1/account/members` — a user's role on the account, joined with enough identity to render a members list without a second round trip (issue #324; `display_name`/`initials` added by issue #495).
      properties:
        user_id:
          type: integer
          format: int64
        role:
          type: string
          enum: [owner, member, viewer]
        github_username:
          type: string
        email:
          type: ["string", "null"]
        display_name:
          type: ["string", "null"]
          description: The member's stored real name (issue #495), null when they have none on file.
        initials:
          type: string
          description: >-
            `UserInitials(display_name, handle)` — derived from `display_name` when set, else from `github_username` falling back to the local part of `email`; the same function an incident acknowledgement's `initials` uses.
        created_at:
          type: string
          format: date-time
    UserInvite:
      type: object
      description: An invite addressed to the signed-in user, as seen via `GET /api/v1/me/invites` (issue #325).
      properties:
        id:
          type: integer
          format: int64
        account_label:
          type: string
          description: |
            The account's earliest owner's `github_username` when
            non-empty, else `"account <id>"` — never an email address.
        github_username:
          type: string
        role:
          type: string
          enum: [owner, member, viewer]
        created_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
    Account:
      type: object
      properties:
        id:
          type: integer
          format: int64
        handle:
          type: string
          description: >-
            Six-character lowercase Crockford base32 ref-prefix (issue #412), e.g. "k7q2mx" — stable, unique, never reused. Safe to show to the account's own members: unlike id, it is not sequential and does not reveal account count or age.
        github_id:
          type: integer
          format: int64
          description: |
            GitHub numeric ID of the account's owner. Since issue #311,
            sourced from `users.github_id` via the account's owner
            membership (`account_members`), not a column on `accounts`
            itself — display-only, never an authorization input. `0` for
            an owner whose identity is email-only (issue #315) rather than
            GitHub — never `null`.
        github_username:
          type: string
          description: |
            GitHub username of the account's owner, sourced the same way
            as github_id. `""` (empty string) for an email-only owner —
            never `null`.
        email:
          type: ["string", "null"]
          description: |
            Any verified email identity held by the account's owner —
            either the address behind an email-identity sign-in (issue
            #315, sign-in part A) or one GitHub reported as verified and
            primary, adopted onto the owner's `users` row on a sign-in
            that found none on file yet (issue #390) — sourced from
            `users.email` via the account's owner membership, the same
            way github_id/github_username are. `null` when the owner holds
            no verified email of either kind. Display-only, never an
            authorization input; never present on any public,
            unauthenticated surface (`GET /feed/{token}`, `GET
            /feed/{token}/rss`). Omitted entirely (issue #323, team
            accounts B1) unless the authenticated caller's OWN role is
            `owner` (issue #325: an account can have more than one owner,
            so this is no longer "caller is THE owner") — a viewer or
            member on the same account never sees it, regardless of
            whether the account's (earliest) owner has adopted an email of
            either kind.
        notification_email:
          type: ["string", "null"]
        role:
          type: string
          enum: [viewer, member, owner]
          description: |
            The AUTHENTICATED CALLER's own authority on this account (issue
            #323, team accounts B1) — not a property of the account itself.
            Always present. The SPA uses this to hide owner/member-only
            controls.
        is_admin:
          type: boolean
          description: |
            True when the authenticated account is in the admins table —
            i.e. the same answer auth.RequireAdmin returns for any
            admin-gated route. Always present on GET /api/v1/account and
            on the PATCH /api/v1/account success response.
        last_cap_hit_at:
          type: ["string", "null"]
          format: date-time
          description: |
            Timestamp of the latest successfully recorded POST
            /api/v1/monitors (or MCP create_monitor) rejection for hitting
            the account's resolved per-account hard cap (`limits.max_monitors`
            — issue #507; 100 monitors on the free plan, but an admin-set
            override on a `complimentary` account can differ, and each paid
            plan has its own cap) — not a
            guaranteed latest-refusal timestamp. Updates are coalesced to at most once
            per account per minute, and a failure to record a hit is
            swallowed (the REST 409 or MCP tool-error result the client
            sees is unaffected either way), so a refusal can occur
            without advancing this field, and null
            does not prove the account has never been refused. Advisory
            only — the app uses it to time an upgrade offer; never cleared
            once set.
        silent_monitors:
          type: integer
          description: |
            Count of ENABLED monitors on this account with no ACTIVE
            attached recipient (issue #212). "Active" excludes a disabled
            recipient and a still-unconfirmed (`pending`) email recipient
            (issue #321) — a monitor whose only attached recipient is
            pending or disabled is counted as silent, the same as one with
            no attached recipient at all. Disabling a monitor removes it
            from this count — a disabled, unreachable monitor is not
            flagged as silent since it is not being checked. Present on
            both `GET` and `PATCH /api/v1/account`.
        plan:
          type: string
          enum: [free, complimentary, basic, pro, business]
          description: >-
            The account's billing/feature plan (issue #507). "free" by default; "complimentary" when an operator has moved it there through the operator-only plan endpoint; "basic", "pro" or "business" (issue #593) set only by billing. Visible to every role.
        limits:
          $ref: "#/components/schemas/AccountPlanLimits"
        billing_enabled:
          type: boolean
          description: >-
            True when billing is open to every account (the `BILLING_OPEN` boot flag) or staff turned on this account's billing preview (issue #592). Visible to every role. Present on `GET` and `PATCH /api/v1/account`; the stored staff-set flag itself is never serialized here.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    AccountPlanLimits:
      type: object
      description: >-
        The account's resolved plan limits (issue #507) — models.PlanLimits projected onto the wire, plus the derived allowed_grace_s. Every field is present on both GET and PATCH /api/v1/account, for every role.
      required:
        - max_monitors
        - soft_cap_monitors
        - min_interval_sec
        - visible_history_days
        - grace_adjustable
        - allowed_grace_s
        - alert_channels
        - host_fan_threshold
      properties:
        max_monitors:
          type: integer
          description: >-
            The enforced maximum number of monitors for the account's plan. The plan's advertised number is `soft_cap_monitors`.
        soft_cap_monitors:
          type: integer
          description: >-
            The highest per-account monitor count that does NOT carry a soft_cap_reached notice — the notice window is (soft_cap_monitors, max_monitors]. Always less than max_monitors. 50 on free; 100, 250 and 1000 on the paid plans. The advertised number, and the only number cap messages print.
        min_interval_sec:
          type: integer
          description: The minimum monitors.interval_sec a create or update may set. 60 on every plan today.
        visible_history_days:
          type: integer
          description: >-
            How many days back GET /incidents, GET /incidents/{id}, the public feed, and MCP list_incidents read. 30 on every plan today — never above the physical retention window.
        grace_adjustable:
          type: boolean
          description: >-
            Whether allowed_grace_s may contain more than one value. true on the paid plans, false on free and complimentary.
        allowed_grace_s:
          type: array
          items:
            type: integer
          description: >-
            The permitted values for a monitor_recipients grace_s (down_delay_s). `[120]` on free and complimentary; all 15 values on the paid plans.
        alert_channels:
          type: array
          items:
            type: string
            enum: [webhook, email, slack, pagerduty]
          description: The closed set of recipient types this account may create.
        host_fan_threshold:
          type: ["integer", "null"]
          description: >-
            The effective inclusive burst allowance for distinct registrable domains. It derives from resolved max_monitors after cap overrides, unless a valid complimentary host_fan_threshold override replaces it. The Nth domain is accepted and N+1 is refused with a host-fan 429 whose limit is this same value. Current plans always report a number; null is reserved for a future plan-level no-burst-limit value. The separate daily allowance is always 2 * max_monitors, and port-fan is unchanged and not reported here.
    AccountPatchInput:
      type: object
      required: [notification_email]
      additionalProperties: false
      properties:
        notification_email:
          type: ["string", "null"]
          maxLength: 254
          description: |
            New notification_email value. JSON null or an empty string
            clears the field. Otherwise the value must parse as an
            RFC 5322 address. Must be valid UTF-8 with no null bytes;
            violations return HTTP 400.
          example: user@example.com
    Monitor:
      type: object
      properties:
        id:
          type: integer
          format: int64
        number:
          type: integer
          format: int64
          description: >-
            This monitor's per-account sequence number (issue #412), assigned once at creation and never reused.
        ref:
          type: string
          description: >-
            Stable "<account handle>-<number>" reference, e.g. "k7q2mx-14" — accepted anywhere `{monitorID}` appears in a path, in place of the numeric id.
        account_id:
          type: integer
          format: int64
        name:
          type: string
          example: Production API
        url:
          type: string
          description: |
            Target URL. Format depends on `type`:
              * `http` — full http(s) URL, e.g. `https://api.example.com/health`.
              * `tcp` — always returned/stored as `tcp://host:port`, port
                restricted to a whitelist (see `MonitorInput.url` for the
                accepted input shapes).
              * `ping` — a bare hostname or IP literal (e.g.
                `api.example.com`, `1.1.1.1`) — no scheme, path, query,
                userinfo, or port.
              * `dns` / `ssl` — reserved formats (a bare hostname for `dns`)
                for a `type` that is defined but not yet serviced by the
                check engine; see the `type` field.
          example: https://api.example.com/health
        type:
          type: string
          description: |
            `http`, `tcp`, and `ping` can appear here. `dns` and `ssl` are
            reserved for a check engine that does not exist yet (issue
            #209); no monitor of one of those two types can be created,
            updated, or persisted.
          enum: [http, tcp, ping]
        interval_sec:
          type: integer
          minimum: 60
          example: 60
        expected_status:
          type: string
          description: Single HTTP status code, expressed as a string, 100–599. Defaults to "200".
          example: "200"
        body_match:
          type: ["string", "null"]
        enabled:
          type: boolean
        response_time_threshold_ms:
          type: ["integer", "null"]
          description: Alert if response time exceeds this (ms). Null = disabled.
        maintenance:
          $ref: "#/components/schemas/MaintenanceWindow"
        method:
          type: string
          enum: [GET, POST, PUT, DELETE, PATCH, OPTIONS]
          description: |
            HTTP request method (issue #364). Always `GET` for `tcp`/`ping`/
            `dns`/`ssl` monitors, regardless of what might once have been
            stored — a non-http monitor's custom-request fields are always
            reset to their defaults on write.
        body:
          type: string
          description: |
            Request body, verbatim (issue #364). Always `""` for a non-http
            monitor. Unlike `headers`, the body is NOT write-only — it is
            returned verbatim on every read to anyone who can read the
            monitor. It must not contain credentials or other sensitive
            data unless that exposure is acceptable; `headers` is the
            write-only place for secrets.
        headers:
          type: array
          items:
            $ref: "#/components/schemas/RequestHeader"
          description: |
            Custom request headers (issue #364), write-only: each entry
            reports only `name` and `value_set`, never the value itself.
            Always `[]` for a non-http monitor.
        timeout_sec:
          type: integer
          minimum: 1
          maximum: 30
          description: Request timeout in seconds (issue #364). Always `30` for a non-http monitor.
        regions:
          type: [array, "null"]
          items:
            type: string
            enum: [EU, US-E, US-W, ASIA, OCE, SA]
          minItems: 1
          uniqueItems: true
          description: |
            The regions this monitor checks and confirms from (issue #572),
            in canonical order (EU, US-E, US-W, ASIA, OCE, SA). `null` means
            every region, including regions added to the fleet later.
            Always present. Checks, re-checks and down confirmation never
            leave the selection.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    RequestHeader:
      type: object
      description: |
        One custom request header (issue #364). Write-only: the value
        itself is never present on a read — only whether one is set.
      required: [name, value_set]
      properties:
        name:
          type: string
        value_set:
          type: boolean
          description: Whether this header carries a non-empty value.
    MaintenanceWindow:
      type: object
      description: |
        A monitor's single alert-silencing window (issue #361). Always
        present on a `Monitor`; `{"type":"none"}` (the default) silences
        nothing. Accepted on `MonitorInput`/`MonitorCreateInput` as one of
        three discriminated shapes — each accepts ONLY the fields listed
        for it, plus `type`; any other field (including one that belongs to
        a different shape) is `400` naming it, e.g.
        `maintenance.timezone: not allowed for type "once"`.
          * `none` — no other fields.
          * `daily` — `start_time`, `end_time`, `timezone` all required.
            Repeats every day in that IANA zone; may span midnight
            (`start_time > end_time`). `start_time` must differ from
            `end_time`. The zone must be a real IANA name — empty, `Local`,
            and anything `LoadLocation` can't resolve are all rejected.
          * `once` — `starts_at`, `ends_at` both required, `ends_at` after
            `starts_at`. A single absolute span; no zone, since both
            instants are already pinned by their offsets. Both timestamps
            are normalized to UTC at microsecond precision (PostgreSQL's
            `timestamptz` precision) before being validated or stored, so
            two timestamps that differ only below a microsecond collapse to
            equal and are rejected as `ends_at` not being after `starts_at`.
        On `PUT`, omitting `maintenance` entirely leaves the stored window
        unchanged; an explicit JSON `null` is `400`
        (`maintenance must not be null`) — the same rule `recipients`
        follows elsewhere. `POST` omitting it defaults to `{"type":"none"}`.
      properties:
        type:
          type: string
          enum: [none, daily, once]
        start_time:
          type: string
          description: '"HH:MM", daily only. Canonical: zero seconds, below 24:00.'
          example: "23:00"
        end_time:
          type: string
          description: '"HH:MM", daily only.'
          example: "03:00"
        timezone:
          type: string
          description: IANA zone name, daily only.
          example: Europe/Lisbon
        starts_at:
          type: string
          format: date-time
          description: RFC3339, once only. Echoed back UTC-normalized at microsecond precision.
        ends_at:
          type: string
          format: date-time
          description: RFC3339, once only. Echoed back UTC-normalized at microsecond precision.
    MonitorState:
      type: object
      properties:
        monitor_id:
          type: integer
          format: int64
        status:
          type: string
          enum: [up, down, unknown, flapping, blocked]
          description: |
            `blocked` (issue #558): bot protection on the site is
            challenging every check, or (issue #621) the site's robots.txt
            does not allow Monitive to check it, so it is not reported as
            down.
        blocked_provider:
          type: ["string", "null"]
          enum: [cloudflare, aws_waf, robots_txt, null]
          readOnly: true
          description: >-
            Why the monitor is blocked (issue #623): `cloudflare` or `aws_waf` when that provider's bot protection challenges every check, `robots_txt` when the site's robots.txt does not allow Monitive to check it. While the monitor stays `blocked` the value follows the newest confirmed block: it changes when two blocked verdicts in a row name the same other reason. Set only while `status` is `blocked`, and null otherwise, including a blocked monitor whose reason was not recorded.
        last_check_at:
          type: ["string", "null"]
          format: date-time
        last_transition_at:
          type: ["string", "null"]
          format: date-time
        suspect_since:
          type: ["string", "null"]
          format: date-time
        flap_count_1h:
          type: integer
        flapping:
          type: boolean
        evidence_buffer:
          type: array
          items:
            $ref: "#/components/schemas/CheckResult"
        primary_region:
          type: ["string", "null"]
          enum: [EU, US-E, US-W, ASIA, OCE, SA, null]
          description: >-
            The region whose probes run this monitor's scheduled checks: the region with the fastest connection to the target (TCP connect time for http and tcp, average round-trip time for ping), measured on create, on a URL, type or region-selection change, and by a one-time backfill. Regions within 5 ms of the fastest count as a tie, broken by a deterministic per-monitor hash. When no region answered, the deterministic hash pick within the monitor's regions. Null until assigned.
        primary_measured_at:
          type: ["string", "null"]
          format: date-time
          readOnly: true
          description: >-
            When the measurement that chose primary_region ran. Null when the current primary was not chosen by measurement (no region answered yet, or the primary changed for another reason, such as a probe fleet change).
        primary_rtt_ms:
          type: ["number", "null"]
          format: float
          readOnly: true
          description: >-
            The winning region's measured time in milliseconds (TCP connect for http and tcp, average round-trip time for ping). Null when the current primary was not chosen by measurement.
    CheckResult:
      type: object
      properties:
        timestamp:
          type: string
          format: date-time
        region:
          type: string
        status_code:
          type: integer
        error_class:
          type: string
        dns_ms:
          type: number
        tls_ms:
          type: number
        connect_ms:
          type: number
        ttfb_ms:
          type: number
        download_ms:
          type: number
        content_length:
          type: integer
          format: int64
        response_hash:
          type: string
        packet_loss_pct:
          type: number
          minimum: 0
          maximum: 100
          description: |
            Ping-only packet loss percentage (0-100). Omitted (not present
            in the object) when not measured — every non-ping check result,
            and a ping probe-side failure that never reached the target. A
            measured 0% loss is present with value 0, distinct from omitted.
    MonitorInput:
      type: object
      description: |
        All string fields must be valid UTF-8 with no null bytes.
        URL fields must additionally be free of ASCII control characters
        (U+0000..U+001F and U+007F). Violations return HTTP 400.
      properties:
        name:
          type: string
          maxLength: 255
        url:
          type: string
          maxLength: 2048
          description: |
            Target URL. Format depends on `type`:
              * `http` — full http(s) URL.
              * `tcp` — `host:port` or `tcp://host:port`, port restricted to
                a fixed allowlist (issue #331): 21, 22, 25, 80, 110, 143,
                443, 465, 587, 993, 995, 2222, 3000, 3306, 5000, 5432, 6379,
                8000, 8080, 8443, 8888, or 27017. Every create,
                and every update whose body includes `url` or `type`, stores
                the canonical `tcp://host:port` form (lowercase, no path)
                regardless of which shape was sent — `example.com:443`,
                `tcp://example.com:443`, and `tcp://EXAMPLE.com:443/` all
                store as `tcp://example.com:443`. An update that changes
                neither `url` nor `type` leaves the stored URL as it is. A
                bracketed IPv6 literal is required (`[2001:db8::1]:443`); an
                unbracketed one is rejected as ambiguous.
              * `ping` — a bare hostname or IP literal (e.g.
                `api.example.com`, `1.1.1.1`) — no scheme, path, query,
                userinfo, or port.
              * `dns` / `ssl` — reserved formats (a bare hostname for `dns`)
                for a `type` that is defined but not yet serviced by the
                check engine; see the `type` field.
        type:
          type: string
          description: |
            `http`, `tcp`, and `ping` are accepted on create or update.
            `dns` and `ssl` are defined in the wire format but rejected
            with `400` (issue #209): `type must be one of: http, tcp, ping,
            dns, ssl (currently available: http, ping, tcp)` for an
            unrecognized value, or `type '<type>' is not available yet; the
            check engine currently supports: http, ping, tcp` for one of
            those two.
          enum: [http, tcp, ping]
        interval_sec:
          type: integer
          minimum: 60
          description: Check interval in seconds. Default 60.
        expected_status:
          type: string
          description: |
            HTTP status range. Default: 200-399. Accepted but silently
            ignored for `type: tcp` or `type: ping` (neither has an HTTP
            response to evaluate it against).
        body_match:
          type: string
          maxLength: 1024
          description: |
            Optional string to match in the response body. HTTP only —
            rejected with `400` (`body_match is not applicable to tcp
            monitors`) when `type` is `tcp`. Accepted but silently ignored
            (a harmless no-op; wopher's ping check never reads it) when
            `type` is `ping`.
        enabled:
          type: boolean
          description: Default true.
        maintenance:
          $ref: "#/components/schemas/MaintenanceWindow"
        method:
          type: string
          enum: [GET, POST, PUT, DELETE, PATCH, OPTIONS]
          description: |
            HTTP request method (issue #364). Default `GET`. HTTP only —
            sending this field at all (including its default value) on a
            `tcp` or `ping` create/update is `400`
            (`method is only applicable to http monitors`). On update,
            omitting it leaves the stored method unchanged; an explicit
            `null` is `400` (`method must not be null`) — but only when
            `null` is the value the request body actually decodes to:
            exact-duplicate JSON keys (same spelling) resolve via
            `encoding/json`'s last-value-wins before this check ever runs,
            so `{"method":null,"method":"POST"}` is accepted as `POST`;
            only a differently-cased duplicate (e.g. `Method` alongside
            `method`) is itself rejected, as more than one key for the
            same field. The same caveat applies to `body`/`timeout_sec`
            below, which share this rejection rule.
        body:
          type: string
          maxLength: 4096
          description: |
            Request body (issue #364). Default `""` — a bodiless POST is
            allowed. Must be valid UTF-8 with no null bytes. HTTP only, same
            rejection rule as `method`. Cleared by sending `""` on update.
        headers:
          type: array
          maxItems: 20
          items:
            type: object
            required: [name]
            description: |
              The case-insensitive duplicate-key rejection described below
              for `name`/`value` applies only to the request's TOP-LEVEL
              keys (`method`, `body`, `headers`, `timeout_sec` — see
              `method`'s description above). It does NOT recurse into each
              header object: a header entry is decoded by
              `encoding/json` into a plain struct, which matches `name`/
              `value` case-insensitively and, when more than one JSON key
              in the same object folds to the same field (any casing, not
              just an exact-spelling duplicate), keeps whichever key
              occurs LAST in that object — e.g. `{"value":null,"Value":"x"}`
              decodes to `value: "x"`, not a rejection. Unknown properties
              on a header object are silently ignored by the same decode,
              not rejected.
            properties:
              name:
                type: string
                description: |
                  An RFC 7230 token. `Host`, `Content-Length`,
                  `Transfer-Encoding`, and `Connection` are rejected
                  case-insensitively, as are two entries with the same name
                  (case-insensitive). This is a check across the headers
                  array's entries, not of this field's own JSON key
                  spelling within one entry — see this schema's own
                  description above for that.
              value:
                type: string
                description: |
                  On `PUT`, an entry with `value` omitted keeps the
                  currently stored value for that name (case-insensitive
                  match) — the array as a whole still REPLACES the full
                  stored list, so omitting `headers` entirely (not sending
                  an entry at all) is what leaves every header untouched.
                  A name with no stored value and no `value` sent is `400`.
                  An explicit `null` is `400` (`header "<name>" value must
                  not be null`) when `null` is the value `encoding/json`
                  resolves this field to — see this schema's own
                  description above for how a same- or differently-cased
                  duplicate `value`/`Value` key within one header object
                  resolves instead (last occurrence wins, never rejected).
                  On `POST`, every entry must carry a `value` — there is
                  nothing stored yet to keep.
          description: |
            Custom request headers (issue #364), at most 20 entries and
            8192 bytes total (`len(name)+2+len(value)` summed). HTTP only,
            same rejection rule as `method`. Values must be valid UTF-8 with
            no CR, LF, NUL, or other control character except horizontal
            tab. On update, sending `url` with a different scheme,
            lowercased host, or effective port than the stored URL requires
            every resulting header to carry a `value` in THIS request — an
            omitted `headers` field (when headers are stored) or any
            kept-by-name entry is `400`
            (`headers must be resent with their values when the URL's
            scheme, host, or port changes`), closing the path where one
            account member could repoint another member's monitor (with
            its still-live secret header) at a host they control. An empty
            array (`[]`) clears every header.
        timeout_sec:
          type: integer
          minimum: 1
          maximum: 30
          description: |
            Request timeout in seconds (issue #364). Default 30. HTTP only,
            same rejection rule as `method`.
        regions:
          type: [array, "null"]
          items:
            type: string
            enum: [EU, US-E, US-W, ASIA, OCE, SA]
          minItems: 1
          uniqueItems: true
          description: |
            Restrict checks and down confirmation to these regions (issue
            #572), for every monitor type and free on every plan. Omitted:
            create checks from every region and update keeps the stored
            selection. `null` checks from every region, including ones added
            later. `[]`, an unknown region or a duplicate is a `422`. The
            selected regions must hold at least 3 probes in total (enabled
            probes, counted across the selection), otherwise `422`, for
            example `regions [SA] have 1 enabled probe; select regions with
            at least 3 probes in total`. A non-array or a non-string element
            is a `400`. Stored and returned in canonical order.
    MonitorCreateInput:
      description: |
        `POST /api/v1/monitors`'s own request shape (issue #329):
        `MonitorInput` plus `recipient_ids`/`recipients`. Not used by
        `PUT /monitors/{id}`, which stays on plain `MonitorInput` — a
        `recipient_ids` or `recipients` field in a PUT body is silently
        ignored, not validated.
      allOf:
        - $ref: "#/components/schemas/MonitorInput"
        - type: object
          properties:
            recipient_ids:
              type: ["array", "null"]
              items:
                type: integer
                format: int64
              description: |
                Selects which recipients to attach at create time. Three
                cases:
                  * Omitted or `null` — attach the account's default
                    recipients (`recipients.is_default`). Identical to
                    pre-#329 behavior.
                  * `[]` — attach none.
                  * A non-empty array — attach exactly those ids. Validated
                    like `PUT /monitors/{id}/recipients`: every id must be
                    positive and the array must not contain duplicates
                    (`400` before any write), and every id must be owned by
                    the calling account (`400`, checked before the
                    monitor-limit and duplicate-URL checks).

                Mutually exclusive with `recipients` — both present is
                `400`.
            recipients:
              type: array
              items:
                type: object
                required: [id]
                additionalProperties: false
                properties:
                  id:
                    type: integer
                    format: int64
                  grace_s:
                    type: integer
                    description: |
                      Seconds to hold a "down" alert before sending it
                      (issue #338, renamed from `down_delay_s` to "grace"
                      by issue #504). Optional; defaults to `120`. Fixed
                      at `120` on the free and complimentary plans — any
                      other value is `422`, naming the fixed value; paid
                      plans accept any of the 15 values (issue #593).
                  down_delay_s:
                    type: integer
                    deprecated: true
                    description: |
                      Deprecated alias for `grace_s` (issue #504) — same
                      column, same meaning. Send only one; sending both
                      with equal values is accepted, differing values is
                      `400`. Scheduled for removal around 2027-02-11.
              description: |
                `recipient_ids`'s alternative form (issue #338): attach
                exactly these pairs, each with its own `grace_s`.
                Mutually exclusive with `recipient_ids` — both present is
                `400`. Unlike `recipient_ids`, `null` is `400` rather than
                "attach defaults" — there is no sensible delay to default
                an implicit set to.
    MonitorListItem:
      description: Monitor with inline status summary for list views.
      allOf:
        - $ref: "#/components/schemas/Monitor"
        - type: object
          required: [flapping, regions_degraded, effective_interval_sec, blocked_provider]
          properties:
            status:
              type: string
              enum: [up, down, unknown, flapping, blocked]
              description: |
                `blocked` (issue #558): bot protection on the site is
                challenging every check, or (issue #621) the site's
                robots.txt does not allow Monitive to check it, so it is
                not reported as down.
            blocked_provider:
              type: ["string", "null"]
              enum: [cloudflare, aws_waf, robots_txt, null]
              readOnly: true
              description: >-
                Mirrors `MonitorState.blocked_provider`. Why the monitor is blocked (issue #623): `cloudflare` or `aws_waf` when that provider's bot protection challenges every check, `robots_txt` when the site's robots.txt does not allow Monitive to check it. While the monitor stays `blocked` the value follows the newest confirmed block: it changes when two blocked verdicts in a row name the same other reason. Set only while `status` is `blocked`, and null otherwise, including a blocked monitor whose reason was not recorded.
            last_check_at:
              type: ["string", "null"]
              format: date-time
            flapping:
              type: boolean
              description: |
                Mirrors `MonitorState.flapping` from `GET /monitors/{id}`.
                Always present. `status` stays `up`, `down`, or `unknown`
                while this is `true` — `status` is never `flapping` in
                practice (issue #453).
            recipient_ids:
              type: array
              items:
                type: integer
                format: int64
              description: Attached recipient ids (issue #212). Always present, `[]` for none.
            regions_degraded:
              type: boolean
              description: |
                True while the monitor's region selection is short of
                healthy probes (fewer than 3 for 3 minutes, issue #589) and
                its checks borrow probes from regions outside the
                selection; false again once the selection has had 3 or more
                healthy probes for 3 minutes. Computed at response time,
                never stored. Always present; `false` for a monitor with
                `regions` null.
            effective_interval_sec:
              type: integer
              readOnly: true
              description: |
                The interval, in seconds, scheduled checks actually run at
                (issue #621): `interval_sec`, or the site's robots.txt
                `Crawl-delay` for Monitive when that is longer (capped at
                86400). Computed at response time from the in-memory
                robots.txt cache, never stored. Always present; equal to
                `interval_sec` when no Crawl-delay applies. Test checks,
                cross-region confirmation checks and the create-time check
                are never paced by it.
    MonitorDetail:
      type: object
      required: [regions_degraded, effective_interval_sec]
      properties:
        monitor:
          $ref: "#/components/schemas/Monitor"
        state:
          $ref: "#/components/schemas/MonitorState"
        notice:
          $ref: "#/components/schemas/SoftCapNotice"
          description: |
            Optional advisory message attached to write responses. Today only
            the soft-cap crossing — the (soft_cap_monitors, max_monitors]
            window, 51..100 for the free plan's default 50/100 — produces a
            notice. Omitted entirely when no notice applies.
        last_check_skipped:
          type: string
          description: |
            Populated only on `POST /monitors` when the create-time initial
            check did not produce a usable result — either short-circuited
            before any probe ran, or the probe started but did not finish
            within the create-time budget, leaving the first check pending.
            The state row's `last_check_at` remains `null` in either case;
            clients distinguish "no data yet" from "skipped on purpose" via
            this field.

            Vocabulary:
            * `domain_rate_limited` — the per-domain dispatch cap
              (`DomainLimiter`) consumed the slot; the next scheduled tick
              will retry once the bucket refills.
            * `initial_check_timeout` — the create-time probe did not
              return within the server's bounded wait; the monitor is
              registered normally and the next scheduled tick resolves it.
            * `robots_txt_unavailable` — the site's robots.txt answered
              with a 5xx (or the probe could not fetch it) and no copy is
              cached, so the check was not sent and the status stays
              `unknown` (issue #621); the next scheduled tick retries.
        recipient_ids:
          type: array
          items:
            type: integer
            format: int64
          description: |
            Attached recipient ids (issue #212). Always present, `[]` for
            none. On `POST /monitors`, reflects any account default
            recipients attached inside the create transaction; a monitor
            whose create-time check finds it down alerts them right away
            (see `Recipient.default`).
        regions_degraded:
          type: boolean
          description: |
            True while the monitor's region selection is short of
            healthy probes (fewer than 3 for 3 minutes, issue #589) and
            its checks borrow probes from regions outside the
            selection; false again once the selection has had 3 or more
            healthy probes for 3 minutes. Computed at response time,
            never stored. Always present; `false` for a monitor with
            `regions` null.
        effective_interval_sec:
          type: integer
          readOnly: true
          description: |
            The interval, in seconds, scheduled checks actually run at
            (issue #621): `interval_sec`, or the site's robots.txt
            `Crawl-delay` for Monitive when that is longer (capped at
            86400). Computed at response time from the in-memory
            robots.txt cache, never stored. Always present; equal to
            `interval_sec` when no Crawl-delay applies. Test checks,
            cross-region confirmation checks and the create-time check
            are never paced by it.
        paused_at:
          type: ["string", "null"]
          format: date-time
          description: |
            Present only on `GET /monitors/{monitorID}` (issue #457) — this
            key is absent entirely from `POST /monitors` and
            `PUT /monitors/{monitorID}` responses, which share this same
            schema but never populate this field. On `GET`, always present
            but non-null only when the monitor is currently disabled AND
            its pause instant is known: it is `null` whenever the monitor
            is enabled, and *also* `null` for a monitor created already
            disabled, or for a pause whose audit-log event has aged out of
            the 90-day `account_events` retention window by the time the
            backfill migration ran. A client cannot infer "this monitor is
            enabled" from `paused_at: null` alone — check the monitor's own
            enabled state for that.
    StatusPageSettings:
      type: object
      description: |
        The free status-page switch state for one monitor (issues #368 and
        #566). Authenticated viewers can read this object; only owners can
        change it. `url` and `embed` are `null` when the page is off. When it
        is on, the server builds every embed value; clients must not construct
        the badge URL or escape snippets.
      required: [enabled, url, embed]
      properties:
        enabled:
          type: boolean
        url:
          type: [string, "null"]
          format: uri
          example: "https://status.monitive.com/sp_0123456789abcdef0123456789abcdef"
        embed:
          oneOf:
            - $ref: "#/components/schemas/StatusPageEmbed"
            - type: "null"
    StatusPageGroup:
      type: object
      additionalProperties: false
      description: |
        A group status page (issue #642). `url` is present only while the
        page is published. `brand_color` is the public page's link color
        (issue #649) and comes back exactly as stored; an imported Classic
        value need not be `#RRGGBB`.
      required: [id, title, about, published, show_response_times, brand_color, logo, components, created_at, updated_at]
      properties:
        id:
          type: integer
          format: int64
        title:
          type: string
        about:
          type: [string, "null"]
        published:
          type: boolean
        url:
          type: string
          format: uri
          description: The public page URL, present only while published.
          example: "https://status.monitive.com/sp_0123456789abcdef0123456789abcdef"
        show_response_times:
          type: boolean
        brand_color:
          type: [string, "null"]
        logo:
          oneOf:
            - $ref: "#/components/schemas/StatusPageGroupLogo"
            - type: "null"
        components:
          type: array
          description: The page's monitors, in display order.
          items:
            $ref: "#/components/schemas/StatusPageGroupComponent"
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    StatusPageGroupList:
      type: object
      additionalProperties: false
      required: [status_pages]
      properties:
        status_pages:
          type: array
          items:
            $ref: "#/components/schemas/StatusPageGroup"
    StatusPageGroupCreate:
      type: object
      additionalProperties: false
      required: [title]
      properties:
        title:
          type: string
          minLength: 1
          maxLength: 120
        about:
          type: [string, "null"]
          maxLength: 280
        published:
          type: boolean
          description: Defaults to `false` when omitted.
        show_response_times:
          type: boolean
          description: "`true` needs a paid plan; defaults to `false`."
        brand_color:
          type: [string, "null"]
          pattern: "^#[0-9A-Fa-f]{6}$"
          description: "`#RRGGBB`, the public page's link color, component names included, used in each color scheme where it reaches 4.5:1; a non-null value needs Pro or Business."
    StatusPageGroupUpdate:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        title:
          type: string
          minLength: 1
          maxLength: 120
        about:
          type: [string, "null"]
          maxLength: 280
        published:
          type: boolean
        show_response_times:
          type: boolean
        brand_color:
          type: [string, "null"]
          pattern: "^#[0-9A-Fa-f]{6}$"
    StatusPageGroupComponent:
      type: object
      additionalProperties: false
      required: [monitor_id]
      properties:
        monitor_id:
          type: integer
          format: int64
          minimum: 1
        display_name:
          type: [string, "null"]
          maxLength: 120
          description: Shown instead of the monitor's name; `null` uses the monitor's name.
        group:
          type: [string, "null"]
          maxLength: 60
          description: The component group; a non-null value needs a paid plan.
    StatusPageGroupComponentsInput:
      type: object
      additionalProperties: false
      required: [components]
      properties:
        components:
          type: array
          maxItems: 50
          items:
            $ref: "#/components/schemas/StatusPageGroupComponent"
    StatusPageGroupLogoInput:
      type: object
      additionalProperties: false
      required: [data]
      properties:
        data:
          type: string
          format: byte
          description: Standard base64 of a PNG, JPEG or WebP image of 1 to 32,768 bytes.
    StatusPageGroupLogo:
      type: object
      additionalProperties: false
      required: [content_type, bytes]
      properties:
        content_type:
          type: string
          enum: [image/png, image/jpeg, image/webp]
        bytes:
          type: integer
    StatusPageLimitError:
      type: object
      additionalProperties: false
      required: [error, limit, plan]
      properties:
        error:
          type: string
          example: status page limit reached
        limit:
          type: integer
          example: 1
        plan:
          type: string
          example: free
    StatusPageEmbed:
      type: object
      description: |
        Server-built values for the app's Embed badge dialog (issue #566).
        Snippets link the badge image to the public status page and use the
        same escaping rules as `statuspage.EmbedSnippets`.
      required: [badge_url, markdown, html, bbcode]
      properties:
        badge_url:
          type: string
          format: uri
          example: "https://status.monitive.com/sp_0123456789abcdef0123456789abcdef/badge.svg"
        markdown:
          type: string
          example: "[![Uptime status](<https://status.monitive.com/sp_0123456789abcdef0123456789abcdef/badge.svg>)](<https://status.monitive.com/sp_0123456789abcdef0123456789abcdef>)"
        html:
          type: string
          example: "<a href=\"https://status.monitive.com/sp_0123456789abcdef0123456789abcdef\"><img src=\"https://status.monitive.com/sp_0123456789abcdef0123456789abcdef/badge.svg\" alt=\"Uptime status\"></a>"
        bbcode:
          type: string
          example: "[url=\"https://status.monitive.com/sp_0123456789abcdef0123456789abcdef\"][img]https://status.monitive.com/sp_0123456789abcdef0123456789abcdef/badge.svg[/img][/url]"
    StatusPageDay:
      type: object
      description: One day of the public status page's 30-day grid.
      required: [date, uptime_pct, not_monitored_yet]
      properties:
        date:
          type: string
          format: date
        uptime_pct:
          type: [number, "null"]
          format: float
        not_monitored_yet:
          type: boolean
          description: True for a day before the monitor existed — rendered grey, never a fabricated 0% or 100%.
    StatusPageIncident:
      type: object
      description: One entry of the public downtime history, newest-first, capped at 50.
      required: [id, started_at, clipped_start, ongoing_over_30_days]
      properties:
        id:
          type: integer
          format: int64
        started_at:
          type: string
          format: date-time
        clipped_start:
          type: boolean
          description: True when the incident actually began before the 30-day window.
        resolved_at:
          type: string
          format: date-time
        ongoing_over_30_days:
          type: boolean
          description: True for a still-open incident older than 30 days — rendered as "Down for more than 30 days".
    StatusPageJSON:
      type: object
      description: |
        The public `GET /{token}/status.json` response (issue #368). Served
        from the status host (`STATUS_PAGE_URL`), unauthenticated — the
        token is the only credential.
      required: [monitor_name, monitor_host, status, headline, days, uptime_pct_30d, avg_response_ms, history, claimed, generated_at]
      properties:
        monitor_name:
          type: string
        monitor_host:
          type: string
        status:
          type: string
          enum: [up, down, flapping, blocked, paused, unknown]
        headline:
          type: string
          example: "example.com is up"
        last_checked_at:
          type: string
          format: date-time
        down_since:
          type: string
          format: date-time
        region_clause:
          type: string
          example: "confirmed from 2 of 3 regions"
          description: Present only when status is down and the open incident carries a region tally.
        days:
          type: array
          minItems: 30
          maxItems: 30
          items:
            $ref: "#/components/schemas/StatusPageDay"
        uptime_pct_30d:
          type: [number, "null"]
          format: float
          description: Plain average of the days whose uptime_pct is not null.
        avg_response_ms:
          type: [number, "null"]
          format: float
        history:
          type: array
          maxItems: 50
          items:
            $ref: "#/components/schemas/StatusPageIncident"
        claimed:
          type: boolean
        generated_at:
          type: string
          format: date-time
    UptimeDay:
      type: object
      description: |
        One day's uptime entry returned by `GET /api/v1/monitors/{monitorID}/uptime`.

        `pct` is nullable: `null` means the day had no scheduled checks
        (render grey). A numeric `pct` is the share of the day NOT
        covered by `down`-incident overlap, clamped to `[0, 100]`, then
        floored to `0` when the day's counters show zero successful
        checks AND the monitor is corroborated down by either signal
        below (both netted against overlapping flapping-incident
        windows, so a flapping monitor's masked-downtime treatment is
        never overridden): an unresolved down incident whose net
        overlap with the day is greater than zero (any day), or the
        monitor's current resolved status being `down`, only when
        enabled, not flapping, and the current status began before the
        day ended — i.e. the day falls inside the monitor's current
        continuous down-period, not merely "today". Never floored when
        the monitor's resolved status is `up` or `blocked`.

        `latency` is nullable and independent of `pct`'s null condition:
        `pct` null keys off `scheduled = 0`, while `latency` null keys
        off there being zero successful checks to sample from that day
        (including days predating this feature). A day can carry a
        non-null `pct` and a null `latency` at the same time.
      required: [day, scheduled, pct, latency]
      properties:
        day:
          type: string
          format: date
          description: UTC calendar day (YYYY-MM-DD).
          example: "2026-05-02"
        scheduled:
          type: integer
          description: |
            Number of checks scheduled for this monitor on this day,
            sourced from `monitor_uptime_day.scheduled`. `0` means the
            dispatcher never tried to check this monitor (suspended,
            disabled, kill switch, dispatcher outage, freshly created).
          example: 1440
        pct:
          type: [number, "null"]
          format: float
          minimum: 0
          maximum: 100
          description: |
            Uptime percentage for the day, derived from down-incident
            overlap. `null` when `scheduled = 0`. Floored to `0` when
            the day had zero successful checks and the monitor is
            corroborated down by either signal, both netted against
            overlapping flapping-incident windows so a flapping
            monitor's masked-downtime treatment is never overridden:
            an unresolved down incident whose net (post flap-mask)
            overlap with the day is greater than zero (any day), or the
            monitor's current resolved status being `down` — only when
            the monitor is enabled, not currently flapping, AND the
            current status began before the day ended, i.e. the day
            falls inside the monitor's current continuous down-period.
            This reconciliation catches days where a runtime incident
            write was dropped and no `incidents` row covers the outage
            — including every day of a multi-week outage, not just the
            most recent one. A day that predates the current down-period
            (status flipped down after that day already ended) is never
            floored by current status alone. Never applied when the
            monitor's resolved status is `up` or `blocked`. Always present in the
            JSON object — never omitted.
          example: 99.86
        latency:
          type: [object, "null"]
          description: |
            The day's latency candle: open/high/low/close/avg total
            response time in whole milliseconds (wopher `total_ms`: the
            full request round-trip, DNS through last byte of
            download), built only from
            successful checks against the monitor's sticky primary
            region. All five values are rounded to the nearest whole
            millisecond server-side (half away from zero).

            `null` when the day has no successful samples to build a
            candle from — this includes days predating the feature.
            This is a distinct null condition from `pct`: a fully
            scheduled, all-down day has a non-null `pct` but a null
            `latency`. Always present in the JSON object — never
            omitted.
          required: [open, high, low, close, avg]
          properties:
            open:
              type: number
              format: float
              description: First successful check's total response time of the day, in whole ms.
              example: 212
            high:
              type: number
              format: float
              description: Highest total response time among the day's successful checks, in whole ms.
              example: 480
            low:
              type: number
              format: float
              description: Lowest total response time among the day's successful checks, in whole ms.
              example: 190
            close:
              type: number
              format: float
              description: Most recent successful check's total response time of the day, in whole ms.
              example: 220
            avg:
              type: number
              format: float
              description: |
                Arithmetic mean of the day's successful-check total
                response times (`latency_sum_ms / latency_count`,
                computed server-side; the underlying sum/count are not
                exposed on the wire), in whole ms.
              example: 231
    SoftCapNotice:
      type: object
      description: |
        Advisory attached to `POST /api/v1/monitors` when the post-insert
        per-account monitor count is strictly greater than the account's
        resolved soft cap and at or below its resolved hard cap (issue
        #507 — 51..100 for the free plan's default 50/100, but a
        `complimentary` account's admin-set overrides can set different
        values; see `soft_cap`/`hard_cap` below, which always report the
        account's actual resolved thresholds). Clients should branch on
        `code` rather than parsing `message`, which names only `soft_cap`
        and the remaining room, never `hard_cap` (issue #593).
      required: [code, message, monitors_current, soft_cap, hard_cap]
      properties:
        code:
          type: string
          enum: [soft_cap_reached]
        message:
          type: string
          description: Human-readable advisory text. Wording is set by SPEC and may evolve.
        monitors_current:
          type: integer
          description: Per-account monitor count after the create.
        soft_cap:
          type: integer
          description: This account's resolved soft cap threshold; crossing it triggers the notice.
        hard_cap:
          type: integer
          description: This account's resolved hard cap; reached → 409 on subsequent creates.
    IncidentListPageResponse:
      type: object
      description: |
        `GET /incidents` cursor list (issue #418). Every key is always
        present; `days` and `incidents` are arrays, `next_cursor` is null
        on the last page.
      required: [summary, days, incidents, next_cursor, as_of]
      properties:
        summary:
          $ref: "#/components/schemas/IncidentListSummary"
        days:
          type: array
          items:
            $ref: "#/components/schemas/IncidentListDay"
        incidents:
          type: array
          description: >-
            Whole groups in list order: ongoing outages oldest first, then resolved outages newest first; burst members and outage segments follow their head.
          items:
            $ref: "#/components/schemas/IncidentPageItem"
        next_cursor:
          type: ["string", "null"]
          description: Opaque cursor for the next page; null on the last page.
        as_of:
          type: string
          format: date-time
          description: >-
            The page's frozen view time, identical on every page of one walk. Pass it as `as_of` to `GET /incidents/{id}` (URL-encoded) within 24 hours of receiving it when opening a listed row, so the detail floor uses this walk's exact cutoff and every listed row opens; past 24 hours, `GET /incidents/{id}` ignores it and anchors at the request time instead.
    IncidentListSummary:
      type: object
      description: >-
        Distinct outages (not segments) matching the `cause` and `monitor` filters, with a segment that is open or resolved within the last 30 days. `filter` does not change it.
      required: [total, ongoing, resolved, in_maintenance, median_resolve_s, needs_attention]
      properties:
        total:
          type: integer
          description: ongoing + resolved.
        ongoing:
          type: integer
        resolved:
          type: integer
        in_maintenance:
          type: integer
          description: Outages whose first segment opened in a maintenance window; also counted in total.
        median_resolve_s:
          type: ["integer", "null"]
          format: int64
          description: >-
            Median of resolved outages' duration (last resolution minus first start), in whole seconds; null when none is resolved.
        needs_attention:
          type: integer
          description: Ongoing outages not in maintenance.
    IncidentListDay:
      type: object
      description: >-
        One local date (in `tz`) a resolved outage's HEAD (its earliest segment) started on. Its counts and durations cover only resolved outages whose head started that day — never a later segment's own day, since every row of an outage is listed under its head's day; an ongoing outage, pinned above the day-grouped list, never has a day entry.
      required: [date, incidents, down_s, maintenance_s, note]
      properties:
        date:
          type: string
          format: date
          example: "2026-11-01"
        incidents:
          type: integer
          description: Distinct resolved outages whose head started this day.
        down_s:
          type: integer
          format: int64
          description: >-
            Wall-clock seconds covered by at least one non-maintenance segment of the resolved outages counted in `incidents`, over their full durations, not clipped to this day, so it can exceed a day (a union, not a sum: four monitors down together for 30 seconds is 30).
        maintenance_s:
          type: integer
          format: int64
          description: The same union over those outages' maintenance segments.
        note:
          type: ["string", "null"]
          description: Reserved for a server-written note; always null for now.
    IncidentPageItem:
      type: object
      description: >-
        One incident (an outage segment) in the cursor list. An outage's head segment also describes the whole outage: its `state`, `resolved_at` and `duration_s` span every segment.
      required: [id, ref, number, outage_id, monitor, state, kind, started_at, resolved_at, duration_s, cause, cause_class, flapping, maintenance, response, burst, segments]
      properties:
        id:
          type: integer
          format: int64
        ref:
          type: string
          example: k7q2mx-42
        number:
          type: integer
          format: int64
        outage_id:
          type: integer
          format: int64
          description: The outage this segment belongs to (its first segment's id).
        monitor:
          type: object
          required: [id, ref, name]
          properties:
            id:
              type: integer
              format: int64
            ref:
              type: string
            name:
              type: string
        state:
          type: string
          enum: [ongoing, resolved]
          description: >-
            On an outage's head segment, the outage's state — `ongoing` while any of its segments is unresolved, matching the section the outage is listed in. On any other segment, that segment's own state.
        kind:
          type: string
          enum: [down, flapping]
        started_at:
          type: string
          format: date-time
          description: >-
            The first failed check (issue #436): when the monitor's suspect phase began, not the moment the cross-region re-check confirmed the verdict. On the head segment, also the outage's start.
        resolved_at:
          type: ["string", "null"]
          format: date-time
          description: >-
            On the head segment, the outage's last segment resolution, null while the outage is ongoing. On any other segment, that segment's own resolution.
        duration_s:
          type: integer
          format: int64
          description: >-
            Seconds from started_at to resolved_at, or to the first page's time while ongoing. On the head segment this spans the whole outage.
        cause:
          type: ["string", "null"]
        cause_class:
          type: ["string", "null"]
          enum: [dns, tls, timeout, connection, http_4xx, http_5xx, keyword, null]
        flapping:
          type: ["object", "null"]
          description: Flapping segments only; each count is null until the segment resolves.
          required: [state_changes, checks_ok, checks_failed]
          properties:
            state_changes:
              type: ["integer", "null"]
            checks_ok:
              type: ["integer", "null"]
            checks_failed:
              type: ["integer", "null"]
        maintenance:
          type: ["object", "null"]
          description: >-
            The maintenance window the segment opened in, when recorded; null otherwise (including older rows that only carry the flag). The `{until}` form is never emitted.
          required: [from, to]
          properties:
            from:
              type: string
              format: date-time
            to:
              type: string
              format: date-time
        response:
          type: object
          required: [alerts_sent, alerts_failed, acked_by, acked_after_s, silenced]
          properties:
            alerts_sent:
              type: ["integer", "null"]
              description: >-
                Per outage, on the head segment only (null elsewhere): every alert the outage sent or is still sending — delivered, failed, pending and retrying deliveries. Superseded and cancelled deliveries never go out and are not counted.
            alerts_failed:
              type: ["integer", "null"]
              description: Per outage, on the head segment only; failed alerts, included in alerts_sent.
            acked_by:
              type: ["object", "null"]
              description: >-
                Who acknowledged the outage (issue #420), on the head segment only (null elsewhere), frozen at the page's `as_of`: an ack made after the walk began reads as unacked. Null for a link ack (the clicker cannot be identified as a user). Name is the acking user's GitHub username, else the local part of their email, else (issue #495) their stored display name when they have neither — so `name` is never empty when this object is present; no email address is ever exposed. A provider name containing an at sign — a bare address, one embedded in or wrapped by display text, or anything else carrying an `@` — is never stored or shown, so this guarantee holds regardless of what a sign-in provider sends.
              required: [initials, name]
              properties:
                initials:
                  type: string
                  description: >-
                    Derived from `display_name` when set (first letter of the first and last word), else from the same GitHub-username/email-local-part handle `name` uses.
                name:
                  type: string
                display_name:
                  type: ["string", "null"]
                  description: >-
                    The acking user's stored real name (issue #495), null when they have none on file.
            acked_after_s:
              type: ["integer", "null"]
              description: >-
                Whole seconds from the outage's start (the head segment's `started_at`) to the acknowledgement (issue #420), on the head segment only, frozen at the page's `as_of`; null while unacked.
            silenced:
              type: ["string", "null"]
              enum: [maintenance, null]
              description: '"maintenance" when the segment opened in a maintenance window.'
        burst:
          type: ["object", "null"]
          description: Set on every segment of a burst's outages; null otherwise.
          required: [id, size]
          properties:
            id:
              type: integer
              format: int64
              description: The burst head's incident id.
            size:
              type: integer
              description: Number of outages in the burst.
        segments:
          type: ["integer", "null"]
          description: On an outage's head segment, its segment count when 2 or more; null otherwise.
    IncidentListItem:
      type: object
      description: |
        An incident as `GET /incidents`' legacy offset mode lists it: every
        `Incident` field, including the onset `evidence` snapshot, except
        the resolve-time `recovery_evidence` snapshot (issue #421).
      required: [outage_id, confirmed_regions, voted_regions, tally_region, borrowed_votes, acknowledged_at, acknowledged_by]
      properties:
        acknowledged_at:
          type: ["string", "null"]
          format: date-time
          description: >-
            When the outage this incident belongs to was acknowledged (issue #420): null while unacked. An ack applies to the whole outage (every incident sharing the outage_id), is set by an authenticated POST /incidents/{id}/acknowledge or the signed emailed link, and is inherited across a down-to-flapping handoff. Never emitted on the public feed or a status page.
        acknowledged_by:
          type: ["object", "null"]
          description: >-
            Who acknowledged the outage (issue #420), as {initials, name, display_name} with no user id and no email address. Null when unacked, when the outage was acknowledged through the signed emailed link (the clicker cannot be identified as a user), or when the acking user has neither a GitHub/email handle nor a stored display name. Name is the acking user's GitHub username, falling back to the local part of their email, falling back further (issue #495) to their display name when they have neither — so `name` is never empty when this object is present; no email address is ever exposed. A provider name containing an at sign — a bare address, one embedded in or wrapped by display text, or anything else carrying an `@` — is never stored or shown, so this guarantee holds regardless of what a sign-in provider sends.
          required: [initials, name]
          properties:
            initials:
              type: string
              description: >-
                Derived from `display_name` when set (first letter of the first and last word, uppercased), else uppercase first characters of the name's first two parts.
            name:
              type: string
            display_name:
              type: ["string", "null"]
              description: >-
                The acking user's stored real name (issue #495), null when they have none on file.
        evidence:
          type: array
          description: Snapshot of the evidence ring buffer at the time of the state transition.
          items:
            $ref: "#/components/schemas/CheckResult"
        id:
          type: integer
          format: int64
        number:
          type: integer
          format: int64
          description: >-
            This incident's per-account sequence number (issue #412), assigned once at creation and never reused.
        ref:
          type: string
          description: >-
            Stable "<account handle>-<number>" reference, e.g. "k7q2mx-3" — accepted anywhere `{incidentID}` appears in a path.
        monitor_ref:
          type: string
          description: The owning monitor's own ref (issue #412), e.g. "k7q2mx-14".
        monitor_id:
          type: integer
          format: int64
        account_id:
          type: integer
          format: int64
        type:
          type: string
          enum: [down, flapping]
        started_at:
          type: string
          format: date-time
          description: >-
            The first failed check (issue #436): when the monitor's suspect phase began, not the moment the cross-region re-check confirmed the verdict. The confirmation moment is `confirmed_at` on the detail response only.
        resolved_at:
          type: ["string", "null"]
          format: date-time
          description: Null if the incident is still ongoing.
        created_at:
          type: string
          format: date-time
        maintenance:
          type: boolean
          description: |
            True when this incident opened while the monitor's maintenance
            window was active (issue #361) — or, for a down-to-flapping or
            flapping-to-down handoff, inherited from the incident it
            replaced. A monitor-wide down/flapping alert is suppressed for
            every recipient while this is true, and the recovery ("up")
            alert is suppressed too once every incident the recovery
            resolved carries this flag.
        state_changes:
          type: integer
          minimum: 0
          description: |
            Number of state changes during the flapping episode (issue
            #421), counting the change that entered flapping and the one
            that left it. Present only on a resolved flapping incident.
        checks_ok:
          type: integer
          minimum: 0
          description: |
            Number of successful checks while the monitor was flapping
            (issue #421). Present only on a resolved flapping incident; may
            be 0.
        checks_failed:
          type: integer
          minimum: 0
          description: |
            Number of failed checks while the monitor was flapping (issue
            #421). Present only on a resolved flapping incident; may be 0.
        maintenance_window:
          type: object
          description: |
            The maintenance window occurrence this incident opened in, or
            inherited across a down-to-flapping or flapping-to-down handoff
            (issue #421). Present only when the incident carries one; a
            later edit of the monitor's window does not change it. For a
            daily window, `from`/`to` are that day's concrete occurrence,
            including any DST shift; for a one-off window they are its
            start and end.
          properties:
            from:
              type: string
              format: date-time
              description: Start of the occurrence, in UTC.
            to:
              type: string
              format: date-time
              description: End of the occurrence, in UTC.
            until:
              type: string
              format: date-time
              description: Reserved for an open-ended maintenance window type. Currently never emitted.
        outage_id:
          type: integer
          format: int64
          description: |
            The outage this incident belongs to (issues #363, #423): this
            incident's own id for a fresh outage, or the first segment's id
            when inherited across a down/flapping handoff. Every segment of
            one outage shares it; a pre-#363 row reports its own id. Always
            present.
        confirmed_regions:
          type: ["integer", "null"]
          minimum: 1
          maximum: 3
          description: |
            How many voters confirmed a verdict-confirmed `down` (issue
            #368). Read `tally_region` and `borrowed_votes` first: when
            `tally_region` is non-null this is a count of probes inside that
            one region (a one-region selection, issue #572); when
            `borrowed_votes` is non-null it is a count of probes (issue
            #589), even when `tally_region` is null; otherwise it is a count
            of regions. Always present; null for every other incident.
        voted_regions:
          type: ["integer", "null"]
          minimum: 1
          maximum: 3
          description: |
            How many voters took part in that verdict (issue #368). Read
            `tally_region` and `borrowed_votes` first: when `tally_region` is
            non-null this is a count of probes inside that one region (issue
            #572); when `borrowed_votes` is non-null it is a count of probes
            (issue #589), even when `tally_region` is null; otherwise it is a
            count of regions. Always present; null for every other
            incident.
        tally_region:
          type: ["string", "null"]
          enum: [EU, US-E, US-W, ASIA, OCE, SA, null]
          description: |
            Non-null only for a probe tally (issue #572): the monitor checks
            from a single selected region, so `confirmed_regions` and
            `voted_regions` count probes inside this region (for example
            "confirmed by 3 of 3 probes in EU") rather than regions. Always
            present; null for every cross-region tally and every incident
            with no tally.
        borrowed_votes:
          type: ["integer", "null"]
          minimum: 1
          maximum: 3
          description: |
            Non-null only when some of a region-restricted monitor's votes
            (the primary check included) ran outside its region selection
            because the selection was short of healthy probes (issue #589):
            the number of those votes. When it is non-null,
            `confirmed_regions` and `voted_regions` are probe counts, even
            when `tally_region` is null (a multi-region selection), for
            example "confirmed by 2 of 3 probes, 1 outside EU". Always
            present; null for every other incident.
        cause:
          type: ["string", "null"]
          description: |
            The first failed assertion of the check that opened the incident
            (issue #419), verbatim with everything after its first word
            lower-cased — e.g. "HTTP 521, expected 200" or "dial tcp: i/o
            timeout". Set once when the incident opens and never changed.
            Null when unknown.
        cause_class:
          type: ["string", "null"]
          enum: [dns, tls, timeout, connection, http_4xx, http_5xx, keyword, null]
          description: |
            The cause's class (issue #419). Null for an unrecognized error,
            a status mismatch outside 4xx/5xx, or a check that did not fail.
    Incident:
      description: |
        A single incident with its onset evidence snapshot and, once
        recovery is confirmed, its `recovery_evidence` snapshot, as
        `GET /incidents/{incidentID}` returns it.
      allOf:
        - $ref: "#/components/schemas/IncidentListItem"
        - type: object
          properties:
            recovery_evidence:
              type: array
              description: |
                The evidence buffer snapshot taken when recovery was confirmed
                (at most 20 checks, oldest first; issue #421). For an ordinary
                probe recovery, the last entry is the recovering check. For a
                recovery confirmed by a cross-region suspect verdict, the buffer
                is stored as is and does not contain the confirming check. For
                a flapping incident that ends by decay, there is no separate
                recovering check: the last entry is the most recent buffered
                check. Omitted when no recovery was recorded, including an
                ongoing incident and an outage that continued as a flapping or
                down incident.
              items:
                $ref: "#/components/schemas/CheckResult"
    IncidentDetail:
      description: |
        A single incident as `GET /incidents/{incidentID}` returns it:
        the list shape plus the fields only that read exposes.
      allOf:
        - $ref: "#/components/schemas/Incident"
        - type: object
          required: [confirmed_at]
          properties:
            confirmed_at:
              type: ["string", "null"]
              format: date-time
              description: >-
                The moment the failure was confirmed by the cross-region re-check (issue #436). Null only on rows written by an older binary during rollout, whose started_at carries the confirmation time.
    APIKey:
      type: object
      description: API key metadata (plaintext and hash are never exposed).
      properties:
        id:
          type: integer
          format: int64
        account_id:
          type: integer
          format: int64
        key_prefix:
          type: string
          description: "Prefix for identification: `mk_live_` + first 8 lowercase hex chars."
          example: mk_live_a1b2c3d4
        label:
          type: ["string", "null"]
          description: |
            User-assigned label. New labels (created on or after the #115
            tightening) are trimmed to 3..100 characters. Legacy labels
            persisted before that rule may fall outside this range or carry
            untrimmed surrounding whitespace and are returned verbatim.
          example: production
        revoked_at:
          type: ["string", "null"]
          format: date-time
          description: If set, the key will stop working after this timestamp.
        last_used_at:
          type: ["string", "null"]
          format: date-time
        last_used_ip:
          type: ["string", "null"]
          description: IP address of the last request authenticated with this key.
        created_at:
          type: string
          format: date-time
    AccountUsage:
      type: object
      description: |
        Nine daily usage counters keyed on (account_id, date), written by
        usage.Worker (internal/usage). The source-derived totals behind
        all nine columns stop changing once every writer attributed to
        that day has committed, but the stored row only reflects those
        totals once a later aggregation pass that still covers the day
        re-writes it — a writer that commits after its day closed is
        repaired only if a RunOnce pass covering that day still runs
        (bounded to a 30-day re-walk; D+30 is the last UTC *date*
        eligible to re-aggregate day D, not a single pass — any number of
        runs on D+30 can still repair it), AND that pass's own three
        source reads all happen after the last attributed writer commits.
        Concurrent passes in the same process now serialize on a
        package-level lock (a later-started pass only begins reading
        once every UPSERT from an earlier pass has committed — see
        internal/usage/usage.go), so a later-started pass's UPSERT no
        longer races an older, still-in-flight one; there is no
        equivalent lock across separate dispatcher processes, though
        production never runs two against the same database. RunOnce
        also rechecks window membership against the live clock before
        each day and each account-day it reads, so a pass running late
        into the next UTC date stops at the first day — or, within a
        day, the first account — the recheck finds outside the window,
        rather than continuing to read it. At D+31, RunOnce's window
        permanently stops reaching day D for any *new* pass, and the row
        is stuck on whatever was last written — regardless of whether a
        pass over D "completed" before then. Completion alone does not
        make a pass correct: the row only reflects reality if that
        pass's source reads all happened after the last attributed
        writer for day D committed, not merely that the pass ran and
        its UPSERT succeeded. A completed pass whose reads raced a late
        writer, or that upserted a mixed snapshot because its three
        reads are independent, freezes the row just as permanently at
        D+31 as no pass running at all. The residual the window recheck
        narrows but does not close: a single account's three source
        reads plus its UPSERT are
        still independent statements, not one atomic snapshot, so they
        can still straddle the recheck and race the independent
        retention sweep below. From the point D falls out of the window,
        day D's three source tables become eligible for their own
        independent retention sweep, each on its own window:
        account_activity_day after 30 days (the narrowest of the three,
        and what sets this worker's 30-day backfill window),
        monitor_uptime_day after 95 days (issue #367 widened this from
        65), and account_events after 90 days — every sweep is
        asynchronous and retryable, so none is guaranteed to run at that
        exact moment, and dispatcher downtime or repeated deletion errors
        (logged and swallowed) can leave rows physically present past
        their own mark.

        `incidents` and `webhooks_sent` additionally carry an exactness
        boundary around migration 032's deploy date — see those fields.
      properties:
        account_id:
          type: integer
          format: int64
        date:
          type: string
          format: date
        incidents:
          type: integer
          format: int64
          description: Count of incidents whose started_at fell on this UTC day, from account_activity_day. Exact after migration 032's deploy date; earlier days may hold a backfilled/legacy-merged value instead of an exact recount.
        webhooks_sent:
          type: integer
          format: int64
          description: Count of delivered webhooks whose attempt-start time (not completion) fell on this UTC day, from account_activity_day. Exact after migration 032's deploy date; earlier days may hold a backfilled/legacy-merged value instead of an exact recount.
        monitors_avg:
          type: number
          format: float
        monitors_created:
          type: integer
          format: int64
        monitors_deleted:
          type: integer
          format: int64
        webhooks_created:
          type: integer
          format: int64
        webhooks_deleted:
          type: integer
          format: int64
        checks_total:
          type: integer
          format: int64
          description: Per-day total check count, summed from monitor_uptime_day.
        checks_succeeded:
          type: integer
          format: int64
    AccountUsageResponse:
      type: object
      properties:
        monitors_current:
          type: integer
        days:
          type: array
          items:
            $ref: "#/components/schemas/AccountUsage"
    ReportPreferences:
      type: object
      description: |
        A signed-in user's weekly/monthly uptime-report opt-ins on one
        account (issue #357) — stored per `account_members` row, not per
        user, so leaving one team's reports never silences another.
        `deliverable` is `true` exactly when `email` is non-null; a
        client can use it to prompt the user to verify an email address
        before expecting any report to actually arrive.
      properties:
        account_id:
          type: integer
          format: int64
        weekly:
          type: boolean
        monthly:
          type: boolean
        email:
          type: ["string", "null"]
        deliverable:
          type: boolean
    AccountEvent:
      type: object
      description: |
        One row of the per-account audit log. Mirrors the `account_events`
        table verbatim (see SPEC §Account Events). `payload` is the
        recorder's bytes round-tripped without re-shaping at the read path
        — the per-event-type contract is documented in the spec and in
        `internal/audit/DECISIONS.md`.
      properties:
        id:
          type: integer
          format: int64
        account_id:
          type: integer
          format: int64
        event_type:
          type: string
          enum:
            - monitor.created
            - monitor.updated
            - monitor.deleted
            - webhook.created
            - webhook.updated
            - webhook.deleted
            - recipient.created
            - recipient.updated
            - recipient.deleted
            - recipient.confirmed
            - recipient.unsubscribed
            - monitor.recipients_set
            - apikey.created
            - apikey.rotated
            - apikey.deleted
            - account.suspended
            - account.unsuspended
            - account.notification_email_changed
            - account.email_cap_hit
            - account.member_role_changed
            - account.member_removed
            - account.invite_created
            - account.invite_revoked
            - account.invite_accepted
            - monitor.status_page_enabled
            - monitor.status_page_disabled
            - status_page.created
            - status_page.updated
            - status_page.components_set
            - status_page.logo_set
            - status_page.logo_removed
            - status_page.deleted
            - account.identity_linked
            - account.github_email_skipped
            - account.plan_changed
            - account.attribution_set
            - account.billing_preview_changed
            - account.plan_shrunk
        ref_type:
          type: ["string", "null"]
          enum: [monitor, webhook, recipient, apikey, status_page, null]
          description: |
            Identifies the kind of entity `ref_id` refers to. Null for
            account-level events that have no associated entity.
        ref_id:
          type: ["integer", "null"]
          format: int64
          description: |
            ID of the entity the event refers to. Null for account-level
            events.
        payload:
          type: object
          additionalProperties: true
          description: |
            Event-specific context. Shape varies per `event_type`; see the
            table in SPEC §Account Events for the contract.

            `account.identity_linked`'s payload is `{provider, user_id}`
            for a Google link, an explicit GitHub link, or a first
            GitHub sign-in merged into an existing user (issue #390) — in
            all three cases `provider` is `"google"` or `"github"`
            unambiguously. For an adopted email address (issue #390,
            GitHub-verified-email adoption) the payload is
            `{provider: "email", source: "github", user_id}` — `source`
            is optional, present only on a GitHub-sourced write, and
            useful only within the 90-day `account_events` retention
            window, not as durable provenance. An explicit
            `POST /api/v1/me/identities/email/verify` link writes the
            two-field form (`{provider: "email", user_id}`, no `source`),
            same as every historical row written before issue #390.

            `account.plan_changed`'s payload (issue #507) is
            `{from, to, max_monitors, soft_cap_monitors, host_fan_threshold}`
            — `from`/`to` are plan strings (`PlanID` values; an admin
            change only ever writes `"free"`/`"complimentary"`);
            `max_monitors`/`soft_cap_monitors`/`host_fan_threshold` are the
            request's override values, null for `"free"` or for an omitted
            override on `"complimentary"` (`host_fan_threshold` added by
            issue #512; null means "no host-fan override"). Rows written
            before issue #512 have no `host_fan_threshold` key. The
            Monitive Classic import writes this shape too, once per
            imported account (`from` `"free"`, the override keys null).
            The billing worker (issue #598) writes a second shape,
            `{from, to, source: "paddle", subscription_id}`, attributed to
            `system` and only when the plan actually changes: `from`/`to`
            may be any plan, the paid `"basic"`, `"pro"` and `"business"`
            included, `subscription_id` is the Paddle `sub_…` ID, and the
            override keys are absent.

            `account.attribution_set`'s payload (issue #510) is
            `{fields: [...]}` — the names of the stored attribution keys,
            in the fixed order `referrer, utm_source, utm_medium,
            utm_campaign, utm_content, utm_term, landing_page, first_visit,
            visit_count`, never their values.

            `account.billing_preview_changed`'s payload (issue #592) is
            `{from, to}` — the account's stored `billing_preview` flag
            before and after the call, both booleans. Written by the
            admin-only billing-preview endpoint on every call, a no-op
            re-set (`from == to`) included.

            `account.plan_shrunk`'s payload (issue #595) is
            `{plan, monitors_paused, grace_reset}` — the account's plan, the
            number of monitors the plan-shrink step paused (each with its
            own `monitor.updated` event), and the number of alert
            attachments whose grace period was reset to 120 seconds.
            Written only when the shrink changed something, attributed to
            `system`, with null `ref_type`/`ref_id`.
        created_at:
          type: string
          format: date-time
        actor:
          type: string
          description: |
            Who or what caused this event (issue #323, team accounts B1):
            `"user:<id>"`, `"api-key:<id>@account:<accountID>"`,
            `"system"` for dispatcher-internal writes (e.g. auto-suspension
            from the port-scan heuristic or DNS-rebinding detection), or
            `"legacy"` for a row written by a pre-#323 binary with no actor
            columns at all. See `internal/audit.RenderActor`.
    AccountEventList:
      type: object
      properties:
        events:
          type: array
          items:
            $ref: "#/components/schemas/AccountEvent"
        next_cursor:
          type: ["string", "null"]
          description: |
            Opaque base64url cursor for the next page, or null if this was
            the last page. Pass back verbatim as `?cursor=` on the next
            request — the value is URL-safe; clients must NOT
            percent-encode it.
    Announcement:
      type: object
      properties:
        id:
          type: integer
        title:
          type: string
        body:
          type: string
        published_at:
          type: string
          format: date-time
        expires_at:
          type: ["string", "null"]
          format: date-time
        updated_at:
          type: string
          format: date-time
          description: |
            Last time this row was mutated. For rows created after
            migration 025 (2026-08-01), this is exact creation time if
            never edited. For rows that already existed when that
            migration ran, no creation timestamp had ever been recorded,
            so the backfilled starting value is
            `LEAST(published_at, migration time)` instead — not the row's
            actual original creation time. Bumped by any PUT that changes
            at least one field; an empty-body no-op PUT does not bump it.
            Strictly monotonic per row — never ties or regresses across
            concurrent writes.
    AnnouncementListResponse:
      type: object
      properties:
        announcements:
          type: array
          items:
            $ref: "#/components/schemas/Announcement"
    Webhook:
      type: object
      description: |
        Configured notification endpoint. The signed JSON body for an HTTP
        attempt contains `event`, `monitor_ref`, `account_handle` (issue
        #412 — replaced the old numeric `monitor_id`/`account_id`),
        `occurred_at`, `delivery_id`, `attempt`, plus
        `reason`/`monitor_name`/`monitor_url` when non-empty. Since issue
        #165, the body also
        carries `collapsed_transitions` (integer) when a delivery superseded
        one or more earlier transitions for the same monitor+webhook pair —
        e.g. a down→up→down→up flap against a slow-to-recover subscriber
        can collapse to a survivor carrying `collapsed_transitions: 3`. The
        field is omitted entirely (not sent as 0) when nothing was
        collapsed, so existing subscribers see a byte-identical body to
        before this field existed.

        `event` is `monitor.down`, `monitor.up`, `monitor.flapping`,
        `monitor.test`, or (issue #558) `monitor.blocked`: bot protection on
        the site is challenging every check, or (issue #621) the site's
        robots.txt does not allow Monitive to check it (or has not loaded
        for 24 hours), so it is not reported as down. A robots.txt block's
        `monitor.blocked` body carries `reason: robots_txt`; a
        bot-protection challenge's carries no `reason`.
        A `monitor.blocked` body also carries `help_url`
        (`https://monitive.com/bot`, the allowlisting guide); every other
        body omits the key. One `monitor.blocked` delivery is enqueued per
        blocked spell for each recipient subscribed to `down`; a failed
        attempt is retried on the normal schedule, so dedupe on
        `delivery_id`.
      properties:
        id:
          type: integer
          format: int64
        monitor_id:
          type: integer
          format: int64
        url:
          type: string
          format: uri
        secret:
          type: string
          description: HMAC-SHA256 signing secret. Prefix `whs_live_`.
        created_at:
          type: string
          format: date-time
    Recipient:
      type: object
      description: |
        Account-level, named delivery target (issue #212) assignable to any
        number of monitors via `PUT /api/v1/monitors/{monitorID}/recipients`.
        `secret` is included ONLY on the `POST /api/v1/recipients` response
        for `type=webhook` — never on `GET`/`PATCH`, and never for
        `type=email`, `type=slack`, or `type=pagerduty`. The signed JSON
        delivery body for `webhook` is unchanged from the pre-#212
        `Webhook` contract; see its description. `type=email` (issue #321)
        sends outage/recovery alert mail instead of a signed POST — see
        `status` below for its confirmation lifecycle. `type=slack` (issue
        #359) posts an unsigned Block Kit message to a Slack incoming
        webhook URL; `config.url` is always masked (the real token is
        never echoed). `type=pagerduty` (issue #363) posts to the
        PagerDuty Events API v2; `config.integration_key` is always masked
        (the real key is never echoed).
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
          maxLength: 255
        type:
          type: string
          enum: [webhook, email, slack, pagerduty]
        config:
          type: object
          description: |
            Channel-specific config: `url` for `type=webhook` or
            `type=slack`, `address` for `type=email`, `integration_key`
            for `type=pagerduty`, plus an optional `channel` for
            `type=slack`. For `type=slack`, `url` is always the masked
            form `https://hooks.slack.com/services/{team}/{bot}/********`
            (or the bare `https://hooks.slack.com/services/********` for a
            stored URL that doesn't match the expected shape) — the real
            token is never returned. For `type=pagerduty`,
            `integration_key` is always the masked form `"********"` plus
            the last 4 characters (or the bare `"********"` for a stored
            key that doesn't match the expected shape) — the real key is
            never returned.
          properties:
            url:
              type: string
              format: uri
              maxLength: 2048
            address:
              type: string
              format: email
              description: Normalized (lowercased) email address.
            channel:
              type: string
              description: |
                `type=slack` only. Optional channel/user override (e.g.
                `"#ops"` or `"@alice"`); omitted when unset.
            integration_key:
              type: string
              description: |
                `type=pagerduty` only. Masked — see this object's own
                description above.
        default:
          type: boolean
          description: |
            When true, this recipient is attached automatically to every
            new monitor created on this account, at create time, in the
            same transaction as the monitor row. A monitor whose
            create-time check finds it down alerts a newly attached
            default recipient right away, under the same rules as any
            later down transition (`grace_s`, maintenance windows).
            A monitor created disabled alerts on its first check after it
            is enabled.
        status:
          type: string
          enum: [active, pending, disabled]
          description: |
            `pending`: a `type=email` recipient awaiting confirmation (no
            alerts sent yet). `disabled`: unsubscribed (via the mailed
            unsubscribe link) — alerts stopped; re-enabling requires
            deleting and recreating the recipient, which re-confirms from
            scratch. `active`: every `type=webhook`, `type=slack`, and
            `type=pagerduty` recipient, and a confirmed, non-disabled
            `type=email` recipient.
        events:
          type: array
          items:
            type: string
            enum: [down, up, flapping]
          minItems: 1
          description: Non-empty subset of event types this recipient is notified for.
        monitor_ids:
          type: array
          items:
            type: integer
            format: int64
          description: Monitors this recipient is currently attached to. `[]` for none.
        secret:
          type: string
          description: |
            HMAC-SHA256 signing secret, prefix `whs_live_`. Present ONLY on
            the `POST /api/v1/recipients` response for `type=webhook` (and
            the deprecated `GET /api/v1/monitors/{monitorID}/webhook`
            alias, for compatibility) — omitted everywhere else, and
            always omitted for `type=email`, `type=slack`, and
            `type=pagerduty` (neither a slack nor a pagerduty recipient
            has a secret at all — the incoming webhook URL or the routing
            key itself is the credential, and both live in `config`,
            masked).
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    RecipientCreate:
      type: object
      required: [name, type, config]
      properties:
        name:
          type: string
          maxLength: 255
        type:
          type: string
          enum: [webhook, email, slack, pagerduty]
        config:
          type: object
          description: |
            `{"url": "..."}` for `type=webhook`, `{"address": "..."}` for
            `type=email`, `{"url": "...", "channel": "..."}` (channel
            optional) for `type=slack`, `{"integration_key": "..."}` for
            `type=pagerduty`. A reserved key the chosen `type` does not
            allow — `address` on webhook/slack/pagerduty, `url`/`channel`
            on email or pagerduty, `channel` on webhook,
            `integration_key` on any type but pagerduty — is 400, matched
            case-insensitively and regardless of value (including `null`
            or `""`); two keys that fold to the same reserved name (e.g.
            `url` and `URL`) are also 400. For `type=slack`, `config.url`
            must match
            `https://hooks.slack.com/services/{team}/{bot}/{token}`
            exactly (no port, userinfo, query string, or fragment, no
            trailing slash). For `type=pagerduty`,
            `config.integration_key` must be exactly 32 characters of
            `[A-Za-z0-9]`.
          properties:
            url:
              type: string
              format: uri
              maxLength: 2048
            address:
              type: string
              format: email
            channel:
              type: string
              description: '`type=slack` only. Optional; e.g. "#ops" or "@alice".'
            integration_key:
              type: string
              description: |
                `type=pagerduty` only. The PagerDuty Events API v2
                routing/integration key, exactly 32 characters of
                `[A-Za-z0-9]`.
        default:
          type: boolean
          default: false
        events:
          type: array
          items:
            type: string
            enum: [down, up, flapping]
          minItems: 1
          description: Defaults to `["down","up","flapping"]` when omitted.
    RecipientPatch:
      type: object
      description: |
        Every field is optional; only fields present are changed. `type`
        must not be present at all. `name`/`default`/`events`/`config`
        each reject an explicit JSON `null`. Changing `config.address` on
        a `type=email` recipient resets it to `status:"pending"` (old
        confirm/unsubscribe links stop working, a new confirmation is
        sent) and records `recipient.updated` with
        `changes.address: {"changed": true}` — never the old or new
        address itself. For `type=slack` (issue #359), `config.url` and
        `config.channel` are each independently optional — at least one
        is required when `config` is present — and changing either
        records `changes.url: {"changed": true}` (never the URL text) and
        `changes.channel: {"old": ..., "new": ...}` respectively, and
        cancels the recipient's own still-queued deliveries. Setting
        `config.channel` to `null` or `""` clears the override. For
        `type=pagerduty` (issue #363), `config.integration_key` is
        required when `config` is present; changing it records
        `changes.integration_key: {"changed": true}` (never the key
        itself) and cancels the recipient's own still-queued deliveries —
        it does not resolve an incident the old key already opened in
        PagerDuty.
      properties:
        name:
          type: string
          maxLength: 255
        config:
          type: object
          properties:
            url:
              type: string
              format: uri
              maxLength: 2048
            address:
              type: string
              format: email
            channel:
              type: ["string", "null"]
              description: |
                `type=slack` only. `null` or `""` clears the channel
                override back to the incoming webhook's own default.
            integration_key:
              type: string
              description: |
                `type=pagerduty` only. Exactly 32 characters of
                `[A-Za-z0-9]`.
        default:
          type: boolean
        events:
          type: array
          items:
            type: string
            enum: [down, up, flapping]
          minItems: 1
    RecipientTestResult:
      type: object
      description: Response body of `POST /api/v1/recipients/{recipientID}/test`.
      properties:
        recipient_id:
          type: integer
          format: int64
        type:
          type: string
          enum: [webhook, email, slack, pagerduty]
        status:
          type: string
          enum: [delivered, accepted, failed]
          description: |
            `accepted` is PagerDuty-only: PagerDuty's Events API v2 is
            asynchronous, so a 2xx response to the test trigger and its
            immediate resolve does not prove the test incident actually
            closed — see `message`.
        response_code:
          type: integer
          description: |
            Webhook: the destination's HTTP status, 3xx included (a
            redirect is never followed, issue #614). Email: 202 on
            success, SendGrid's status on failure, or 0 for a transport
            error. Slack: Slack's HTTP status, 3xx included (a redirect
            is never followed and is reported as its own 3xx code) — only
            a transport failure omits this field (502). PagerDuty: the
            trigger's HTTP status on success or on a trigger rejection;
            the resolve's HTTP status when the trigger succeeded but the
            resolve failed; omitted for a transport error on either
            request. Omitted when no response was obtained at all (502).
        error:
          type: string
          description: |
            Present only when status is "failed" or the request 502s. For
            `type=webhook` with a 3xx response (issue #614), this is the
            fixed text `"The endpoint answered with a redirect. Use the
            final URL."` — never the `Location` or the response body; a
            webhook's other non-2xx responses carry no `error`. For
            `type=pagerduty`, this is always fixed outcome text (e.g.
            `"PagerDuty rejected the event (HTTP 400)"`) — never a
            response body, which could echo the routing key — and, for
            every failure except a cleanly-rejected trigger, is followed
            by a warning that a test incident may remain open in
            PagerDuty.
        message:
          type: string
          description: |
            Present only for `type=pagerduty` on a successful
            `status="accepted"` test send: notes that PagerDuty processes
            events asynchronously and a test incident can remain open,
            to be resolved in PagerDuty if so. Omitted for every other
            type and outcome.
    MonitorRecipients:
      type: object
      description: |
        `GET`/`PUT` responses always carry both `recipient_ids` and
        `recipients` (resolved from the same snapshot), so a client reading
        either field sees the attached set. `PUT` request bodies accept
        exactly one of `recipient_ids` (today's form) or `recipients`
        (issue #338, per-pair grace period, renamed from `down_delay_s` to
        `grace_s` by issue #504 — `down_delay_s` is still accepted as a
        deprecated alias) — specifying both `recipient_ids` and
        `recipients`, or specifying neither, is 400. Either field, when
        present, must not be JSON `null` (400) — only an explicit `[]`
        detaches every recipient. Omitting both `grace_s` and
        `down_delay_s` on a `recipients` entry keeps an already-attached
        pair's stored value, or defaults a newly-attached pair to `120`
        (the only value allowed on the free and complimentary plans; paid
        plans accept any of the 15 values); the
        `recipient_ids` form always keeps every attached pair's existing
        value. Sending both `grace_s` and `down_delay_s` on one entry is
        accepted only when they're equal (so a client can round-trip a
        `GET` response, which always carries both, straight into a `PUT`);
        differing values are 400. A well-shaped but disallowed value is
        422, naming the allowed value(s).
      properties:
        recipient_ids:
          type: array
          items:
            type: integer
            format: int64
          description: Must be positive and unique.
        recipients:
          type: array
          items:
            type: object
            required: [id]
            additionalProperties: false
            properties:
              id:
                type: integer
                format: int64
              grace_s:
                type: integer
                description: |
                  Seconds to hold a "down" alert before sending it, so a
                  blip shorter than this never reaches the recipient at
                  all — like Monitive's alert delay (issue #338, renamed
                  to "grace" by issue #504). `up`/`flapping` are always
                  immediate. Optional on write — defaults to `120`, fixed
                  at `120` on the free and complimentary plans, any of the
                  15 values on paid plans; always present on read.
              down_delay_s:
                type: integer
                deprecated: true
                description: |
                  Deprecated alias for `grace_s` (issue #504) — same
                  column, same meaning, same value on read. Scheduled for
                  removal around 2027-02-11.
              attached_at:
                type: string
                format: date-time
                description: |
                  Read-only (issue #396) — when this monitor/recipient
                  attachment was made, stamped by the Postgres server
                  clock. A kept attachment keeps its `attached_at` across
                  a `PUT` that only changes its `grace_s`. This is
                  the per-monitor boundary
                  `DELETE /api/v1/recipients/{recipientID}?replaced_by=`
                  measures a replacement recipient's delivery coverage
                  against. Ignored if sent on a request.
    PushSubscriptionRequest:
      type: object
      required: [endpoint, p256dh, auth]
      properties:
        endpoint:
          type: string
          format: uri
          description: |
            Push service endpoint URL from the browser's
            `PushSubscription`. Must be HTTPS with a non-empty host.
          example: https://fcm.googleapis.com/fcm/send/abcd1234
        p256dh:
          type: string
          description: |
            Base64url-encoded P-256 ECDH public key from the browser.
            Write-only — never returned in any response.
        auth:
          type: string
          description: |
            Base64url-encoded auth secret from the browser, used
            server-side to encrypt push payloads. Write-only —
            never returned in any response.
        user_agent:
          type: ["string", "null"]
          description: Optional client UA string for operator-facing UI.
    PushSubscriptionResponse:
      type: object
      properties:
        id:
          type: integer
          format: int64
        endpoint:
          type: string
          format: uri
        user_agent:
          type: ["string", "null"]
        created_at:
          type: string
          format: date-time
      description: |
        Persisted push subscription as exposed via the REST API. The
        `p256dh` and `auth` write-only secrets are intentionally
        omitted to prevent exfiltration via a compromised dashboard
        token.
    WebhookDelivery:
      type: object
      properties:
        id:
          type: integer
          format: int64
        webhook_id:
          type: integer
          format: int64
          description: |
            A recipient id (issue #212) — the field name is kept for wire
            compatibility; it has not named a row in the legacy `webhooks`
            table since the recipients migration. A row can represent an
            email delivery (issue #321), a Slack post (issue #359), or a
            PagerDuty Events API v2 event (issue #363) as well as a
            webhook POST — check the referenced recipient's `type` to tell
            which; `last_response_code` is SendGrid's status for email
            (202 on success, 0 on transport error), the destination's HTTP
            status for webhook, Slack's own HTTP status for slack
            (`response_body` carries Slack's error string, e.g.
            `"no_service"`), and PagerDuty's own HTTP status for pagerduty
            (`response_body` carries FIXED outcome text, e.g.
            `"PagerDuty accepted the event (HTTP 202)"` or
            `"PagerDuty rate-limited the event (HTTP 429)"` — never
            PagerDuty's actual response body, which could echo the
            routing key) — for both slack and pagerduty, only 429 and 5xx
            retry; every other non-2xx, 3xx included, is terminal on the
            first attempt. For webhook (issue #614), a redirect is never
            followed: a 3xx is terminal on the first attempt, with
            `response_body` set to the fixed text `"The endpoint answered
            with a redirect. Use the final URL."`; every other webhook
            non-2xx retries. A pagerduty row with no `outage_id` — enqueued
            before issue #363, or an "up" recovery whose onset transition
            left no open incident to inherit an outage id from — fails
            immediately with `response_body` `"no outage key"` and no
            request ever sent; such a recovery is never reported to
            PagerDuty.
        monitor_id:
          type: integer
          format: int64
        account_id:
          type: integer
          format: int64
        event_type:
          type: string
          enum: [down, up, flapping, blocked]
          description: |
            The delivery's event. `blocked` (issue #558) is the "Your
            firewall is blocking Monitive" notice, or (issue #621, the
            delivery's `reason` is `robots_txt`) the "Your robots.txt is
            blocking Monitive" notice naming the fix, routed through the
            recipient's `down` subscription and never sent to PagerDuty.
          example: down
        payload_hash:
          type: ["string", "null"]
        status:
          type: string
          enum: [pending, retrying, delivered, failed, superseded, cancelled]
          description: |
            `superseded` (added for issue #165): an older `pending`/`retrying`
            delivery for the same webhook+monitor pair was replaced by a
            newer one, bounding a swarm of stale notifications after an
            outage recovers to at most one live delivery per pair at a
            time. Not immutably terminal: the
            replacement is not atomic with dispatch, so a delivery already
            in flight when it was superseded can still complete and
            transition to `delivered` for that one attempt — a subscriber
            can still receive a delivery for a transition that was
            superseded before it arrived.

            `cancelled` (added for issue #338): a `down` delivery that
            had not been delivered when its outage recovered — still
            inside its `grace_s`, due but not yet claimed for dispatch, or
            waiting to retry after a failed attempt (issue #581); in that
            case no `up` is enqueued for that recipient. A `down` already
            claimed for dispatch, or one that replaced an earlier unsent
            `up`, is `superseded` instead. Also a delayed `down` that a
            pause ended inside its `grace_s`, or one whose recipient's
            events narrowed to drop `down` while it was still pending.
            Never reused for `superseded` — nothing replaced the row, it
            was never delivered. Also not
            immutably terminal: a row already claimed for dispatch when an
            events-narrowing edit cancels it can still complete and
            transition to `delivered`.
        attempt_count:
          type: integer
        collapsed_count:
          type: integer
          description: |
            The number of older live (`pending`/`retrying`) delivery rows
            this row superseded, plus their own accumulated collapsed
            counts. Zero for a delivery that superseded nothing. This is
            NOT a count of POSTs guaranteed suppressed, and NOT a count of
            transitions the subscriber missed: a superseded row can still
            be in flight and reach `delivered` after being counted here.
            Mirrors the outbound `collapsed_transitions` payload field.
        next_attempt_at:
          type: string
          format: date-time
        last_attempt_at:
          type: ["string", "null"]
          format: date-time
        last_response_code:
          type: ["integer", "null"]
          description: |
            The HTTP status of the last attempt (see `webhook_id` for the
            per-type meaning). For `type=webhook`, a 3xx here means the
            endpoint answered with a redirect, which was refused, not
            followed (issue #614).
        response_body:
          type: ["string", "null"]
          description: |
            Truncated copy (≤4096 bytes, NUL-stripped, valid UTF-8) of the
            subscriber's HTTP response body from the last attempt, for
            `type=webhook`/`type=email`/`type=slack`. Present to help
            debug rejected deliveries; null for rows recorded before this
            was captured or when the subscriber returned no body. A
            `type=webhook` row failed on a 3xx (issue #614) carries the
            fixed text `"The endpoint answered with a redirect. Use the
            final URL."`, never the redirect's own body. For
            `type=pagerduty` (issue #363), this is NEVER the actual
            response body — it is always one of a small set of fixed
            outcome strings (e.g. `"PagerDuty accepted the event (HTTP
            202)"`, `"PagerDuty rejected the event (HTTP 400)"`,
            `"PagerDuty request failed (timeout)"`, or `"no outage key"`),
            because a real PagerDuty response body could echo the request
            back, including the routing key.
        created_at:
          type: string
          format: date-time
        cancelled_at:
          type: ["string", "null"]
          format: date-time
          description: Set only when status is `cancelled` (issue #338).
        enqueued_at:
          type: ["string", "null"]
          format: date-time
          description: |
            The Postgres server clock's own stamp of this row's insert
            moment (issue #396) — distinct from `created_at`, which is
            the dispatcher's own Go-clock transition time and so cannot
            be compared against anything the database generates. Null
            for a row written before this column existed; every reader
            treats null as "before any boundary". Used by the
            `?recipient_id=&order=id` drain scan (see
            `/api/v1/webhook-deliveries`'s description) and the guarded
            `DELETE /api/v1/recipients/{recipientID}?replaced_by=`
            endpoint to decide whether a row predates a replacement
            recipient's attachment.
    WebhookDeliveryListResponse:
      type: object
      properties:
        deliveries:
          type: array
          items:
            $ref: "#/components/schemas/WebhookDelivery"
        total:
          type: integer
        limit:
          type: integer
        offset:
          type: integer
    WebhookDeliveryCursorListResponse:
      type: object
      description: |
        The response shape for `?order=id` (issue #396, keyset-paginated
        ascending by `id`) and `?order=newest` (issue #418, keyset-paginated
        descending by `created_at`, then `id`). No `total`/`offset`: cursor mode never runs the
        COUNT(*) that would produce one. `next_cursor` is always present,
        even on the last page, where its value is `null`.
      required: [deliveries, limit, next_cursor]
      properties:
        deliveries:
          type: array
          items:
            $ref: "#/components/schemas/WebhookDelivery"
        limit:
          type: integer
        next_cursor:
          type: ["string", "null"]
          description: |
            Opaque base64url token. Pass back verbatim as `?cursor=` to
            fetch the next page. `null` means no further page exists.
    APIKeyCreated:
      description: API key with the one-time plaintext included.
      type: object
      properties:
        id:
          type: integer
          format: int64
        account_id:
          type: integer
          format: int64
        key_prefix:
          type: string
          example: mk_live_a1b2c3d4
        label:
          type: ["string", "null"]
        revoked_at:
          type: ["string", "null"]
          format: date-time
        created_at:
          type: string
          format: date-time
        key:
          type: string
          description: |
            Full plaintext API key. **Shown once** — store it securely.
          example: mk_live_a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
    Timings:
      type: object
      properties:
        total_ms:
          type: number
          format: float
        dns_ms:
          type: number
          format: float
        tcp_ms:
          type: number
          format: float
        tls_ms:
          type: number
          format: float
        ttfb_ms:
          type: number
          format: float
        server_ms:
          type: number
          format: float
    TestResult:
      type: object
      properties:
        monitor_id:
          type: integer
          format: int64
        timestamp:
          type: string
          format: date-time
        region:
          type: string
        probe_location:
          type: string
        state:
          type: string
          enum: [up, down]
        status_code:
          type: integer
        error:
          type: string
        body_bytes:
          type: integer
          format: int64
        timings:
          $ref: "#/components/schemas/Timings"
        packet_loss_pct:
          type: number
          minimum: 0
          maximum: 100
          description: |
            Ping-only packet loss percentage (0-100). Omitted (not present
            in the object) when not measured — every non-ping check result,
            and a ping probe-side failure that never reached the target. A
            measured 0% loss is present with value 0, distinct from omitted.
    FeedTokenResponse:
      type: object
      properties:
        token:
          type: string
          example: fd_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d
    FeedIncident:
      type: object
      properties:
        id:
          type: integer
          format: int64
        monitor_name:
          type: string
        monitor_host:
          type: string
          description: |
            The monitor's host only (issue #514), never its full URL.
            For http/https monitors, the lowercase host, with the port
            only when it is not the scheme's default. For tcp monitors,
            `host:port`. For ping/dns monitors, the bare host. The empty
            string when no clean host can be derived or the monitor
            lookup fails.
          example: example.com
        monitor_url:
          type: string
          deprecated: true
          description: |
            Deprecated alias; always equal to `monitor_host`. Never the
            full monitor URL.
        monitor_type:
          type: string
        type:
          type: string
          enum: [down, flapping]
        started_at:
          type: string
          format: date-time
        resolved_at:
          type: ["string", "null"]
          format: date-time
    FeedResponse:
      type: object
      properties:
        account:
          type: object
          properties:
            github_username:
              type: string
              deprecated: true
              description: Deprecated; always the empty string.
        incidents:
          type: array
          items:
            $ref: "#/components/schemas/FeedIncident"
  headers:
    XRateLimitLimit:
      schema:
        type: integer
      description: |
        Bucket capacity for the limiter that produced this response. `200`
        for the global per-account dispatcher cap; `20` on a 429 from the
        per-route monitor-create limiter.
    XRateLimitRemaining:
      schema:
        type: integer
      description: |
        Tokens left in the bucket after this request was charged
        (floor of the post-charge token count). `0` on a 429 means the
        request was rejected with the bucket empty.
    XRateLimitReset:
      schema:
        type: integer
      description: |
        Unix epoch seconds at which the bucket would be full again if no
        further requests are made. Sub-second fragments are rounded up so
        `Reset - now` is never less than the actual refill duration.
    EmailPageCSP:
      schema:
        type: string
      description: |
        The hashed, per-page `Content-Security-Policy` served on this
        response (issue #483): `default-src 'none'; style-src
        'sha256-d7Dj8X9zCXYc4kqEK7rs5Am/yTA8N8FL15RCe/TfiZk='; frame-ancestors
        'none'`, overriding the process-wide `default-src 'none'; frame-ancestors
        'none'` default on this route only. The hash is computed at process
        start from the exact CSS block all 13 of these pages share, so it
        can never drift from the `<style>` actually served. Not present on
        a `429` from the same route — that response is JSON and keeps the
        process-wide default.
    StatusPageAge:
      schema:
        type: integer
      description: |
        Seconds since the origin built the `View` currently being served —
        `0` on the request that populated the cache, growing on every
        subsequent request served from that same entry. Computed the same
        way (live clock minus the cache entry's insertion time) for all
        five status-host formats (issue #368, badge added by #383), so two
        requests served from one cache entry at the same instant carry
        identical `Age` — this is not a promise that `Age` itself stays
        constant across requests over time.
    StatusPageCacheControl:
      schema:
        type: string
      description: |
        `public, max-age=<N>`, where `N` is the serving cache entry's full
        freshness lifetime as cached — `60` for a settled view (the live
        status agrees with the open incident rows), `5` for an unsettled
        one — never reduced by `Age`: an HTTP cache already subtracts
        `Age` from `max-age` itself to get the remaining lifetime, so an
        already-reduced `max-age` would double-subtract. Identical across
        all five formats for one cache entry.
    StatusPageRetryAfter:
      schema:
        type: integer
      description: |
        Fixed at `5` — the shared view-build deadline
        (`StatusPageBuildTimeout`) that expired while this request was
        still live.
  responses:
    BadRequest:
      description: Invalid request.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Unauthorized:
      description: Missing or invalid credentials.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: invalid credentials
    InternalError:
      description: Internal server error.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    AccountSuspended:
      description: |
        Account is currently suspended. On `POST /api/v1/monitors`, and on
        a `PUT /api/v1/monitors/{monitorID}` that changes `url` or `type`
        (issue #335), this can also be returned by the per-account
        port-scan heuristic when the triggering request crossed the
        port-fan threshold inside the sliding window (10 minutes by
        default; `SCAN_WINDOW`). A host-fan trip does NOT suspend the
        account — see the 429 response instead.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: account suspended; contact support
    RequestEntityTooLarge:
      description: |
        Request body exceeds the 64 KB hard limit. Per docs/SPEC.md
        §Hard Limits the dispatcher rejects any payload larger than
        65,536 bytes before it is decoded.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: request body exceeds 64 KB limit
    UnsupportedMediaType:
      description: |
        The request `Content-Type` is not `application/json`. Write
        operations (POST, PUT, PATCH, and a DELETE that takes a request
        body) require that header; a missing or
        non-JSON media type is rejected before the body is read.
        The `charset` parameter is accepted and ignored, so
        `application/json; charset=utf-8` is valid.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: unsupported media type, expected application/json
    MethodNotAllowed:
      description: |
        The HTTP method is not supported for this path. The `Allow`
        response header lists the methods this endpoint accepts.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: method not allowed
    RateLimited:
      description: |
        Per-account dispatcher rate limit exceeded (200 requests/minute).
        The `Retry-After` header gives the integer seconds until at least
        one token has refilled. The `X-RateLimit-*` trio reflects the
        bucket whose rejection produced this response — usually the global
        200/min cap; on `POST /api/v1/monitors` a 429 may instead reflect
        the per-route 20/min creation limit.
      headers:
        Retry-After:
          schema:
            type: integer
          description: Seconds until the next allowed request.
        X-RateLimit-Limit:
          $ref: "#/components/headers/XRateLimitLimit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/XRateLimitRemaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/XRateLimitReset"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: account rate limit exceeded; retry in 1s
    MonitorUpdateRateLimited:
      description: |
        Per-account dispatcher rate limit exceeded on
        `PUT /api/v1/monitors/{monitorID}` (issue #335). Two possible
        causes, distinguishable by `X-RateLimit-Reason` header (absent on
        the global-cap rejection) — no creation-cap case, since `PUT` has
        no equivalent to `POST`'s 20/min creation limiter:

        1. **Global cap** (200/min per account): `error` contains
           `"account rate limit exceeded; retry in <N>s"`.
           `X-RateLimit-Limit: 200`.
        2. **Host-fan**, tripped by a request that changes `url` or `type`
           and would exceed either the account's inclusive 30-minute burst
           allowance (`limits.host_fan_threshold`) or its fixed rolling
           24-hour allowance (`2 * max_monitors`): body is the `HostFanError` schema with
           `retry_after_seconds` and `limit`. `X-RateLimit-Reason:
           host_fan`. Account is NOT suspended. `X-RateLimit-Limit`/
           `X-RateLimit-Window` and the body's `limit`/`window_seconds`
           always reflect the controlling allowance and window.

        The `Retry-After` header is present in both cases (integer >= 1).
      headers:
        Retry-After:
          schema:
            type: integer
          description: Seconds until the next allowed request.
        X-RateLimit-Limit:
          $ref: "#/components/headers/XRateLimitLimit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/XRateLimitRemaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/XRateLimitReset"
        X-RateLimit-Reason:
          schema:
            type: string
            enum: [host_fan]
          description: Present only on host-fan rejections.
        X-RateLimit-Window:
          schema:
            type: integer
          description: Sliding-window length in seconds (present on host-fan rejections).
      content:
        application/json:
          schema:
            anyOf:
              - $ref: "#/components/schemas/Error"
              - $ref: "#/components/schemas/HostFanError"
          examples:
            globalCap:
              summary: Global rate cap (200/min)
              value:
                error: account rate limit exceeded; retry in 1s
            hostFanBurst:
              summary: Ninth domain exceeds an inclusive burst allowance of 8
              value:
                error: "too many distinct domains in a rolling window; slow monitor creation or target changes and retry"
                limit: 8
                window_seconds: 1800
                retry_after_seconds: 347
            hostFanDaily:
              summary: Daily allowance controls the retry
              value:
                error: "too many distinct domains in a rolling window; slow monitor creation or target changes and retry"
                limit: 200
                window_seconds: 86400
                retry_after_seconds: 7200
    ServiceUnavailable:
      description: |
        The test was not sent, for one of two reasons. The `Retry-After`
        header suggests a polite re-try window in both.

        * The dispatcher's global kill switch is engaged; no checks will be
          dispatched until an operator lifts it. Body:
          `{"error": "kill_switch_active", "message": "check dispatches temporarily disabled"}`.
        * (issue #621) The site's robots.txt answered with a 5xx, or the
          probe could not fetch it, and no copy is cached, so robots.txt
          cannot be obeyed yet. Body: `{"error": "robots.txt is temporarily
          unavailable; retry in 60s"}`, with `Retry-After: 60`.
      headers:
        Retry-After:
          schema:
            type: integer
          description: Suggested seconds before retrying.
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
                example: kill_switch_active
              message:
                type: string
                description: Present on the kill-switch response only.
                example: check dispatches temporarily disabled
            required: [error]
    StatusPageNotFound:
      description: |
        Unknown or malformed token, a page that is off, a deleted
        monitor, or a suspended account — all indistinguishable, and all
        five status-host formats (`/{token}`, `/{token}/feed.rss`,
        `/{token}/feed.atom`, `/{token}/status.json`,
        `/{token}/badge.svg`) return this identical shape. A malformed
        token (wrong length, prefix, or a non-hex/uppercase character)
        never reaches the database lookup the other cases do.
    StatusPageInternalError:
      description: |
        The token lookup, the view build, or the format's own render
        step failed for a reason other than the deliberately
        indistinguishable 404 cases above — a connection failure, query
        timeout, or scan error. Distinct from `503` below, which is
        specifically the shared view-build deadline expiring.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    StatusPageUnavailable:
      description: |
        The shared view-build deadline (`StatusPageBuildTimeout`, 10s)
        was exceeded while this request was still live — e.g. database
        slowness. Distinct from a client disconnecting mid-build, which
        writes no response at all. Every one of the five status-host
        formats returns this identical shape, including the
        `Retry-After` header.
      headers:
        Retry-After:
          $ref: "#/components/headers/StatusPageRetryAfter"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
