<!-- REST API & read keys — Heystack docs. Rendered: https://heystack.dev/docs/api · Index: https://heystack.dev/llms.txt -->
# REST API & read keys

Everything the console and the [MCP server](https://heystack.dev/docs/mcp) can do is available as a plain HTTPS API — for health checks, status pages, internal dashboards, CI checks, scripts, and autonomous agents that need to look at production logs and traces without a human at the keyboard.

```
Base URL:  https://ingest.heystack.dev
Auth:      Authorization: Bearer <credential>
Format:    JSON in, JSON out
```

> Sending telemetry is a different thing: your app pushes OpenTelemetry to `/v1/traces`, `/v1/logs`, `/v1/metrics` with an **ingest key** (`sk_live_…`, `hs_web_…`, `hs_ios_…`, `hs_android_…`), as described in [The SDK](https://heystack.dev/docs/sdk). Ingest keys are **write-only** — the read API rejects them with `401`. The public Browser key (`hs_web_…`) is narrower still: it is accepted only on `/v1/traces`, `/v1/logs`, `/v1/replay`, `GET /v1/replay/config` and `/v1/bug-reports`, and gets `403` on `/v1/metrics`, `/v1/sampling/config` and `/api/dsyms`. dSYM upload needs a server key (`sk_live_…`). This page covers the **read/manage** API under `/api/*` (plus `GET /v1/ingest/counters`).
>
> To check a server key and the endpoint before changing any code, `POST /v1/test-event` with `Authorization: Bearer sk_live_…` answers `200 {ok, app_id, app_name, received_at, message}` and records the app's `test_event_received` milestone. It stores no telemetry and never counts as the app's first signal. A Browser key gets `403`.
>
> Spans sent to `/v1/traces` that describe an exporter's own upload to Heystack (a request other than `GET`/`HEAD` to `/v1/traces`, `/v1/logs`, `/v1/metrics`, `/v1/replay` or `/v1/bug-reports` on the ingest host) are discarded on arrival, so tracing your telemetry exporter cannot feed back into itself.

## Authentication

Four kinds of credential are accepted, all as `Authorization: Bearer …`. Pick by who the caller is:

| Credential | Looks like | Acts as | Can do | Made for |
|---|---|---|---|---|
| **Read key** | `hs_read_…` | the workspace (or one app) — not a person | **read only**, 7-day window cap, per-key rate limit | unattended agents, status pages, dashboards, monitoring scripts |
| **Personal access token** | `hs_pat_…` | **you**, in one workspace | the scopes you chose: `read`, `write`, `admin`, limited to what your **current** role allows; expires | CI, scripts and agents acting on your behalf |
| **OAuth access token** | a signed JWT | you, via an MCP client, in the workspace you chose when connecting | your role's scopes | [MCP clients](https://heystack.dev/docs/mcp) (Claude, Cursor, …) |
| **Session** | a short-lived signed JWT | you | your role's scopes | the console |

Heystack is moving sign-in from Clerk to its own sign-in service at `auth.heystack.dev`. During the move both kinds of session and OAuth token are accepted, so nothing you already use stops working; MCP connections made before the move may hold an opaque `oat_…` token until you reconnect. Your role is always read from the workspace's membership on every request, never from the token itself. Personal access tokens and read keys are unaffected.

`GET /api/me` tells you which one you sent and what it can do:

```bash
curl -H "Authorization: Bearer $HEYSTACK_TOKEN" https://ingest.heystack.dev/api/me
```

```json
{ "tenant_id": "org_…", "org": { "id": "org_…", "name": "Acme", "slug": "acme" },
  "user_id": "user_…", "role": "org:admin", "auth": "pat", "scopes": ["read", "write"],
  "token": { "id": "tok_…", "name": "ci", "prefix": "hs_pat_ab12cd34", "expires_at": "2027-01-01T00:00:00.000Z" },
  "app_scope": null }
```

For a read key, `auth` is `"read_key"`, `user_id` is `"key:<key id>"`, `scopes` is `["read"]` and `app_scope` is the app id it is pinned to (`null` for an org-wide key).

### Read keys (`hs_read_…`)

A read key is a credential that can **only read**. It can never send telemetry — every ingest endpoint rejects it with `401` — and it carries the single scope `read`, so nothing that changes your workspace or spends on your behalf will accept it. That makes it safe to hand to a monitoring script, a status page or an unattended agent.

Read keys come in two shapes:

- **Org-wide** — sees every app in your workspace.
- **App-scoped** — sees only the one app it was minted for. Other apps are simply absent from its responses, and any `app=` parameter is overridden by the key's own app.

Only an **Admin** can mint a read key. In the console, open **Settings › Organisation › Coding agents & API**, choose org-wide or pick an app, and mint. The full key is shown **once** — copy it straight into your secret store. The list shows each key's prefix and when it was **last used**, and you can **revoke** a key at any time; revoked keys stop being accepted immediately. (Programmatically: `POST /api/org/read-keys`, below.)

Because a key is meant for unattended callers, two guard-rails apply to keys that don't apply to a person's credentials:

- **7-day maximum range.** `window` longer than `7d`, or `from`/`to` more than 7 days apart, returns `400` with `{"error":"window too long (max 7d for read keys)"}`. `to` without `from` is rejected too, and a malformed `window` returns `400` rather than being silently widened. Omit the range and you get the endpoint's default (usually `24h`). Need more history? Page through it a week at a time.
- **120 requests per minute per key.** Over that, requests return `429` with `{"error":"rate limited"}` and a `Retry-After: 60` header. Back off and retry after the header's delay.

A few reads are **kept for people** (session, OAuth or PAT) and answer `403 { "reason": "read_key_not_allowed" }` for a key: **"Explain this trace"** (`/api/traces/:id/explain` runs an AI model per call), **alert rule definitions** (`GET /api/alert-rules` — a rule points at one of your notification channels; the response carries only `channel_id`, `channel_name`, `webhook_configured` and `webhook_kind`, never the webhook URL; alert *events* are readable), **notification channels** (`GET /api/notification-channels`, the delivery destinations those rules use), **saved-view writes** (`POST`/`PATCH`/`DELETE /api/views*`, pins included; listing views is allowed), **the workspace surface** (`/api/org*` — members, invites, read keys themselves), **tokens** (`/api/tokens`), **Ask** (`POST /api/ask`, which spends model budget), **the issue summary** (`POST /api/inbox/:issueKey/narrative`, which spends AI credits), **fix and deploy writes** (linking, cancelling or resolving a fix, and `POST /api/deploys`) and **free-form SQL** (`POST /api/query/sql`, which can't be app-scoped or window-capped by construction) and **where a visitor is** (`GET /api/monitoring/network`, an IP-to-location lookup). A key never sees the visitor network identity Heystack recognises. These are removed from what it reads (telemetry, logs, traces, trace events, monitoring, replay sessions, people sessions and bug reports), matched case-insensitively with `-` and `_` treated alike: attributes starting `client.`, `source.`, `net.peer.`, `net.sock.peer.`, `network.peer.`, `geo.`, `heystack.geo.`, `cf.`, `user_agent.` and `cloudflare.email.`; every `http.request.header.*`; `http.client_ip`, `http.user_agent`, `net.country`, `net.asn`, `faas.invoked_region`; the Cloudflare visitor fields (`cloudflare.asn`, country, city, region, postal code, latitude, longitude, timezone, `colo`); the `client_ip`, `geo_*` and `cloudflare_colo` columns, and the runtime summary's `top_colos`, which a key's response leaves out (a key's default compare also leaves `cloudflare_colo` out of the fields it compares); a replay session's `browser` (returned as `null`); and a bug report's reporter `email`. A key never reads end-user profile attributes either: every attribute starting `user.`, `enduser.` or `heystack.user.`, except the id keys `user.id`, `enduser.id` and `heystack.user.id`, so a person's name, email, display name and profile source come back empty. A key never reads AI prompt or completion text either: these attributes are removed too, each with every key under it: `gen_ai.prompt`, `gen_ai.completion`, `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`; the Vercel AI SDK's `ai.prompt`, `ai.response.text`, `ai.response.object`, `ai.response.toolCalls`, `ai.response.reasoning`, `ai.toolCall.args`, `ai.toolCall.result`, `ai.value` and `ai.values`; `llm.prompt(s)`, `llm.completion(s)`, `llm.input_messages`, `llm.output_messages`, `input.value`, `output.value`, `llm.prompt_template.template`, `llm.prompt_template.variables`, `retrieval.documents` and `embedding.embeddings` (OpenInference); `traceloop.entity.input` and `traceloop.entity.output`; Cloudflare AI Gateway’s `gen_ai.prompt_json` and `gen_ai.completion_json`; Mastra’s `mastra.<span type>.input` and `mastra.<span type>.output`; LiteLLM’s `llm.openai.messages`, `llm.openai.choices` and `metadata.requester_metadata`; Pydantic AI’s `pydantic_ai.all_messages` and `final_result`. The model, token usage, operation and tool name stay. A log whose `event_name` starts with `gen_ai.` (a GenAI message event such as `gen_ai.user.message` or `gen_ai.choice`) comes back with an empty `body`, because the body is the message. A key's free-text search matches names, ids and message text, never attribute contents or a GenAI message event's body, and a request that filters, groups or lists by any of those attributes (`attrKey`, `filterField`, `field`, `fields`, `groupBy`, column filters; `attr:` and `resource:` forms included) is `403 read_key_not_allowed`. A key can still see your app's own user ids (`enduser_id`), because the product shows them. Removal is by key name, so an address written into a log message or stored under a custom attribute name is not recognised. The [MCP server](https://heystack.dev/docs/mcp) accepts a read key as well: connect with it and you get the core toolset's read tools.

**More people-only routes and removed keys.** A read key also answers `403 read_key_not_allowed` on `GET /api/profiles`, the people-data connector routes (`/api/connectors*`) and `PUT /api/apps/{id}/profiles`, every `/api/github` route, `POST /api/key-events/preview`, `GET /api/key-events/suggestions`, `POST /api/key-events/suggest`, `GET /api/ai/conversations/export`, `POST /api/ai/conversations/{traceId}/mark`, every `/api/ai-spend/pools*` route, `PUT /api/apps/{id}/sdk-config` and the person erase and export routes. It may read `GET /api/key-events`, `GET /api/key-events/{id}`, `GET /api/key-events/journeys`, `GET /api/events/catalogue`, `GET /api/events/volume`, `GET /api/ai/health` and its drilldown, `GET /api/ai-spend` and `GET /api/ai-spend/budgets` (an explicit `from`/`to` longer than 7 days is `400`), `GET /api/apps/{id}/sdk-config` and the security exception, custom-rule, guard-fleet and posture reads (an app-scoped key is pinned to its app). People reads answer a key with ids only: no `profiles` map, no names, emails, plans or account names. Besides the AI keys above, these are removed from every row a key reads, and filtering or grouping on them is refused: `gen_ai.prompt_json`, `gen_ai.completion_json`, `llm.prompt_template.template` and `.variables`, `retrieval.documents`, `embedding.embeddings`, `mastra.<step>.input|output`, `llm.openai.messages|choices`, `metadata.requester_metadata`, `pydantic_ai.all_messages` and `final_result`; identify and group traits (`heystack.traits.*`, `heystack.account.traits.*`); and feedback comments (`heystack.feedback.comment`, `score_comment`). Security decision explanations lose `match_sha256`, and exceptions show an empty hash.

**A note on replays.** Replay chunks contain the recorded screen of a real user session. A read key can read them, exactly as a console user can, so treat a key that has access to an app with session replay enabled with the same care you'd give a console login.

### Personal access tokens (`hs_pat_…`)

Create one in the console under [**Settings › Organisation › Coding agents & API**](https://console.heystack.dev/settings/org/agents). Only a signed-in console session can create a token: a request authenticated with another token (a PAT or an MCP/OAuth access token) gets `403 { "reason": "session_required" }`, so a leaked token can't be used to mint fresh ones. Tokens belong to **you** in **one workspace** and carry the **scopes** you chose (`read`, `write`, `admin`).

Every request with a token is checked against your role in that workspace **now**, not the role you had when you created it (re-checked at least once a minute):

- **Role lowered** (Admin → Member): the token keeps working, but only with the scopes your new role allows, so an `admin` token stops doing admin actions.
- **Role raised**: the token does **not** gain scopes it wasn't created with.
- **Removed from the workspace** (or account deleted): the token is rejected with `401` and revoked.
- **Membership can't be checked right now** (a brief outage): the request is rejected with `401`, but the token is **not** revoked and the failure does not count against your failed-attempt budget. Retry shortly.

Tokens expire on the date you set and can be revoked at any time. OAuth access tokens issued to MCP clients are accepted on the same endpoints with the same scopes as your role.

### Failed sign-in attempts

Repeated requests with an invalid, expired or revoked credential from one network address count against a per-address budget (shared with the ingest endpoints). Over budget, the API answers `429 { "error": "rate limit exceeded" }` with `Retry-After: 60` for that address, even for a valid credential, until the window passes. Valid credentials never use up the budget. If you hit this, fix the failing credential first, then retry after the delay.

### Recommended production settings (operators)

These ingest Worker variables tighten which tokens the API accepts. Both are unset by default, which keeps the current behaviour:

| Variable | Effect | Recommended value |
|---|---|---|
| `OAUTH_ALLOWED_CLIENT_IDS` | Comma-separated OAuth client ids. When set, an OAuth access token issued to any other client is rejected (`401`). | The client ids of the MCP clients you support. Check `client_id` in `GET /api/me` (or the audit log) for each one before you turn this on, because dynamically registered clients each get their own id. |
| `OAUTH_RESOURCE` | Clerk-issued tokens: when set, a JWT access token that carries an `aud` claim must include this value, or it is rejected (`401`); tokens with no `aud`, and opaque `oat_…` tokens, are not checked. Tokens from Heystack's own sign-in service always carry an audience, and it must include this value (or `MCP_RESOURCE` when this is unset); a token without it is rejected. | `https://mcp.heystack.dev/mcp`. For Clerk-issued tokens, first confirm that your MCP clients' access tokens carry that audience, because some issuers put the client id in `aud`. |

Session tokens are also bound to the console's origins: a session token whose `azp` (the site it was issued for) isn't in `CORS_ORIGINS` is rejected. When `CORS_ORIGINS` is unset (local development) only the local console origin, `http://localhost:5173`, is accepted.

Tokens from Heystack's sign-in service are checked locally against its published signing keys (EdDSA only, each token kind against its own key set), so a session token can never be used as an MCP access token or the reverse. An MCP access token must name a workspace (`org_id`); a token without one is rejected. If those keys can't be fetched, requests answer `401` and the fetch is retried at most every 10 seconds.

Once the move to Heystack's own sign-in is complete, every credential's role is read from Heystack's membership records, including an older Clerk console session that is still open: a member who was removed or demoted loses that access within a minute, whichever sign-in they used.

### Errors

| Status | Body | Meaning |
|---|---|---|
| `401` | `{ "error": "unauthorized" }` | Missing/invalid credential, expired or revoked — or an ingest key was used on the read API |
| `401` | `{ "error": "no_organization" }` | OAuth token without a workspace — sign in again and pick one |
| `410` | `{ "error": "organization_deleted" }` | A valid credential of an organisation that has been deleted. Only `GET /api/org/deletion` still answers |
| `403` | `{ "error": "forbidden", "reason": "scope_required", "scope": "write" }` | Credential lacks that scope (a read key only has `read`) |
| `403` | `{ "error": "forbidden", "reason": "admin_required" }` | The action needs the Admin role |
| `403` | `{ "error": "forbidden", "reason": "read_key_not_allowed" }` | That endpoint is for people, not read keys (see above) |
| `403` | `{ "error": "forbidden", "reason": "session_required" }` | Creating a token needs a console sign-in, not another token |
| `400` | `{ "error": "…" }` | Bad parameter (message says which) — including a read key asking for more than 7 days |
| `404` | `{ "error": "not found" }` | Unknown id — or, for an app-scoped key, an app that isn't its own |
| `429` | `{ "error": "rate limited" }` | Slow down — see [rate limits](#rate-limits) (`Retry-After` is set) |
| `429` | `{ "error": "rate limit exceeded" }` | Too many failed sign-in attempts from your address (see above); `Retry-After` is set |
| `502` | `{ "error": "clickhouse" }` | Query backend unavailable; retry |

## Conventions

- **Scope of every read is your workspace.** You never pass a tenant; it comes from the token.
- **Time.** Reads accept either `from` + `to` (ISO 8601) **or** a relative `window` (`15m`, `1h`, `24h`, `7d`, `30d`). If you pass neither, a bounded default applies (usually `24h`; `1h` for health endpoints). Nothing is ever unbounded. Every caller is limited to **30 days**: a longer `window` is treated as `30d`, and a `from`/`to` range only covers the 30 days before `to`. Data is kept for 30 days, so this never hides retained data.
- **App.** Most reads take `app=<app_id>` (the id in the console URL, `?app=<app id>`, and under **Settings › App › Overview**). Omit it on `/api/service-map` for the whole workspace. **Ignored for an app-scoped read key** — the key's own app always wins. Some endpoints (issue-states, alert-events, bug-reports, replays, session-signals) require it.
- **Limits.** `limit` defaults to 100, max 1000. There is no offset pagination — narrow `from`/`to` to page through time.
- **Filters** (traces): `status`, `service`, `kind`, `spanName`, `route`, `method`, `q` (substring on span name/attributes), `attrKey` + `attrValue`, and repeatable `cf=field:value` (equals) and `ncf=field:value` (does not equal) on an allow-listed set of fields (see `GET /api/telemetry/facets`; trace fields include `span_name`, `http_route`, `http_method` and `enduser_id`). Field and value are each percent-encoded, e.g. `ncf=http_route:%2Fhealth`. `ncf=f:v` keeps rows where `f` is empty as well as rows with another value; `ncf=f:` (empty value) keeps only rows where `f` has a value. Logs: `service`, `severity`, `q`, `trace`, `filterField` + `filterValue`, `cf`, `ncf`.
- **Sort.** `sort` + `order` (`asc`/`desc`); traces sort by `timestamp`, `duration_ms`, `status_code`, `span_name`, `service_name`.

## Endpoints

Access column: **read** = any credential with the `read` scope, read keys included; **read (people)** = `read` scope but **not** a read key (`403 read_key_not_allowed`); **write** = scope `write`; **admin** = scope `admin` **and** the Admin role. A read key has only `read`, so every write/admin row refuses it.

### Identity & tokens

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/me` | — | `{tenant_id, org, user_id, role, auth, scopes, token, app_scope}` (`token` set for a PAT or read key; `app_scope` for an app-scoped read key) | read |
| `GET /api/org/read-keys` | — | `{keys:[{id, name, key_prefix, app_id, created_at, revoked_at, last_used_at}]}` — never the hash | read (people) |
| `POST /api/org/read-keys` | `{name?, app_id?: string \| null}` (`app_id` pins the key to one app) | `201 {id, key: "hs_read_…", key_prefix}` — secret shown once | admin |
| `DELETE /api/org/read-keys/:id` | — | `{revoked: boolean}` | admin |
| `GET /api/tokens` | — | `{tokens:[{id, name, token_prefix, scopes, created_at, expires_at, last_used_at, revoked_at, user_id}]}` — yours; admins see the whole organization's | read (people) |
| `POST /api/tokens` | `{name, scopes: ["read", "write"?, "admin"?], expires_in_days?: 1–365}` — scopes must be a subset of your own (`403 scope_exceeds_creator` otherwise) | `201 {token: "hs_pat_…", id, …}` — secret shown once | write, console session only (`403 session_required` for a PAT or OAuth token) |
| `DELETE /api/tokens/:id` | — | `{revoked:true}` | write |

### Apps, keys & configuration

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/apps` | — | `{apps:[{id, name, service_name, framework, repo_url, span_count_24h, last_seen, …}]}` (an app-scoped read key sees only its own app) | read |
| `GET /api/apps/:id` | — | `{app, keys_count, status}` | read |
| `POST /api/apps` | `{name, service_name, framework?}` (`nextjs`, `workers`, `node`, `web`, `ios`, `android`, `otlp` = Python or another OpenTelemetry language, `other`) | `201 {app, key: "sk_live_…"}` — first key shown once. Over the plan's app limit (`enforce` mode only): `403 {error:"forbidden", reason:"plan_limit", limit, plan, resource:"apps"}` | admin |
| `PATCH /api/apps/:id` | `{name?, repo_url?, framework?}` — `repo_url` must be an `https://` URL with a real hostname (no credentials, query or fragment; `""` clears it), else `400 invalid repo_url`; `framework` changes the app's stack (same values as create), else `400 invalid framework` | `{app, repository}` (the [repository view](#apps-keys--configuration) below; the recovery connector is never changed) | admin |
| `GET /api/apps/:id/milestones` | — | `{app_id, milestones:[{milestone, first_at, scope:"app"\|"org"}], first_signal:{first_at, kinds:["trace"\|"log"\|"event"\|"replay"\|"crash"\|"metric"]}\|null, test_event:{first_at}\|null, activation:{activated, reached, next}}`. Reads Heystack's own records only (never an analytics query), so the console's setup page can check it every few seconds; `first_signal` is written as data is stored, whatever kind arrives first. See [Activation milestones](#activation-milestones) | read (read keys allowed; an app-scoped key sees only its own app) |
| `GET /api/apps/:id/privacy` | — | `{ai_content, visitor_network, show_names, sdk_traits_enabled, gateway_spend_source, updated_at}` (`ai_content`/`visitor_network`: `true` = keep what the app sends, the default; `show_names`/`sdk_traits_enabled` default `false`; `gateway_spend_source` defaults to `null`, no rule) | read |
| `PUT /api/apps/:id/privacy` | any of `{ai_content?, visitor_network?, show_names?, sdk_traits_enabled?}` (booleans) and `gateway_spend_source?` (`"app"`, `"gateway"` or `null`); at least one | the stored settings; `400 invalid privacy settings` otherwise. Names apply to the next read; the ingest switches apply to data arriving from about a minute later, never to data already stored. See [Privacy controls](#privacy-controls) | admin |
| `GET /api/apps/:id/repository` | — | repository view `{url, full_name, github, recovery_repository, status}` with `status` one of `unset`, `linked`, `not_github`, `mismatch`. It reads Heystack's own records only (no analytics query). `mismatch` means the app's repository URL and the recovery connector's repository differ (or the URL is not GitHub while a connector exists): recovery keeps using the connector's repository and nothing is blocked; reconnect the connector to align them. App-scoped read keys see only their own app | read |
| `DELETE /api/apps/:id` | — | `{deleted:true, blobs:{deleted,remaining}\|{error:true}}`; `409 recovery_in_progress` while a GitHub run is live | admin |
| `GET /api/apps/:id/status` | — | `{connected, span_count, services, error_rate, last_seen}` (last 15 min) | read |
| `GET /api/apps/:id/presence` | `window` | `{traces, issues, logs, metrics, crashes, replays, genai}` booleans | read |
| `GET /api/apps/:id/keys` | — | `{keys:[{id, key_prefix, key_class, created_at, revoked_at}]}` | read |
| `POST /api/apps/:id/keys` | `{class?: "live" \| "web" \| "ios" \| "android"}` — `live` = server key (`sk_live_`, server-side only), `web` = public Browser key (`hs_web_`) | `201 {key}` — shown once | admin |
| `POST /api/apps/:id/keys/:keyId/revoke` | — | `{revoked:true}` | admin |
| `GET /api/apps/:id/sampling-config` | — | `{trace_sample_rate, keep_errors, keep_slow_ms}` | read |
| `PUT /api/apps/:id/sampling-config` | same shape | normalized config | write |
| `GET /api/apps/:id/replay-config` | — | `{enabled, sample_rate, masking_mode, tracing_enabled, errors_enabled}` | read |
| `PUT /api/apps/:id/replay-config` | same shape (`masking_mode`: `strict`/`relaxed`) | normalized config | write |
| `GET /api/apps/:id/cloudflare-connector` | — | `{connector \| null}` | read |
| `PUT /api/apps/:id/cloudflare-connector` | `{account_id, api_token, script_name?, dispatch_namespace?, enabled?}` | `{connector}` (`dispatch_namespace`: Workers for Platforms namespace, 1-63 chars of `A-Za-z0-9_-`; API-only for now, no console form; a PUT without it clears it, like `script_name`) | admin |
| `DELETE /api/apps/:id/cloudflare-connector` | — | `{deleted}` | admin |
| `POST /api/apps/:id/cloudflare-connector/sync` | — | sync result | admin |

### Security control plane

Security policy is selected by app, deployment environment, and profile. Runtime
keys (`hg_live_…`) are separate from ingest/read/API credentials and are shown
only once. Policy mutations and dry runs require an Admin; reads require the
`read` scope and remain tenant/app scoped.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/security/policies` | optional `app` | Policies with immutable versions and active version. A read key gets metadata only: `{id, app_id, deployment_environment, profile, active_version, created_at, updated_at, versions:[{version, checksum, state, created_at, published_at}]}`, never the rule `config`. For people each version carries `signature`: `"present"` only when the stored config still matches its checksum and the signature verifies under the current signing key (as the guard checks), otherwise `null`. For people, each policy lists at most its newest 50 versions plus the active one; `versions_truncated: true` says older ones were left out. A read key gets every version and no `versions_truncated` field | read |
| `POST /api/security/policies` | `{app_id: string\|null, deployment_environment, profile, config?}`: `app_id` is an app of this organisation, or `null` for the organisation minimum; `profile` and `deployment_environment` are lowercase names (`[a-z0-9][a-z0-9_-]`, at most 64 characters); `config` defaults to the starter policy | `201 {policy}` with draft v1. `400` for an invalid field, `404` for an unknown app (an app-scoped credential may only name its own app), `409 {error:"policy already exists"}` for a second policy with the same app, environment and profile | admin (org admin role and the `admin` scope) |
| `POST /api/security/policies/:id/versions` | `{config}` | `201 {version}` draft | admin |
| `POST /api/security/policies/:id/versions/:version/publish` | `{evaluation_id}` | Signed published version | admin |
| `POST /api/security/policies/:id/rollback` | `{version, evaluation_id}` | Re-signed active version | admin |
| `POST /api/security/evaluate` | `{request, config}` | Deterministic shadow decision; sample content is not retained | admin |
| `GET /api/security/keys` | optional `app` | Runtime-key metadata; never the hash or full key | read |
| `POST /api/security/keys` | `{app_id, deployment_environment, allowed_profiles, name?, expires_at?}`: `app_id` and `deployment_environment` are required; `allowed_profiles` is 1–32 profile names (`[a-z0-9][a-z0-9_-]`, at most 64 characters); `name` is trimmed to 80 characters; `expires_at` is an ISO-8601 time or `null` | `201 {id, key, prefix}`: an AI safety runtime key (`hg_live_…`), shown only in this response. `400 {error:"app_id required"\|"allowed_profiles required"\|"deployment_environment required"\|"invalid expires_at"}`, `404` for an unknown app (an app-scoped credential may only name its own app) | admin (org admin role and the `admin` scope) |
| `POST /api/security/keys/:id/revoke` | — | `{revoked:true}` | admin |
| `POST /api/security/issues` | `{app_id, deployment_environment, decision_id, policy_checksum, recorded_at_ms, review_phase, rule, category}` (body at most 4 KB) | Tracks one security decision as an issue: `{fingerprint, source_digest, evidence:"tracked_decision_metadata", verification:"not_verified"}`. The decision is re-read from the analytics store and must still match (`409 source_changed` otherwise, `404 source_not_found`, `422 invalid_source_or_rule`) | scopes `read` and `write` |
| `GET /api/security/issues` | required `app`; optional `fingerprint` (`sec_` + 64 hex) | `{issues, truncated, limit:50}`: the app's tracked groups, newest first. Each carries `verification` (`not_verified`, `historical_verification` or `operator_verified_current_policy`), `source_count`, the verification counts, `note` and `assignee`, and a `status` that is **derived from `verification`** (`resolved` only for `operator_verified_current_policy`, otherwise `open`), the same rule the inbox uses. It does not read the stored issue-state status, which a later publish never rewrites. `404` for an app of another organisation; an app-scoped read key is pinned to its app | read (read keys allowed) |
| `GET /api/security/issues/:fingerprint/sources` | required `app` | `{sources, truncated, limit:20}`: the tracked decision metadata behind a group (allow-listed correlation fields only), newest first | read (read keys allowed) |
| `GET /api/security/decisions` | required `app`; optional `window` (max 90d), `deployment_environment`, `release`, `profile`, `action`, `trace`, `decision`, `limit` (1–200), `cursor` | Metadata-only `decisions`, `page_cursor`, `next_cursor`, fixed `window`, `consistency: bounded_live` (pending release) | read |
| `GET /api/security/executions` | required `app`, `deployment_environment`, `turn`; optional `window` (`24h`, `7d` default, `30d`, `90d`) | Scoped lifecycle and receipt completeness, not protection; pending release | read |
| `GET /api/security/receipts` | required `app`, `deployment_environment`, `decision`; optional `window` (`24h`, `7d` default, `30d`, `90d`) | Application receipt variants, conflicts, completeness and explicit time window; pending release | read |
| `GET /api/security/decisions/search` | the AI & Safety decision search: optional `app` (omit for the whole org; an app-scoped key is always pinned to its app), `window` (`15m`, `1h`, `6h`, `24h`, `7d`, `30d`; anything else is `400 bad_window`, and the default is `24h`) or an exact `from` and `to` (both ISO-8601, `from` before `to`, at most 30 days apart, `from` no older than the 90-day retention and `to` no more than 2 days ahead; anything else, or only one of the two, is `400 bad_window`; a valid range replaces `window`), `profile`, `action`, `trace`, `decision`, `user`, `session`, `rule` (each 1-256 characters, longer is `400 {error:"bad_filter", field}`), `limit` (1-200, default 100) | `{ decisions, truncated, profiles, names_shown }`: metadata-only decisions (each carries its `app_id`), newest first, plus `profiles`, `profiles_by_app` (when the page spans apps) and `names_shown` for the people listed (one profile read at most; none for a read key or with names off; email for admins only); `truncated` is true when more exist than `limit`. Cached for 5 minutes. At the critical analytics budget it answers `503 analytics_paused` (admins may retry with `force=1`); a read that hits a scan, time or memory cap is `413 too_broad` (narrow the window or filters) | read |

Runtime enforcement uses `https://guard.heystack.dev`, not `/api/security`.
See [Security](https://heystack.dev/docs/security) for policy behavior and the local/concurrent
integration pattern.

#### Feedback, exceptions, custom rules and posture

Every route here reads and writes D1 only (no analytics read, no budget gate). Errors are `{error, field?}`. "admin" = org admin role and the `admin` scope; "write" = the `write` scope (members); "read" allows read keys, and an app-scoped read key is pinned to its own app (naming another app is `404`). A read route without `app` (and without an app-scoped key) is `400 {error:"app_required", field:"app"}`.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/security/decisions/:id/feedback` | `{app_id, verdict: "fine"\|"should_block", rule?, match_sha256?, tool?}`: `rule` is `secrets`, `pii`, `prompt_injection`, `harmful_content` or `custom:<cr id>`; `match_sha256` is 64 lowercase hex (the decision's `explanation.match_sha256`); `tool` matches `[A-Za-z0-9_.:-]{1,160}`. Body at most 4 KB | `201 {feedback:{id, decision_id, verdict, exception_id, created_at}, exception?}`. A `fine` verdict with a `rule` and a `match_sha256` or `tool` also drafts an exception (state `draft`; the hash wins over the tool). Never stores content. One verdict per person per decision: a second is `409 feedback_exists`. At most 200 verdicts per person per app in 24 hours (`429 feedback_rate_limited`) and 200 unpublished drafts per app (`409 too_many_drafts`; the decision id is not checked, so a draft is only a suggestion for an admin) | write |
| `GET /api/security/exceptions` | `app` | `{exceptions: ExceptionView[]}`, newest first (at most 1,000). `ExceptionView = {id, app_id, deployment_environment ("" = every environment), rule, match:{kind:"sha256"\|"tool"\|"custom_rule", value}, state:"draft"\|"published"\|"revoked", source_decision_id, expires_at, created_by, created_at, published_at}` (times ISO 8601). A read key gets `match.value: ""` for every `sha256` match | read (read keys allowed, hashes blanked) |
| `POST /api/security/exceptions` | `{app_id, rule, match, deployment_environment?, expires_at?}`: `match` is `{kind:"sha256"\|"tool"\|"custom_rule", value}` or `{kind:"text", value}` (an allowed literal, at most 2,000 characters). `text` is hashed under hash normalisation v1 (the guard's canonical view, trimmed, **case kept**, salted with the organisation id) and stored as `sha256`; the literal is never stored. A `custom_rule` match needs `rule: "custom:<value>"`, and a `custom:` rule must name one of the app's custom rules. `expires_at` must be in the future | `201 {exception}` (state `draft`). `400 {error:"invalid_rule"\|"invalid_match"\|"invalid_environment"\|"invalid_expires_at"\|"invalid_exception"\|"unknown_custom_rule", field}` | admin |
| `POST /api/security/exceptions/:id/publish` | — | `{exception}` (state `published`). Idempotent. `409 exception_revoked`, `409 exception_expired`, `409 too_many_exceptions` (at most 200 published, unexpired exceptions per app) | admin |
| `POST /api/security/exceptions/:id/revoke` | — | `{exception}` (state `revoked`). Idempotent | admin |
| `GET /api/security/custom-rules` | `app` | `{rules: CustomRuleView[]}` oldest first. `CustomRuleView = {id, app_id, name, kind:"keyword"\|"pattern"\|"topic", surface?, values?, match?, action, enabled, created_at, updated_at}` | read |
| `POST /api/security/custom-rules` | `{app_id, name (1–80), kind, surface?, values?, match?, action, enabled?}`. `keyword`: `surface` (`input`\|`output`\|`both`) and `values` (1–100 terms, each 1–128 characters); `pattern`: `surface` and `match` with exactly one of `eq`, `prefix`, `suffix`, `contains` (1–256 characters); `topic`: `values` (1–20 labels, each 1–64 characters). `action`: `flag`\|`redact`\|`quarantine`\|`block` (`topic`: no `redact`). **No regular expressions:** any other field (for example `regex`) or match operator is refused | `201 {rule}`. `400 {error:"invalid_custom_rule", field}`; `409 {error:"too_many_custom_rules", limit:50}` | admin |
| `PATCH /api/security/custom-rules/:id` | any of `{name, values, match, surface, action, enabled}` (the kind never changes: `400 kind_immutable`) | `{rule}` | admin |
| `DELETE /api/security/custom-rules/:id` | — | `{deleted:true}`; the rule's exceptions are revoked with it | admin |
| `POST /api/security/policies/:id/versions/compose` | `{mode?: "enforce"\|"watch", explain?: boolean, spend_limit?: {enabled, action:"flag"\|"block", on_unknown:"allow"} \| null}`; an omitted field keeps the latest version's value | `201 {version, contract5, exceptions, custom_rules}`: a new **draft** version built from the policy's latest version, with `mode`, `explain`, the app's published unexpired exceptions for the policy's environment (at most 200), its enabled custom rules (at most 50) and `rules.spend_limit`. A key with nothing to say is left out (`mode` when `enforce`, `explain` when false, an off or cleared spend rule, empty lists), so a policy that uses none of them is byte-identical to its base and `contract5` is `false`. An organisation minimum gets no exceptions or custom rules (they are per app). `400 {error:"invalid_mode"\|"invalid_explain"\|"invalid_spend_limit"}`; `400 {error:"invalid_policy_config", field, problems}` when the result fails the contract-5 check (no version is written). Publish it with the usual evaluate-release + publish | admin |
| `GET /api/security/guard-fleet` | `app` | `{app_id, window_hours:24, reporters:[{version, contract, last_seen}], contract5_ready, reason: null\|"no_recent_reports"\|"older_guard_reporting"}`: the `@heystack/guard` versions this app's processes reported on `GET /v1/policy` in the last 24 hours (no `X-Heystack-Guard` header reads as 0.2.0, contract 4). Ready only when at least one process reported and every one is on contract 5 | read |
| `GET /api/security/posture` | `app`; `days` `7` (default) or `30` (anything else `400 invalid_days`; a read key at most 7) | `{app_id, days, derived, content_scan, patterns:[{pattern, count, sample_trace_id}], daily:[{day, pattern, count}], offenders:[{user_id, count, cost_usd, profile}], scorecard:{items:[{id:"LLM01".."LLM10", title, status:"covered"\|"partly"\|"not_covered"\|"unknown", evidence:[…]}]}}`. `patterns` always lists all six: `secret_in_content`, `personal_data_in_content`, `injection_pattern`, `calls_per_user_hour`, `large_input`, `loop`. `derived` is false while the posture counters are switched off (`DERIVE_POSTURE_ENABLED`, ships `"false"`): nothing is counted, so every pattern reads as not checked (the counts are not measured zeros), `offenders` is empty and the scorecard treats posture as unknown. `content_scan` is true only when `derived` is true, the `POSTURE_SCAN` switch is `"true"` (it ships `"false"`) and the organisation's AI processing switch is on. `offenders` are the top 50 users by count, with their AI cost in USD; `profile` is the user's name card where the app's privacy settings show names, and always `null` for a read key. The counts are Heystack's own records; the names cost one profile read, like the people pages, skipped at the critical budget (then `profile` is `null`). An erased person never appears | read (members; read keys without profiles) |

- **Strict contract-5 check on policy writes.** `POST /api/security/policies` and `POST /api/security/policies/:id/versions` refuse a config whose `mode`, `explain`, `exceptions`, `custom_rules` or `rules.spend_limit` is invalid (an unknown `mode` included) with `400 {error:"invalid policy config", reason}`. A config without those keys is checked exactly as before.
- **Decisions and read keys.** `check_results[]` may carry `would_action` and `explanation: {rule, category, exception_id?, count?, spans?, match_sha256?}`. `GET /api/security/decisions` and `GET /api/security/decisions/search` remove `explanation.match_sha256` from every check for a read key. A watch-only decision has `action: "allow"` and `enforcement_status: "shadow"`; "would have been blocked" = `would_action` in `block`, `quarantine` or `require_approval`.

#### Guard runtime (contract 5)

The guard runtime endpoints (`https://guard.heystack.dev/v1/*`, runtime key `hg_live_…`):

- **Capability negotiation on `GET /v1/policy`.** A caller sends `X-Heystack-Guard: <version>; contract=<n>`. A caller that sends `contract=5` (or higher) gets the policy with every contract-5 key (`mode`, `explain`, `exceptions`, `custom_rules`, `rules.spend_limit`) signed under `detector_version: "deterministic-5"`. Every other caller (no header, a malformed one, or `contract=4`) gets the deterministic-4 projection: watch mode removes the policy's stopping actions; exceptions and custom rules are left out. A policy that uses no contract-5 key is served byte-for-byte as before to everyone. The two forms share the generation, policy id and version; their `checksum` and `ETag` differ, and the response carries `Vary: X-Heystack-Guard`. A policy with an unknown `mode` is never served (`503`). Switch: `GUARD_CONTRACT5_ENABLED` (guard worker var, on only when exactly `"true"`, which is its ship value; anything else serves every caller the projection).
- **`/v1/evaluate` and `/v1/review`** honour mode, exceptions and custom rules for every caller, 0.2.0 included, and answer with the `policy_checksum` of the form the caller holds (the pinned `policy_bundle`'s, else the form its header selects). Watch mode answers `allow` with `enforcement_status: "shadow"`, never interrupts and never counts toward an account action; the decision records each check's `would_action`. Explanations (rule, category, count, spans, hashes; never matched text) and `would_action` are returned only to contract-5 callers and are always recorded in the decision. `/v1/adoptions` and receipts accept either form.
- **Guard versions.** Each `GET /v1/policy` caller's reported version and contract are recorded (no header = 0.2.0). `GET /api/security/guard-fleet` reports contract-5 features ready when at least one process reported in the last 24 hours and none reported a contract below 5.
- **`GET /v1/spend?profile=&deployment_environment=[&user=]`** (runtime key; the key's profile and environment): the app's spend state from enforced budgets, `{scope_state, scopes:[{scope, value, period, state}], resets_at}` with `state` `ok` | `warn` (≥ 80%) | `exceeded`. `user` (1–256 characters) adds that end user's per-user budget, echoed back as `value`; a user with no spend yet is `ok`. Pool scopes use the pool id as `value`. Reads daily D1 counters only, cached 30 s per app, so the state is about a minute behind. `503` when unavailable (callers treat that as unknown, which allows).
- **Soft spend limit.** With `rules.spend_limit.enabled` in the policy and an enforced budget `exceeded`, the worker's answer for a `provider_request` carries the check `{rule:"hard_budget", action:<rule action>, detector:"spend_state", reason:"spend_limit"}` (a 0.2.0 client raises its usual blocked error). Never in watch mode; unknown state allows. It is a budget guard, not a meter: spend made in the last minute can go over.

### App Care

App Care is rollout-gated. Until `CARE_ENABLED` is `"true"` after its D1 migration, these routes return `404 {"error":"app_care_not_enabled"}`. Every route is tenant- and app-scoped. Read keys may read only their permitted app; all mutations require a person or PAT/OAuth credential with the stated scope.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/care/apps/:id/summary` | — | `{summary:{state,last_checked_at,journeys,open_incidents,coverage}}`; stale checks count as unknown | read |
| `GET /api/care/apps/:id/journeys` | — | `{journeys:[…]}` (max 100 returned) | read |
| `POST /api/care/apps/:id/journeys` | `{name,url,method?:"GET"\|"HEAD",expected_status?:number,check_interval_minutes?:5–1440,assertions?:[],browser_steps?:[],browser_allowed_origins?:[]}` | `201 {journey}` | admin |
| `PATCH /api/care/apps/:id/journeys/:journeyId` | editable journey fields | `{journey}`; changed checks return to unknown | admin |
| `POST /api/care/apps/:id/journeys/:journeyId/run` | — | `{run,incident?}`; network/checker errors remain unknown | write |
| `POST /api/care/apps/:id/checkup` | — (uses first enabled journey) | `{checkup,incident?}` with bounded public-response and header observations | write |
| `GET /api/care/apps/:id/incidents` | `state=open\|all` | `{incidents:[…]}` | read |
| `GET /api/care/apps/:id/incidents/:incidentId` | — | `{incident,evidence,investigations,repair_plans,action_runs,recovery_receipts}` | read |
| `POST /api/care/apps/:id/incidents/:incidentId/investigate` | — | `{investigation}` with confirmed facts and open questions | write |
| `POST /api/care/apps/:id/incidents/:incidentId/repair-plans` | `{action_kind,summary,parameters,verification_journey_ids}` plus optional `Idempotency-Key` header | `201 {repair_plan}`; release fence is derived by the server. A `deployment_rollback` `target_release_id` must be a release observed in server telemetry (SERVER spans ingested with an `sk_live_` key; ingest stamps `heystack.key_class` and ignores client-supplied values) in the last 30 days (`400 invalid_target_release_id`). Managed source preparation (`allowed_source_files`) is admin only; its `artifact.review` holds the full diff with `safety_scan: "advisory"` | write (managed source: admin) |
| `POST /api/care/apps/:id/repair-plans/:planId/refresh` | — | latest async preparation status and artifacts | write |
| `POST /api/care/apps/:id/repair-plans/:planId/reconcile-dispatch` | `{decision:"attach_run",external_run_id,confirm:true}` or `{decision:"confirm_not_dispatched",confirm:true}` | reconciles an ambiguous preparation dispatch after the recovery service validates the GitHub evidence | admin |
| `POST /api/care/apps/:id/repair-plans/:planId/approve` | — | `{repair_plan}`; a managed source repair needs its full diff on the plan (`409 managed_review_missing`) | admin |
| `POST /api/care/apps/:id/repair-plans/:planId/execute` | optional `Idempotency-Key` header | `202 {action_run}`; only supervised/autopilot policy modes | admin |
| `POST /api/care/apps/:id/action-runs/:runId/reconcile-dispatch` | `{decision:"attach_run",external_run_id,confirm:true}` or `{decision:"confirm_not_dispatched",confirm:true}` | reconciles an ambiguous execution dispatch without redispatching it | admin |
| `POST /api/care/apps/:id/action-runs/:runId/refresh` | — | `{action_run,verification_pending?}` or `{action_run,recovery_receipt}` | write |
| `GET /api/care/apps/:id/action-policy` | — | `{policy:{mode,allowed_actions,max_actions_per_day,version,…}}` | read |
| `PUT /api/care/apps/:id/action-policy` | `{mode:"watch"\|"prepare"\|"supervised"\|"autopilot",allowed_actions,max_actions_per_day,expected_version?}` — with `expected_version`, a stale value (or a concurrent write) returns `409 {error:"version_conflict",current_version}` and nothing is saved; without it the write always applies | `{policy}` | admin |
| `GET /api/care/apps/:id/recovery-connector` | — | public connector metadata; never its token | read |
| `PUT /api/care/apps/:id/recovery-connector` | `{repository?:"owner/repo",workflow?,base_branch?,token}` — `repository` is optional: when omitted it is taken from the app's GitHub repository URL (`400 repository_required` with no URL, `400 repository_not_github` for a non-GitHub host, `400 invalid_connector_config` if it is not a valid `owner/repo`). Saving makes the connector repository the app's repository (last write wins, overwriting a non-GitHub commit-link URL) | public `{connector, repository}` (`repository` is the repository view); token is write-only | admin |
| `GET /api/care/apps/:id/activity` | `limit` (1–200) | `{activity:[…]}` | read |

Repair action kinds are `source_patch_deploy`, `deployment_rollback`, and `config_restore`. The exact parameter schema is allow-listed by kind; release, configuration and version identifiers are limited to letters, digits and `._:+-`. Under the `autopilot` mode only plans created by an Admin (or by Heystack itself) execute without an approval; plans created with `write` scope wait for an Admin. An executor success is not a recovery: Heystack requires a five-minute observation window, fresh telemetry for the deployed release, and fresh passing results from the unchanged verification journeys before it writes a recovery receipt. See [App Care](https://heystack.dev/docs/app-care).

If GitHub accepts a workflow dispatch but its response is lost, the plan or action remains nonterminal and its activity records that manual reconciliation is required. An Admin must either attach the exact GitHub run after the recovery service validates its repository, workflow, title, commit, and time fence, or explicitly confirm that no dispatch occurred. These reconciliation calls are idempotent and never redispatch the repair.

### Health, issues & releases

| Method & path | Params | Returns | Access |
|---|---|---|---|
| `GET /api/metrics/red` | `app`, `service?`, `route?`, `window` (1h) | `{routes:[{route, requests, errors, error_rate, p50, p95, p99}]}` | read |
| `GET /api/metrics/red/timeseries` | `app`, `service?`, `route?`, `window`, `bucket?` (`1m`, `5m`, …) | `{series:[{ts, requests, errors, p50, p95, p99}]}` | read |
| `GET /api/metrics/anomalies` | `app`, `service?`, `window` (1h; baseline 7d) | `{anomalies:[{metric, current, baseline, ratio, severity}]}` | read |
| `GET /api/issues` | `app`, `service?`, `window` (24h), `limit` | `{issues:[{type, sample_message, fingerprint, events, traces, first_seen, last_seen, sample_traces}]}` | read |
| `GET /api/problems` | `app`, `service?`, `window`, `limit` | `{problems:[{span_name, service_name, count, users_affected, sessions_affected, first_release, last_release, sample_trace_id, …}]}` | read |
| `GET /api/problems/releases` | `span_name`, `service`, `app`, `window` | `{releases:[{release, errors, total, error_rate, first_seen, build}]}` | read |
| `GET /api/releases` | `app`, `service?`, `window`, `limit` | `{releases:[{release, requests, errors, users_affected, p50, p95, p99, first_seen, last_seen}]}` | read |
| `GET /api/service-map` | `app?`, `service?`, `window`, `bindings?` (`1` adds Cloudflare binding nodes), `limit?` (default 100, max 500), `cf=deployment_environment:<env>?` (the only column filter the map applies) | `{edges:[{from_service, to_service, to_kind, calls, errors, p95, last_seen}], truncated}` (`to_kind` is `service` or the binding type, e.g. `d1`, `kv`, `r2`; `truncated` is true when more edges existed than `limit`; edges are the busiest by calls, and with `bindings=1` service edges are kept ahead of binding edges) | read |
| `GET /api/cloudflare/d1/statements` | `app?`, `service?`, `window` (1h), `from?`, `to?`, `limit` (1–1000, default 100; `truncated` is true when more rows existed), `cf=deployment_environment:<env>?` (narrows the span-derived rows to one environment; connector figures are account-wide and ignore it) | `{rows:[{fingerprint, statement, binding_name, calls, errors, p50_ms, p95_ms, rows_read, rows_written, primary_calls, replica_calls}], truncated}` | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/storage-ops` | same | `{rows:[{binding_type, binding_name, operation, calls, errors, p95_ms}], truncated}` (KV and R2 only) | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/queues` | same | `{rows:[{source, destination, metric, value}], truncated}` (rows are cut on queue boundaries, so a queue is never half shown; `source` is `spans` or `connector`; native sends without a destination appear as `(unattributed)`; connector rows are keyed by queue ID: `cloudflare.queues.backlog` and `.backlog_bytes` are the latest reading in the range, `.lag_ms`, `.retries` and `.consumer_concurrency` are averages, the rest are sums) | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/platform` | same (`cf` does not apply: the figures are account-wide, not per environment) | `{rows:[{product, key, detail, metric, value}], truncated}` (Cloudflare connector figures for `durable_objects`, `d1`, `kv`, `r2`, `workers_ai`, `ai_gateway`, `workflows` and `hyperdrive`; `key` is the namespace, database, bucket, model, gateway, workflow or config, `detail` the operation, provider or similar sub-key (empty when none); counters are summed over the range, `cloudflare.durable_objects.active_websockets` is the peak, other gauges are averaged; rows are cut on product, key and detail boundaries, so an item is never half shown; a metric Cloudflare did not report is absent, never 0) | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/durable-objects` | same | `{rows:[{durable_object_id, requests, wall_ms, storage_ops, sql_rows_read, alarm_errors, websocket_events}], truncated}` | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/runtime` | same | `{rows:[{invocations, cpu_ms_quantiles:[p50,p99], outcomes:{<outcome>:count}, top_colos, subrequests}]}` (root spans only; one row; `cpu_ms_quantiles` ignore invocations that recorded no CPU time and are `null` when none did; an invocation with no recorded outcome appears under the empty key) | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/runs` | same | `{rows:[{kind, service, name, started, outcome, duration_ms, retries}], truncated, missed:[{service, name, after, before, expected_interval_ms, label}]}` (cron runs and Workflow binding calls such as `create`, which are not Workflow executions, newest first; `retries` is always 0 today; `missed` is inferred from each cron's own cadence, so it is only ever "possibly missed") | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/cloudflare/coverage` | same | `{report:{handlers, bindings, truncated, blindSpots}, rows:[{source, key, n}]}` (`truncated` is true when the 1000-row cap was hit) (anything Heystack has not seen is `"unknown"`, never `"ok"`; reads span attributes over the whole window, so prefer short windows; `limit` is ignored and blind spots are withheld if the result hits the 1000-row cap) | read; read keys allowed (app-scoped keys are forced to their app) |
| `GET /api/issue-states` | `app` | `{states:[{kind, fingerprint, status, note, assignee, updated_at, updated_by}]}` | read |
| `POST /api/issue-states` | `{app, fingerprint, kind: "exception" \| "problem" \| "crash", status: "open" \| "resolved" \| "ignored", note?, assignee?}` | `{ok:true}` | write |

### Home & Issues

| Method & path | Params | Returns | Access |
|---|---|---|---|
| `GET /api/overview` | `app?`, `window` (1h\|24h\|7d; others round up; default 24h), `env?` (echoed as `env_applied:false`), `refresh=1` (people only; at most once per 2 min per workspace; admins may use it to load while paused), `limit?` (1–50, technical lists only) | Home dossier `{window, computed_at, stale, refresh_available_at, headline, journeys, kpis, ai_spend, safety, attention (top 5), releases, series, apps, technical}` — served from a shared snapshot (≤10 min old, 30 min for 7d). `ai_spend` is `null` when no AI call was seen in the window, otherwise `{usd, prior_usd, prior_estimated, monthly_forecast_usd, capped, unpriced_models, by_model}`, priced by the same rule as `/api/ai/overview`: `usd` and `monthly_forecast_usd` are `null` when calls were made but no model could be priced (never `0`; no calls at all is `0`); `prior_usd` is the priced total for the previous window and is `null` when none of it is priced or no model had calls then; `prior_estimated` is true when any of that previous total is an estimate or a minimum rather than a billed amount; `capped` is true when the model list was cut at 200 rows, so the totals are lower bounds; `unpriced_models` lists models with no price or only partly reported cost; `by_model` rows are `{provider, model, calls, usd, cost_basis}` (`cost_basis` as on `/api/ai/overview`). Groups with no calls in a window are ignored for that window. `503 analytics_paused {can_force}` when paused to stay within limits; `502` when the analytics store failed recently (retried after 2 min) | read |
| `GET /api/inbox` | `app?`, `window`/`from`/`to`, `status` (`open` default \| `resolved` \| `ignored` \| `all`), `source` (comma list: `error`, `failing_operation`, `crash`, `journey`, `alert`, `bug_report`, `security`, `performance`, `usage_drop`, `ai_regression`), `severity` (comma list), `q?` (up to 200 chars), `snoozed=1`, `limit` (0–200, default 100), `refresh=1`, `cached=1` (cached snapshot only, never computes; `{cached:false}` when nothing is cached) | `{window, computed_at, stale, refresh_available_at, issues, counts, sources_status}` — the same shared snapshot as `/api/overview`; `counts` ignore filters; errors map as for `/api/overview` | read |
| `GET /api/inbox/:issueKey` | `app?`, `window`/`from`/`to`, `refresh=1` | `IssueStory {state, issue, highlighted_member, what_happened, likely_cause (always "suggested" or "unknown"), fix, confirm (verified only when App Care marked the incident recovered with a recovery check newer than its last failure), activity}`; `404` for an unknown key, another app or another tenant; `state: "not_found_in_window"` for an analytics issue outside the window; the likely cause degrades to `unknown` instead of failing when the one release lookup is unavailable | read |
| `POST /api/inbox/:issueKey/triage` | `{status?, assignee?, snoozed_until? (epoch ms or ISO, up to 90 days ahead, null clears), members?}` (`members` up to 20 more issue keys) | `{results:[{issue_key, field, ok, reason?}]}` | write |
| `GET /api/setup-check` | `app` (required), `fresh=1` (take an uncached telemetry sample; honoured at most once per app per 15 s and only while the analytics budget is normal) | `{app_id, ok, checked_at, telemetry: live\|paused\|unavailable, signals, items, verify}` — the setup checklist behind Settings › App › Overview, the Connect page and `heystack_verify_setup`. `signals` lists the kinds of data received in the last 24 hours, each `{kind: trace\|log\|event\|replay\|crash\|metric, count, last_seen}`; it is `null` when `telemetry` is not `live`. `items` are `{id, status (done\|missing\|warn\|unknown\|unavailable), required, detail, fix?, settings:{scope, slug}}` in a fixed order; `ok` is true when the three required items (`telemetry_arriving`, `ingest_key`, `sampling`) are done. `telemetry_arriving` is done when any kind has arrived. `ai_safety_policy` is `missing` with the detail "Not protected: this app has no policy of its own" for an app that has only the organisation minimum, and `warn` with "Not protected yet: this app's policy has no published version." (fix "Publish this app's policy.") when the app's own policy is only a draft, whether or not the organisation minimum is published. When the app's own policy has a published active version with no signature (the guard never serves it) it is `missing` with "Not protected: this app's published policy version is not signed." (fix "Publish a new version of this app's policy."). With no policy or draft of its own and no organisation minimum it is `missing` with "No AI safety policy". Configuration comes from the workspace database; telemetry from at most one bounded sample, cached 60 s. When paused to stay within the daily limit it takes no sample: `telemetry: "paused"`, `verify: null` and the telemetry items are `unknown`, never `missing`. An analytics failure gives `telemetry: "unavailable"` (still `200`). It reads an already-cached overview snapshot for signal presence but never computes one. `400 {error:"app required"}`, `404` for an unknown app; an app-scoped read key is forced onto its own app | read (read keys allowed) |

**Security issues.** Every `security` issue carries a `subtype`: `repeat_offender`, `block_spike`, `novel_attack` (a rule that matched at least 5 times in the window and never in the window before, under a policy version that was already running then), `tracked` (a security decision someone chose to track as an issue; raw id `tracked|sec_<hex>`; the `|` is not a safe key character, so the whole raw id is base64url-encoded and the key is `security:<app>:~<base64url("tracked|sec_<hex>")>`; `severity` is `high` for the `missed_control` and `review_failure` categories and `medium` otherwise; listed for every caller, since it holds only allow-listed correlation metadata, at most 50 per app, newest first), or one of the GitHub finding subtypes `dependency`, `code_scanning`, `secret_scanning`. `GET /api/inbox/:issueKey` for a security issue adds a `security` lane to the story: `{kind:"runtime", subtype, user_id, profile, rule, events, prior}` for the runtime subtypes, `{kind:"tracked", fingerprint, category, rule, surface, profile, deployment_environment, verification, source_count}` for a tracked group (`verification` is `not_verified`, `historical_verification` or `operator_verified_current_policy`), or `{kind:"finding", source, severity, summary, html_url, path, start_line, opened_at, scanned_at, stale}` for a finding (`html_url` is null unless it is a plain `https://github.com` link; `stale` is true when the last successful scan is more than 7 days old or there was none, which means the finding's state is unknown). A finding that a later scan no longer lists answers `confirm: {state:"unknown", reason:"scan_cleared", verified_at}` (it may have been fixed or dismissed on GitHub, so it is never reported as confirmed fixed); an open one is `unknown / no_independent_check`. A tracked group answers `confirm: {state:"verified" | "not_verified", reason:"security_verification", verified_at}`: it is `verified`, and its `status` is `resolved`, only while a journey verification exists that was made against the environment's current policy activation; publishing or rolling back **any** policy in that environment (any app, any profile, the organisation minimum) makes every earlier verification there historical, and every tracked group in the environment is `open` again until it is verified again. Activations are per organisation and environment, not per policy. Saving `status:"resolved"` on a finding answers `status_owned_by_source` (only a scan closes it); `ignored` and re-opening work. An admin can still open a finding that closed before the list window by its key. Only the first 10 open findings per source (per app) are listed; more may be open on GitHub.

**Usage and AI issues.** Two sources are decided from stored daily counters, never from an analytics read:

- `usage_drop`: a [key event](#key-events) whose count for yesterday (a complete UTC day) is at least 40% below the same weekday averaged over the previous 4 weeks (complete days only, so usage concentrated in part of the day compares like with like; today's partial count is never prorated), with a baseline of at least 50 (below that the state is unknown and no issue opens). The likely cause is a release first seen inside the window.
- `ai_regression` ("AI answers got worse"): an app's AI failure or flagged rate rose against the previous period for one model, prompt version, feature or release (key `ai_regression:<app>:<encoded dim|value>`). The issue brief names the change that lines up with it as the likely cause. See [AI health](https://heystack.dev/docs/ai-health).

App Care checks and journeys (synthetic traffic) never count toward either.

**GitHub findings are admin-only.** They appear in the list, counts and story only for a signed-in organization admin holding the `admin` scope, and only while App Care is enabled. For everyone else, including read keys and read-only tokens, they are absent from the list and counts, and `GET /api/inbox/:issueKey` and `POST /api/inbox/:issueKey/triage` answer `404` for a finding key (a finding key in `members` also makes the whole triage request `404`, before anything is written). `sources_status.security` is `ok` when findings were loaded or a guard policy is set up.

**Uninstrumented AI calls in the setup check.** `GET /api/setup-check`'s `genai_enrichment` row becomes `warn` when the app made outbound calls to a known AI provider in the last 7 days that carried no AI details (a call nested under an instrumented model call never counts). The row's detail names the provider ("Your app is calling OpenAI but Heystack isn't receiving AI details"; several providers are joined, an unknown one falls back to its host) and its `fix` links `https://heystack.dev/docs/ai-frameworks`. This is one extra D1 read with no analytics, applies even while the telemetry sample is paused, and then shows the AI safety row. `SetupConfigFacts.ai_uninstrumented` (`[{provider, host, last_seen}]`) carries the detail.

**Home's AI answers tile.** `GET /api/overview` gains `ai_answers` (last 24 h: answers, failure rate, status; `null` when the app sent no AI answers), read from D1 with no analytics read.

Journey status is owned by App Care, so a status change on a journey issue answers `status_owned_by_source`; it can still be assigned or snoozed. Security issues have one closure rule too: a runtime signal (`repeat_offender`, `block_spike`, `novel_attack`) leaves the inbox when it stops and a tracked group closes only by a current-policy verification, so `status:"resolved"` or `"ignored"` on either answers `status_owned_by_source` (`status:"open"` is accepted and writes nothing: no overlay row and no activity entry); they can still be assigned or snoozed. Assignments made here live in the new triage overlay, not the earlier issue-state assignee. Other `reason` values are `invalid_key`, `wrong_app` and `not_found` (a tracked key that names no tracked group of that app is `not_found`).

The Home dossier is built from a shared snapshot, so repeated loads (and several people looking at the same app) do not each trigger fresh reads. `computed_at` tells you when the numbers were last calculated and `stale` is `true` when a newer calculation is overdue; `refresh_available_at` is the earliest time a person may force a recalculation with `refresh=1`. Read keys share the same snapshot as everyone else and cannot force a refresh.

### AI & Safety

| Method & path | Params | Returns | Access |
|---|---|---|---|
| `GET /api/ai/overview` | `app?`, `window` (1h\|24h\|7d; others round up; default 24h), `refresh=1` (people only; read keys never force) | `{window, computed_at, stale, refresh_available_at, app, ai, safety}`. `ai` is `{state:"no_data"}` or `{state:"ok", calls, prior_calls, errors, error_rate, input_tokens, output_tokens, usd, prior_usd, prior_estimated, monthly_forecast_usd, unpriced_models, p50_ms, p95_ms, agent_runs, tool_calls, by_model, models_capped, series, cheapest_wins}`. Each model's cost is `reported` (from your gateway), `estimated` (from a price list), `mixed` (some calls reported and the rest estimated), `partial` (some calls reported and the rest have no known price, so the amount is a lower bound) or `unpriced` (never guessed); `usd` is `null` when nothing could be priced. A model is priced from the list only when its name matches a known model exactly (a dated copy counts as the same model) or is a reviewed alias of one (for example `gemini-1.5-pro-002`, `gpt-4-turbo-preview`, `claude-sonnet-4-0`, `model@YYYYMMDD`); preview, realtime, audio and small-size variants are unpriced until they have their own price. Home's AI spend uses the same rule, so the two pages agree: `usd`, `prior_usd` and `monthly_forecast_usd` are `null` when calls were made but no model could be priced (never `0`), `prior_usd` is the priced total for the previous window (`null` when none of it is priced), and `prior_estimated` is true when any of that previous total is an estimate or a minimum rather than a billed amount. On `/api/overview`, `ai_spend` has the same fields plus `capped`, true when the model list was cut at 200 rows so the totals are lower bounds. `models_capped` means `by_model` and `usd` cover only the busiest models. `cheapest_wins` (at most 3) are `cheaper_model`, `failed_calls` or `unpriced_model` suggestions. `safety` is `not_set_up`, `awaiting_data` or `active {total, blocked, blocked_prior, flagged, reviewed, would_have_blocked, unchecked, unchecked_blocked, by_action, top_rules, repeat_offenders, series, capped, rules_capped, offenders_capped}`. With repeat offenders, a person asking also gets `profiles`, `profiles_by_app` (when they span apps) and `names_shown` for them (one profile read at most; skipped at the critical budget) | read |
| `GET /api/security/summary` | `app?`, `window`, `refresh=1` | `{window, computed_at, stale, refresh_available_at, safety}` from the same snapshot as `/api/ai/overview` (one analytics request serves both) | read |
| `GET /api/ai/conversations` | `app?`, `window` (`15m`, `1h`, `6h`, `24h`, `7d`, `30d`; others `400 bad_window`; default `24h`), `from`/`to` (unparseable is `400 bad_range`), `model`, `user`, `session` (each 1-256 characters, longer is `400 {error:"bad_filter", field}`), `errors=1`, `limit` (clamped to 1-100, default 50) | `{ conversations, truncated, profiles, names_shown }` (plus `profiles`, `profiles_by_app` (when the page spans apps) and `names_shown` for the people listed (one profile read at most; none for a read key or with names off; email for admins only)): one row per trace of AI calls (`trace_id`, `app_id`, `started_at`, `session_id`, `user_id`, `calls`, `models`, `input_tokens`, `output_tokens`, `reported_usd`, `usd`, `cost_basis`, `estimated_calls`, `unpriced_calls`, `errors`, `tool_calls`, `duration_ms`, `has_content`), newest first; `usd` prices each call the way `/api/ai/routes` does (the reported cost, else an estimate from public prices) and is null when no call could be priced, `cost_basis` is `reported`, `estimated`, `unpriced` or `mixed`, and the two counts say how many calls were estimated or had no price; `truncated` is true when more exist than `limit`. `user`, `session` and the row's `user_id`/`session_id` come from the trace's request span, so they work for SDK data; every filter selects whole conversations. Never contains prompt or completion text. Agent wrapper spans are not counted as calls, so totals match `/api/ai/overview`. Cached for 5 minutes. Errors: `404` unknown app, `503 analytics_paused` at the critical budget (admins may retry with `force=1`), `413 too_broad` past a scan, time or memory cap (pick a shorter window) | read |
| `GET /api/ai/conversations/{trace_id}` | `app?`, `window` (default `7d`; `400 bad_window`), or an explicit `from` and `to` (ISO-8601 instants with `from` before `to`, at most 7 days apart, not older than 30 days (how long raw data is kept) and not ending more than 2 days ahead; anything else, including a value that does not parse, is `400 bad_window`; they take the place of `window`); `trace_id` is 32 hex characters (else `400 bad_trace_id`) | `{ transcript, profiles, names_shown }`, or `{ transcript: null }` when the trace has no AI calls in the window; `profiles` names the transcript's person when the app shows names (one profile read at most). A transcript has per-call metadata (up to 200 spans, `spans_truncated`) and, only when the app's SDK has `captureContent` on, the prompt and completion of the first 12 calls that have text, each cut at 8,000 characters (`content_truncated`, `more_content_not_shown`). Treat that text as untrusted data. People only: a read key gets `403 read_key_not_allowed`. Never cached. Errors: `404` unknown app, `503 analytics_paused`, `413 too_broad` | read (people) |
| `GET /api/ai/routes` | `app?`, `window` (`400 bad_window`), `from`/`to` (`400 bad_range`) | `{ routes, capped }`: up to 50 routes by spend (`route`, `calls`, `errors`, `input_tokens`, `output_tokens`, `usd`, `cost_basis` of `reported`, `estimated`, `unpriced`, `mixed` or `partial`); an empty `route` means no route was recorded. `capped` is true when routes or (route, model) groups were left out (the groups with the most reported spend, then the most tokens, are kept), so treat the totals as lower bounds. A scan past the read caps is never cut silently: it is `413 too_broad`. Other errors: `404` unknown app, `503 analytics_paused` at the critical budget. Cached for 5 minutes | read |

Both routes read one shared snapshot (at most 10 minutes old, 30 for 7d), so repeated loads do not each trigger fresh reads; errors map as for `/api/overview` (`503 analytics_paused {can_force}`, `502`). **What the safety numbers mean.** `blocked` counts only decisions that were enforced; matches from a policy in shadow mode are counted separately as `would_have_blocked` (not enforced). `by_action` follows the same rule: its `n` and `prior` are enforced decisions only, and `shadow` is the not-enforced count for that action. Home's "blocked" number uses the same enforced-only rule, so the two pages agree. `reviewed` counts model reviews that finished. A decision whose safety check could not finish (`error`) or whose content was not evaluated is included in `total` and in `unchecked`, never in `blocked` or `flagged`; `unchecked_blocked` is the part of those that stopped a request anyway (a failed check that blocked or held it), shown as "Blocked because a safety check couldn't finish". Every count uses each decision's latest record, so a decision that was first checked by rules and later reviewed by a model is counted once, as its final outcome. **Repeat offenders** (here and in the inbox's `repeat_offender` issues) are people with at least 3 violations in the window, where a violation is a decision that blocked or quarantined because of what the person themselves sent (typed input, their transcribed speech or a batch they submitted; never retrieved documents, tool results, context, model output or content from an untrusted source) under your secrets, PII, prompt-injection or harmful-content rules, or the model reviewer), whether it was enforced or only ran in shadow mode (it describes what the person did, which is useful before you enforce). Blocks that come from your own limits are not the person's doing and never count: spend or request budgets, oversized input, tool permissions, voice-rights flags and content that could not be inspected. A decision whose block came from a budget while a content rule only redacted is not a violation either. Decisions from a failed check (`error`) or with content that was not evaluated are unknown, never violations. "Blocked" stays enforced-only, so a repeat offender can have more violations than blocks. Because decisions from a failed check are left out of rule matches and repeat-offender counts, `top_rules` and `repeat_offenders` can undercount while checks are failing. Per-model latency (`p50_ms`, `p95_ms`) is computed across all apps in the scope. `capped: true` means the list of decision groups hit its limit, so every count is a lower bound; `rules_capped` and `offenders_capped` mean `top_rules` or `repeat_offenders` may omit entries. GitHub findings are not part of these routes. **Where the definitions differ from the guard.** The repeat-offender definition above is the dashboards'. The guard's own per-user account actions use the same rule list but do not require a user-authored surface or a trusted source, so for example a model review of output text can count toward an account action while it is not counted as the person's violation here.

**Read keys on the AI & Safety and People routes.** They follow the rules in [Read keys](#read-keys-hs_read_): `window=30d` is `400` with the read-key message, a `from`/`to` range is limited to 7 days wide (any 7-day range inside retention is allowed, not only the latest), an app-scoped key is pinned to its app, and `/api/ai/conversations/{trace_id}` answers `403 read_key_not_allowed`. The session story's replay summary (`replay`) is looked up over the 30-day replay retention for every credential, like `GET /api/replays/for-session`, so a read key can see replay metadata for a visit older than 7 days.

### AI health

The counters behind Health, the Home tile, the AI alerts and the AI regression issue are written as AI calls arrive (switch `DERIVE_AI_HEALTH_ENABLED`, ships `"true"`). The three text checks (declined wording, invalid JSON, user asked again) run only while `AI_HEURISTICS` is `"true"` (it ships `"true"`); with it off those counts are 0. See [AI health](https://heystack.dev/docs/ai-health).

| Method & path | Params / body | Returns | Access |
| --- | --- | --- | --- |
| `GET /api/ai/health` | `app`, `window` = `1h` `6h` `24h` (default) `7d` `30d`, else `400 bad_window`; unknown or other-tenant app `404` | `AiHealthReport`: `status` (`working` / `getting_worse` / `failing_for_some` / `unknown`; unknown below `min_calls` = 30), `calls`, `failed_calls`, `flagged_calls`, `failure_rate` / `flagged_rate` (0–1 or null), `previous`, `rows[]` (`failed`, `cut_short`, `declined`, `empty`, `marked_bad`, `invalid_json`, `user_repeated`, each with `count`, `rate`, `previous_rate`, `trend`), `cost_usd` (null when nothing could be priced) + `unpriced_calls`, `ttft_ms_avg`, `duration_ms_avg`, `series[]`, `bucket` (`hour` ≤ 24h, else `day`), `markers[]` (new model / prompt / release), `by` (top values per dimension), `tools[]`. D1 counters only, never analytics; not budget-gated | read; read keys allowed (an app-scoped key is pinned to its app) |
| `GET /api/ai/health/drilldown` | `group` ∈ `provider model operation tool_name release feature prompt_version gateway consumer` (default `model`), else `400 bad_group`; filters use the same names; `app`, `window` as above | `{group, window, rows[], capped}` (≤ 200 rows; `reported_cost_usd` null when none reported; time to first token null when not recorded). **On demand**: one read of the AI health rollup, 5-minute reuse, `503 analytics_paused` at the critical budget, `413 too_broad` on a cap | read; read keys allowed (pinned) |
| `POST /api/ai/conversations/:traceId/mark` | `{app, verdict: "bad"\|"good", span_id?, reason?, comment?}`; `comment` ≤ 500 chars, `reason` `[a-z0-9_.-]{1,64}` | `202 {ok:true}`. Appends one team rating (`scorer = team`, `scorer_id` = the member); a newer mark by the same member on the same target replaces it. Bad trace id `400 bad_trace_id`; bad body or an app outside the caller's org `400 {error:"invalid", field}`. Audit label `ai.answer.mark` | write; read keys `403 read_key_not_allowed`; read-only viewers `403 scope_required` |
| `GET /api/ai/conversations/export` | the list's filters (`app`, `window`/`from`/`to`, `model`, `user`, `session`, `errors=1`, `needs_look=1`), `limit` ≤ 200 (default 200) | `application/x-ndjson`, `cache-control: no-store`, attachment `conversations-YYYY-MM-DD.jsonl`; one JSON object per conversation (trace) with its steps (≤ 200), signals and words (≤ 12 steps with words, each field ≤ 4,000 chars). **On demand** (one read); never cached | read; read keys `403 read_key_not_allowed` |

Changes to the conversation routes:

- `GET /api/ai/conversations` returns **threads**: traces grouped by `ai_conversation_id` (else the trace is its own thread), newest activity first. New per-row fields: `thread_id`, `conversation_id`; `turns` (trace ids, newest first, ≤ 50), `turn_count`, `first_started_at`; `cut_short`, `filtered`, `flagged`, `cached_tokens`, `reasoning_tokens`; `rated_good`, `rated_bad` (latest rating per rater), `needs_look`. `trace_id` is the newest turn, and `limit` counts threads. New filter `needs_look=1`: an error, a cut-short or filtered answer, a signal, or a bad rating.
- `GET /api/ai/conversations/:traceId` takes an optional `conversation=` (≤ 256 chars) to read every turn of that thread. Spans gain `trace_id`, `finish_class`, `signals[]` (`empty`, `declined`, `invalid_json`, `user_repeated`, `loop`), `cached_tokens`, `reasoning_tokens` and `feature`. The transcript gains `conversation_id` and `scores[]` (`scorer`, `verdict`, `score`, `reason_code`, `comment`, `trace_id`, `span_id`, `at`; ≤ 50). It is still people-only and never cached.
- **Gateway calls and wrapper steps.** Gateway calls carry their gateway (`litellm`, `cloudflare_ai_gateway`, `vercel_ai_gateway`) and consumer. Wrapper steps (agent runs, agent steps, tool calls, Mastra model generations) are steps, never extra calls, and a model call reported twice (an inner HTTP record under an AI SDK call, LlamaIndex's nested LLM records, a same-upload duplicate from two Anthropic instrumentations) is counted once. Normalisation is behind `AI_NORMALIZE` (on only when exactly `"true"`, its ship value); with any other value, rows are stored exactly as received.

### AI spend

Every route here reads and writes D1 only: no analytics read, no budget gate, never paused. Money on the wire is **USD as a number** (at most 6 decimals); days are UTC `YYYY-MM-DD`; errors are `{error, field?}`. "admin" = the organisation admin role and the `admin` scope. Reads need the `read` scope; read keys may read spend and budgets (an app-scoped key is always pinned to its own app, and an explicit `from`/`to` longer than 7 days is `400` for any read key) but get `403 read_key_not_allowed` on every `/api/ai-spend/pools*` route, and the budgets a key reads leave out pool budgets and budgets set by another organisation. A budget another organisation set on a shared-gateway label is listed for people with an empty `app_id`.

Spend comes from the daily spend counters written as AI calls arrive (switch `DERIVE_AI_SPEND_ENABLED`, ships `"true"`): model calls only (no delegated, inferred or synthetic calls). Cost is the reported cost when the call carries one, else an estimate from the price table; calls with neither are counted as `unpriced_calls`, never priced.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/ai-spend` | `app?` (omit = organisation-wide), `from?` (default: first day of the current UTC month), `to?` (default: today), `group?` = `provider` (default) \| `model` \| `gateway` \| `consumer` \| `app`. Span at most 400 days | `{app_id, from, to, group, as_of, totals:{calls, input_tokens, output_tokens, cost_reported_usd, cost_estimated_usd, cost_usd, unpriced_calls}, rows:[{key, label, calls, cost_reported_usd, cost_estimated_usd, cost_usd, unpriced_calls, input_tokens, output_tokens}], daily:[{day, cost_usd, calls}], month:{month, cost_usd, forecast_usd, days_with_data}, budgets: SpendLimitView[]}`. `rows`: at most 200, by `cost_usd` descending; `group=app` labels rows with the app name; an empty gateway is labelled `Direct`, an empty consumer `Unlabelled`. `daily` lists every day of the range (zeros filled). `forecast_usd` is a straight line from the month's first day with spend through today, projected to the month end; `null` with fewer than 3 days with spend. `budgets` are the ones that concern `app` (all the organisation's when omitted). `400 {error:"invalid", field:"from"\|"to"\|"group"}`, `400 {error:"invalid_range"}`, `404` for an app of another organisation | read |
| `GET /api/ai-spend/budgets` | `app?` | `{limits: SpendLimitView[]}`: with `app`, the budgets that concern it (organisation-wide ones, its own, provider/model/user budgets with no app, consumer budgets on it or mapped to it, the pool budgets of pools it is an accepted member of, and the owner's budget on its shared-gateway label); without, every budget the organisation owns. Disabled budgets are listed | read |
| `POST /api/ai-spend/budgets` | `{scope, period:"day"\|"month", limit_usd (> 0, ≤ 10,000,000), app_id?, scope_value? (≤ 200), thresholds? (1–5 integers 1..100; default [50, 80, 100]), enforce? (default false), pool_id?}`. `org`: no `app_id`. `app`: `app_id`. `provider` \| `model` \| `consumer`: `scope_value`, `app_id` optional. `user`: `app_id` optional (organisation-wide = every app). `pool`: `pool_id` of a pool this organisation owns, no `app_id` | `201 {limit: SpendLimitView}`. `400 {error:"invalid", field}`; `409 {error:"budget_exists", id}` (same app, scope, value and period); `409 too_many_budgets` (100 per organisation) | admin |
| `PATCH /api/ai-spend/budgets/:id` | any of `{limit_usd, thresholds, enforce, enabled, period}` | `{limit}`. Changing the amount, thresholds or period clears the budget's fired thresholds for the period, so they are checked afresh. `409 {error:"budget_exists", id}` when another budget already has the same app, scope, value and the new period | admin |
| `DELETE /api/ai-spend/budgets/:id` | — | `{deleted: true}` (its alert state goes too) | admin |
| `GET /api/ai-spend/pools` | — | `{owned: PoolSummary[], memberships: Membership[]}`. `PoolSummary = {id, name, created_at, members, accepted, month_cost_usd, limit: SpendLimitView \| null}` (`members` counts invited and accepted). `Membership = {pool_id, pool_name, owner_org_id, app_id, state:"invited"\|"accepted"\|"removed", gateway_consumer}`: this organisation's own memberships, every state: accepted first, then invitations newest pool first, then removed (at most 200) | read (people only) |
| `POST /api/ai-spend/pools` | `{name}` (1–80 characters) | `201 {pool:{id, name, owner_org_id, created_at}}`; `409 too_many_pools` (20 per organisation) | admin |
| `GET /api/ai-spend/pools/:id` | `app?` (a member organisation with several apps in the pool picks its share) | For the owner: `{pool:{id, name, owner_org_id}, viewer:"owner", month, total_usd, forecast_usd, limit, by_provider:[{provider, cost_usd}], members:[{org_id, app_id, state, gateway_consumer, cost_usd, by_provider}]}`. For an organisation with an **accepted** membership: the same without `members` and without the pool-wide `by_provider` (with its own share it would give another member's spend per provider), plus `own:{app_id, cost_usd, by_provider}`: a member never receives another member's figures. Anyone else (including invited and removed members) gets `404` | read (people only) |
| `POST /api/ai-spend/pools/:id/members` | `{org_id, app_id, gateway_consumer? (≤ 200)}` | `201 {member:{pool_id, org_id, app_id, state, gateway_consumer, accepted_by, accepted_at}}` with state `invited`. Inviting one of the owner's own apps records the acceptance at once (`400 invalid app_id` when it is not one of its apps). `409 already_member`; `409 too_many_members` (100 per pool); `409 too_many_invitations` (at most 5 open invitations from one organisation to another, across its pools); `404` for a pool this organisation does not own | admin of the owning organisation |
| `POST /api/ai-spend/pools/:id/accept` | `{app_id}` | `{member}` state `accepted` (`accepted_by`, `accepted_at`). Always this organisation's own invitation: `404` when there is none (or it was removed) or the app is not one of its apps. Idempotent | admin of the invited organisation |
| `POST /api/ai-spend/pools/:id/decline` | `{app_id}` | `{member}` state `removed` | admin of the invited organisation |
| `DELETE /api/ai-spend/pools/:id/members/:orgId/:appId` | — | `{member}` state `removed`. The owner removes anyone; a member organisation removes only its own row; otherwise `404` | admin |

`SpendLimitView = {id, app_id ("" = organisation-wide), scope:"org"|"app"|"provider"|"model"|"consumer"|"user"|"pool", scope_value, period, limit_usd, thresholds, enforce, enabled, pool_id, used_usd, state:"ok"|"warn"|"exceeded", period_start, resets_at, forecast_exceeds_on, created_at, updated_at}`. `state` is `warn` from 80% and `exceeded` from 100%. For `user` budgets `used_usd` is the **highest single user's** spend in the period (no user id is returned). `forecast_exceeds_on` is the day the straight line reaches the limit when that is before the period ends (null with fewer than 3 days with spend, for user budgets and once exceeded).

- **Pool attribution.** A member counts only once an admin of its organisation accepts. Without `gateway_consumer` it contributes its own app's spend; with one, it contributes the pool owner's spend (any owner app) whose consumer label is that value, and its own spend is then not counted. A label only ever resolves against the owner's records. No telemetry moves between organisations; only totals are attributed. Do not add the owner's gateway app itself as an own-telemetry member next to labelled members: its records would be counted twice.
- **Budget alerts.** Checked every 5 minutes inside the organisation's alert task (organisations with a budget and no alert rule are included). Each threshold notifies once per period (kind `ai_budget_threshold`: the highest new threshold, so a jump to 100% says "used up" once), plus `ai_budget_forecast` once per period when 3 or more days have spend and the straight line passes the limit before the period ends. Pool budgets notify the owning organisation; each accepted member organisation is also told when the pool reaches 100%. Notifications need `EVENT_NOTIFICATIONS_ENABLED`.
- **Enforcement is soft.** `enforce: true` makes a budget count towards `GET /v1/spend` and the guard worker's spend check (when the app's policy turns on `rules.spend_limit`; see [Guard runtime](#guard-runtime-contract-5)). Spend lags by about a minute and counts only reported or priceable cost of model calls sent with a server key (a Browser or mobile key's calls count as unpriced; one call counts at most $100): a budget guard, not a meter. Hard caps belong in the gateway (LiteLLM virtual-key budgets; see [AI gateways](https://heystack.dev/docs/ai-gateways#budgets-and-pooled-credits)).
- **Retention.** Daily spend 400 days; per-user spend (kept only for apps with a user budget, at most 50,000 users per app per day) 35 days; fired-threshold state for the current and previous period.

Audit labels: `ai_budget.create|update|delete`, `spend_pool.create`, `spend_pool.member.invite|accept|decline|remove`.

### Traces, logs & metrics

**On-demand reads.** These routes query fresh data rather than a shared snapshot, so they follow the same budget rules as the rest of the analytics reads: at the critical analytics budget they answer `503 {error:"analytics_paused", reason:"budget", can_force}` (an org admin may retry with `force=1`), and a read that hits a scan, time or memory cap, or whose answer is too large to send back, answers `413 {error:"too_broad"}` (narrow the window or add a filter); any other failure, including a dropped connection to the analytics store, is still `502 {error:"clickhouse"}`. The check runs after authentication and the read-key limits, so an unauthenticated request never learns the budget state. It covers `/api/telemetry`, `/api/telemetry/summary`, `/api/logs`, `/api/traces/{traceId}`, `/api/traces/{traceId}/events`, `/api/traces/{traceId}/resource`, `/api/traces/{traceId}/explain`, `/api/metrics`, `/api/metrics/timeseries`, `/api/metrics/exemplars`, `/api/metrics/red`, `/api/metrics/red/timeseries`, `/api/metrics/anomalies`, `/api/metrics/genai`, `/api/crashes/{signature}`, `/api/telemetry/facets`, `/api/logs/facets`, `/api/telemetry/compare`, `/api/logs/compare`, `/api/telemetry/aggregate`, `/api/explore`, `/api/service-map`, every `/api/cloudflare/*` read, `/api/replay/by-trace/{traceId}`, `/api/monitoring/{section}`, `/api/accounts`, `/api/accounts/{accountId}`, `/api/profiles`, `POST /api/apps/{id}/users/{userId}/export`, `/api/ai/health/drilldown`, `/api/ai/conversations/export`, `POST /api/key-events/suggest` and `POST /api/query/sql` (the pause is checked after the read-key refusal). The budget level is remembered for up to 15 seconds per server instance, so a pause or release can take that long to show.

Some reads are counted per action rather than per page:

- **People pages.** `GET /api/users`, `/api/users/{userId}`, `/api/sessions` and `/api/sessions/{sessionId}` add **one** read for names (skipped for a read key, with names off, or with no ids on the page; cached 5 minutes per server instance) and one more for a name search.
- **Person export.** At most 4 reads per export, two exports per organisation per day.
- **Key-event suggestions** (`POST /api/key-events/suggest`): one read of the request rollup (top 300 method and route pairs over 7 days), cached 24 h, at most 3 per app per UTC day.
- **Key-event history count** (the backfill started by `POST /api/key-events` with `backfill`, or `POST /api/key-events/:id/backfill`): one read per run, at most 20,000 matches, at most 5 runs per organisation per UTC day, admin only. At the critical budget the run is `deferred` and waits for an admin to retry it (never retried automatically); a scan past its caps sets `failed` with the 7-day suggestion.
- **Fix baselines.** Linking a fix (by hand, or automatically when a merged GitHub pull request names the issue) runs one read of the issue's rate over the 7 days before the link; at the critical budget it is skipped and the baseline is unknown. See [Fixes and deploys](#fixes-and-deploys).

Everything else added for people, key events, AI health and AI spend (connectors, bulk profiles, erasure, key-event counts, the event catalogue, Health, budgets, pools, posture counts) reads Heystack's own records and makes no analytics read. Posture names, like people pages, cost one profile read.

| Method & path | Params | Returns | Access |
|---|---|---|---|
| `GET /api/telemetry` | `app`, filters, `window`/`from`/`to`, `sort`, `order`, `limit` | `{spans:[…]}` (one row per span, attributes as JSON strings) | read |
| `GET /api/telemetry/summary` | `app`, `window` | `{total, errors, last_seen}` | read |
| `GET /api/telemetry/facets` | `app`, `field` **or** `fields`, filters (including `cf`/`ncf`) | `{field, values:[{value, count}]}` (top 20); with `fields=a,b,c` (max 12, optional `perField` 1-20, default 10; traces accept `service_name`, `span_name`, `http_route`, `http_method`, `status_code`, `service_version`, `deployment_environment`, `cloudflare_colo`, `binding_type`, `gen_ai_provider`, `device_model`, `os_version`; logs accept `service_name`, `severity_text`, `service_version`, `event_name`, `deployment_environment`, `device_model`, `os_version`; high-cardinality fields such as `enduser_id` and `session_id` are `field=` only): `{fields:{a:[{value, count}], …}, total}` from one scan. A facet keeps your own filter on its field, so selecting a value narrows that facet to it. An invalid field is `400 {error:"invalid facet field"}` | read |
| `GET /api/telemetry/compare` | `sel` (`errors`, `slow` or `match`), `min_ms` (`slow` only, an integer string 1-600000), `sel_field` + `sel_value` (`match` only; any facet field, value 1-256 characters), `fields?` (csv, a subset of the multi-field facet list above; default all of them, minus the field that defines the selection: the matched field for `match`, `status_code` for trace `errors`, `severity_text` for log `errors`; an explicit `fields=` is used as given), `app`, filters (including `cf`/`ncf`), `window`/`from`/`to` | `{selection, fields_compared, totals:{selected, baseline}, differences:[{field, value, selected, baseline, selected_pct, baseline_pct, delta_pct}], comparable}`: one scan splits the filtered window into the selection and everything else, then ranks the values whose share differs most (`*_pct` are 0-1 shares of each side; `delta_pct = selected_pct - baseline_pct`; sorted by absolute delta, then selected count, field and value; at most 12). A value needs at least 3 rows on the side that drives the finding (selected for over-represented values, the rest for under-represented ones), a shift of less than one percentage point is not reported (an empty `differences` with `comparable:true` means nothing stands out), and a field with exactly two mirror-image values shows only the over-represented one. `comparable:false` (and no differences) when either side is empty, or, with a `reason`, when a side has fewer than 10 rows in total (`selection_too_small` for the selection, `baseline_too_small` for everything else): shares of so few rows are not reported. Values rare overall but distinctive of the selection, or of everything else, are kept. A bad selection or field is `400 {error:"bad_selection"}`; over a scan cap, or an answer too large to send back, `413 {error:"too_broad"}`; paused at the critical analytics budget `503 {error:"analytics_paused"}` (admins may `force=1`); any other failure `502 {error:"clickhouse"}`. Read keys allowed, within the 7d cap | read |
| `GET /api/telemetry/aggregate` | `app`, `groupBy` (field or `attr:<key>`), `aggSort`, filters | `{groups:[{group_value, count, errors, error_rate, p50, p95, p99}]}` | read |
| `GET /api/explore` | `source` (`traces`/`logs`), `groupBy` (1–2, csv), `metrics` (csv), `bucket?`, `app`, `q`, `window` | `{rows:[…], groupBy, metrics, bucketed}` | read |
| `GET /api/example-trace` | `app`, `service?`, `route?`, `release?`, `prefer` (`error`/`slow`) | `{trace \| null}` | read |
| `GET /api/traces/:traceId` | `app?`, `from` + `to` (optional; both ISO-8601 instants, at most 7 days apart, not older than 30 days (how long raw data is kept) and not ending more than 2 days ahead; anything else, or only one of the two, is `400 {error:"bad_window"}`; a valid range narrows the scan, otherwise the last 30 days are searched) | `{spans:[…], truncated}` in waterfall order: the trace's earliest spans, at most 5,000 of them and at most about 6 MB of span data (an estimate that counts attribute and statement text twice); `truncated` is true when the trace has more spans than were returned, for either reason. The first span is always returned. Each span also carries `enduser_id`, `session_id`, `is_error`, `exception_type`, `http_route`, `http_method` and `http_status_code`, and its `span_attributes`. A span with no user or session id of its own takes the one set on its resource (`enduser.id`, `user.id` or `heystack.user.id`; `session.id` or `heystack.session.id`). Resource attributes (service, host, process and SDK keys, the same on most spans) are not included: read one span's with `/api/traces/:traceId/resource`. `GET /api/traces/:traceId` no longer returns a `resource_attributes` field (it was never documented); use the `/resource` route below. A large trace is cut, not refused; `413 {error:"too_broad"}` is left only for an answer that still cannot be sent back, such as one span carrying megabytes of attributes. To see later spans of a cut trace, narrow `from`/`to` to the part you need | read |
| `GET /api/traces/:traceId/resource` | `span` (required, 1-128 characters; otherwise `400 {error:"bad_span"}`), `app?`, `from` + `to` (as `/api/traces/:traceId`) | `{resource_attributes}`: that span's resource attributes as JSON text, or `null` when the span isn't found in the range (or, for an app-scoped read key, belongs to another app). A read key never gets visitor address, location, request-header, user-agent or AI prompt/completion keys | read |
| `GET /api/traces/:traceId/events` | `span?`, `app?`, `version?`, `build?` (the span's release, used to find a source map when the event names none) | `{events:[{timestamp, app_id, span_id, event_name, is_exception, exception_type, exception_message, exception_stacktrace, attributes, frames?, symbolicated?}]}`; `frames` (`file, line, column, function, in_app, context?`) on the first 5 exceptions an uploaded [source map](#source-maps) resolves; a read key gets `file, line, function, in_app` only | read |
| `GET /api/traces/:traceId/explain` | — | `{configured, summary, model, ai_generated: true}`. Trace data is passed to the model as untrusted input, never as instructions. Links in the answer (including scheme-less ones like `example.com/login`) are replaced with `[link removed]`. Uses one AI credit per answer: out of credits is the standard `429 {error:"quota_exceeded", signal:"ai_credits", …}` with `Retry-After`; `403 {reason:"ai_processing_disabled"}` when your organisation turned AI processing off | read (people) |
| `GET /api/logs` | `app`, `q`, `service`, `severity`, `trace`, `window`, `limit`, `sort` | `{logs:[…]}` | read |
| `GET /api/logs/facets` | `app`, `field` **or** `fields`, filters (including `cf`/`ncf`) | `{field, values}`, or `{fields, total}` with `fields=` as above | read |
| `GET /api/logs/compare` | as `/api/telemetry/compare`, for logs: `sel=errors` (severity ERROR and above) or `match`; `slow` is not available (400); `trace` scopes to one trace; fields come from the logs multi-field list | same shape and errors (400, 413, 502, 503) | read |
| `GET /api/metrics` | `app`, `window` | `{metrics:[{metric_name, metric_type, count, avg_value, max_value, last_seen}]}` | read |
| `GET /api/metrics/exemplars` | `app`, `metric`, `window`, `limit` | `{exemplars:[{timestamp, metric, value, trace_id, span_id}]}` | read |
| `GET /api/metrics/genai` | `app`, `window` (24h) | `{models:[{model, provider, calls, input_tokens, output_tokens, errors, error_rate, p50, p95, cost_usd, agent_runs, tool_calls}]}` (`cost_usd` = reported cost; `agent_runs` / `tool_calls` count agent and tool spans, which are excluded from `calls` and tokens so nothing is double-counted). During the 30-day cutover window, buckets before the cutover come from the older rollup, which counted agent-wrapper and delegated spans (tokens may read higher) and has no `cost_usd`, `agent_runs` or `tool_calls` (read as 0) | read |
| `GET /api/telemetry/session-signals` | `app`, `session`, `window` (7d) | `{signals:[{trace_id, span_name, status_code, duration_ms, exception_type, …}]}` | read |

### Sessions, crashes & bug reports

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/replay/sessions` | `app`, `window` (`15m`/`1h`/`24h`/`7d`/`30d`), `limit` (≤500) | `{sessions:[{session_id, user_id, started_at, duration_ms, click_count, error_count, entry_url, browser, device, trace_ids}]}` | read |
| `GET /api/replay/sessions/:id` | `app` | `{chunks:[{chunk_seq, timestamp, event_count, has_snapshot, start_url, click_count, error_count}]}` | read |
| `GET /api/replay/sessions/:id/chunks/:seq` | `app` | raw replay events for that chunk | read |
| `GET /api/replay/by-trace/:traceId` | `app` | `{session_id \| null}` | read |
| `GET /api/replays/for-session` | `app`, `session` | `{session \| null}` | read |
| `GET /api/crashes` | `app`, `window`, `limit` | `{crashes:[{signature, exception_type, exception_message, count, devices, sessions, first_seen, last_seen, releases}]}` | read |
| `GET /api/crashes/:signature` | `app`, `limit` | `{group, instances, symbolicated, profiles, profiles_by_app?, names_shown}`; `profiles` names the people behind the instances when the app shows names (one profile read at most; none for a read key); `profiles_by_app` is present when the instances span several apps, so an id is named only by its own app | read |
| `GET /api/bug-reports/:id` | none | `{report:{id, app_id, message, session_id, trace_id, url, release, build, recent_errors, status, created_at}}` for one report in your organisation (an app-scoped read key sees only its own app). It leaves out the reporter's `email` and the free-form `context`. `404` when there is no such report | read |
| `GET /api/bug-reports` | `app`, `status?` (`new`/`triaged`/`resolved`), `limit` | `{reports:[{id, message, email, url, release, build, session_id, trace_id, recent_errors, status, created_at}]}` | read |
| `PATCH /api/bug-reports/:id` | `{status}` | `{ok:true}` | write |
| `GET /api/users` | `app?`, `window` (`1h`, `6h`, `24h`, `7d`, `30d`; others `400 bad_window`; default `24h`), `q` (part of a user id, 1-256 characters, longer is `400 {error:"bad_filter", field}`), `risky=1`, `limit` (clamped to 1-100, default 50) | `{ users, truncated, risky_capped, window }`: one row per user id seen on a request (`user_id`, `app_ids`, `requests`, `errors`, `sessions`, `first_seen`, `last_seen`, `risky`, `violations`), busiest first. A request is one action: one trace that holds a request span (a server entry span, or a trace root) carrying the user id. Requests and errors (an action with a failed request) are distinct traces, by the same rule on `/api/users/{user_id}`, `/api/sessions` and `/api/sessions/{session_id}`, so a mobile app or browser call and the server span it triggered count once even when both carry the user id. The two lists count with an approximate distinct count (exact below tens of thousands of actions for one user or session); the person page and the session story count exactly. `sessions` is a distinct count that is exact for ordinary users. `risky` is true, and `violations` counts, a user with at least 3 blocked or quarantined prompts of their own in the window, the same definition the Home and AI & Safety pages use (prompts the user typed, not documents or tool results the app fetched; counted whether or not the policy was enforced). `risky=1` lists only those users. Risk is read for the 500 users with the most violations in the window: when more users than that have violations, `risky_capped` is true and a listed user outside those 500 has `violations: null` (unknown, not zero) and `risky: false`; the `risky=1` filter uses the same 500. Cached for 5 minutes. Errors: `404` unknown app, `503 analytics_paused` at the critical budget (admins may retry with `force=1`), `413 too_broad` past a scan, time or memory cap (pick a shorter window), `502 {error:"clickhouse"}` when the query backend fails (retry; never an empty list) | read |
| `GET /api/users/{user_id}` | `app?`, `window` (`1h`, `6h`, `24h` default, `7d`; `30d` is `400 window_too_wide`; others `400 bad_window`); `user_id` is 1-256 characters after decoding (else `400 bad_user_id`) | `UserProfile`: `{ user_id, state, totals, sessions, errors, ai, safety, sessions_truncated, errors_truncated, replays_truncated }`. The three flags say there are more sessions than the 20 shown, more error titles than the 10 shown, or more replay sessions than the lookup holds. `state` is `not_found_in_window` when nothing was seen. `totals` (`requests`, `errors` (failed requests), `sessions`, `first_seen`, `last_seen`, `app_ids`); `sessions` (newest 20, the row shape of `/api/sessions`, but `requests`/`errors` count only this person's requests, whereas the sessions list counts every request in the visit, so the two differ when someone signs in partway through; `has_replay` is found from the user's own session ids, so it works whether or not the web SDK set a replay user id); `errors` (the 10 most frequent titles with `count`, `last_seen` and a `sample_trace_id`); `ai` (`calls`, `input_tokens`, `output_tokens`, `models`, or null when the user made no AI calls, resolved per trace so SDK data counts); `safety` (`risky`, `violations`, `by_action` counting enforced decisions only, and the 10 most recent enforced non-allow `recent` decisions, or null when there are none). One scan of the user's traces, so the window is limited to 7 days. Cached for 5 minutes. Errors as `/api/users` | read |
| `GET /api/sessions` | `app?`, `window` (as `/api/users`), `user` and `q` (1-256 characters each; `q` matches a session or user id), `errors=1` (only sessions with a problem), `limit` (clamped to 1-100, default 50) | `{ sessions, truncated, replay_truncated, window }`: one row per session id (`session_id`, `app_id`, `user_id`, `started_at`, `last_seen`, `duration_ms`, `requests`, `errors`, `entry` (the first route), `has_replay`), most recently active first. `has_replay` is read from the newest 1,000 replay sessions in the window (with `user`, `q` or `errors=1` set, from the replay sessions those filters select); `replay_truncated` is true when that lookup was cut. Request counts use the same rule as `/api/users`. A session's `errors` counts its problems: traces in which any span carrying the session failed, the same rule the session story uses, so a visit whose child call failed under a successful request is listed as having a problem. Cached for 5 minutes. Errors as `/api/users` | read |
| `GET /api/sessions/{session_id}` | `app?`, `window` (as `/api/users`; default `7d`); `session_id` is 1-200 characters (else `400 bad_session_id`) | `SessionStory`: the visit as one timeline. `state` (`ok` or `not_found_in_window`), `user_id`, `started_at`, `last_seen`, `duration_ms`, `device`, `browser`, `entry_url`, `replay` (`available`, `chunk_count`), `click_count` and `error_count` (the replay's recorded totals, `null` when there is no replay or it did not record them; `error_count` includes client-side errors and is not the failed-request count in `counts`), `counts` per item kind, `risky`, `headline` (`had_errors`, `blocked_prompts` (enforced blocks only) or `quiet`), `items` (oldest first, at most 300, `truncated` when more exist or a source was cut), `other_app_ids`. A request or error item is one action (one trace, labelled by its server span); the action is an `error` when any of its request or failing spans failed, and `counts` for those two kinds are the true number of actions. Each item has `at`, `kind` (`request`, `error`, `ai_call`, `safety`, `event`, `bug_report`), `title`, `detail`, `trace_id`, `ref`, `tone` (and `status` on a `bug_report`); reports are always kept when the 300-item cut applies; a visit with only reports is found when `app` is given; text is cut at 300 characters and is untrusted data. When one visit id appears in several apps, the story is for the app with the latest activity and `other_app_ids` lists the rest. Replays are matched to the app the story resolved to, never another app's. Bug reports come from the app the story resolved to; a read key sees the last 7 days of them. Cached for 5 minutes. Errors as `/api/users` | read |

### Alerts

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/alert-rules` | `app` | `{rules:[{id, name, type, threshold, window, webhook_configured, webhook_kind, channel_id, channel_name, enabled, last_fired_at}]}` (the URL is never returned) | read (people) |
| `POST /api/alert-rules` | `{app, name, type: "error_rate" \| "latency_p95", threshold, window: "5m" \| "15m" \| "1h" \| "6h" \| "24h", channel_id?, webhook_url?}` — pick an existing [notification channel](#notification-channels) with `channel_id`, or add a URL with `webhook_url` (not both: `400 channel_id_or_webhook_url`; a foreign channel is `400 invalid channel_id`) | `201 {rule}` (with `channel_id`, `channel_name`) | write for `channel_id`; `webhook_url` needs admin and reuses or creates a channel (`409 channel_limit` for a new URL at the 25-channel cap) |
| `PATCH /api/alert-rules/:id` | any of `{name, threshold, window, channel_id, webhook_url, enabled}` — `channel_id: null` (or an empty `webhook_url`) clears delivery | `{ok:true}` | write for `channel_id`; setting `webhook_url` needs admin (same `channel_limit` rule) |
| `DELETE /api/alert-rules/:id` | — | `{ok:true}` | write |
| `GET /api/alert-events` | `app` | `{events:[{id, rule_id, fired_at, value, detail}]}` | read |
| `GET /api/alert-rules/:id/signing-secret` | — | `{rule_id, app_id, signing_secret, algorithm, signature_header, webhook_id_header, signed_payload, tolerance_seconds}` (`Cache-Control: no-store`) | admin (people) |
| `GET /api/alert-digest/signing-secret` | `app` | same shape with `app_id`, for the app's daily digest | admin (people) |
| `GET /api/alert-digest` | `app` | `{config:{app_id, enabled, delivery_hour_utc, webhook_configured, webhook_kind, channel_id, channel_name, created_at, updated_at}, last_delivery}` (the URL is never returned) | read (people, session) |
| `PUT /api/alert-digest` | `{app, enabled, delivery_hour_utc, channel_id?, webhook_url?}` — `channel_id` picks an existing [notification channel](#notification-channels); `webhook_url` reuses or creates one (`409 channel_limit` for a new URL at the 25-channel cap); both together is `400 channel_id_or_webhook_url`; `channel_id: null` or an empty `webhook_url` clears the destination (`400` while `enabled`) | same shape as `GET` | admin (session) |

See [Verifying webhook signatures](https://heystack.dev/docs/console#verifying-webhook-signatures) for how to check `X-Heystack-Signature`.

### Notification channels

Named, reusable webhook destinations for alerts and daily digests. A channel's URL is write-only: responses carry a `destination_hint` (host plus the last four characters), never the URL. Each workspace can have up to **25** channels (`409 channel_limit` beyond that). Changing a channel's URL updates every alert rule and digest that uses it. At delivery time (alerts, digests and test messages) the URL's hostname must resolve only to public addresses; otherwise nothing is sent and the delivery fails as `invalid_url`.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/notification-channels` | — | `{channels:[{id, name, kind: "slack" \| "generic", destination_hint, created_by, created_at, updated_at, last_tested_at, last_test_status, used_by:{alert_rules, digests}}]}` | read (people) |
| `POST /api/notification-channels` | `{name (1–80 chars), url}` — `https://` public URL only (`400 invalid_name` / `invalid_url`) | `201 {channel}`; `409 channel_exists {channel_id}` for a URL already saved | admin |
| `PATCH /api/notification-channels/:id` | any of `{name, url}` | `{channel}`; `404`; `409 channel_exists` | admin |
| `DELETE /api/notification-channels/:id` | — | `{ok:true}`; `404`; `409 channel_in_use {alert_rules, digests}` | admin |
| `POST /api/notification-channels/:id/test` | — | `{status: "sent" \| "failed", http_status, error_code}` — sends an unsigned test message with header `X-Heystack-Test: 1`; `429 test_too_soon {retry_after_ms}` (one per 10 s) | admin |

### Explore saved views

Named Explore links shared across the org, pinned per person. Any read credential lists them; no read key sees authorship (`created_by` is absent, and `mine` and `pinned` are always `false`), and an app-scoped read key sees only views bound to its app (all-app views are hidden from it). Every write is people-only: a read key gets `403 read_key_not_allowed`. Names are unique per org after Unicode normalisation and lower-casing, and may not contain control or zero-width characters. Caps: 200 views per org, 8 pins per person.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/views` | — | `{views:[{id, name, href, app_id, created_by (people only), mine, pinned, created_at, updated_at}]}`, pinned first (your pin order) then by name | read (a read key passes the usual rate limit and window checks) |
| `POST /api/views` | `{name (1–80 chars), href}` — `href` is an `/explore/{traces\|logs\|metrics\|map\|workers\|sql}` path (only `traces` takes an id segment, `[A-Za-z0-9._:-]`, up to 128 characters), at most 10,000 characters; a single `app` query parameter, if present, must be one of your apps (`400 invalid_name` / `invalid_href` / `invalid_app`) | `201 {view}`; saving a name you already own replaces it (`200 {view}`); `409 name_taken` for someone else's name; `409 too_many_views` | write (people) |
| `PATCH /api/views/:id` | any of `{name, href}` (same validation as `POST`) | `{view}`; `400 nothing_to_change` / `invalid_name` / `invalid_href` / `invalid_app`; `404`; `409 name_taken`; `403 not_owner` | write for your own view; an admin (admin scope) may edit any |
| `DELETE /api/views/:id` | — | `{ok:true}` (its pins go too); `404`; `403 not_owner` | write for your own view; an admin (admin scope) may delete any |
| `PUT /api/views/:id/pin` | — | `{view}`; idempotent; `404`; `409 too_many_pins` | write (people) |
| `DELETE /api/views/:id/pin` | — | `{ok:true}`; idempotent, and works even if the view is already gone | write (people) |

Deleting an app removes the views bound to it and their pins.

`DELETE /api/apps/:id` removes **everything stored for the app** (organisation admin), in one batch bound to your organisation and the app: ingest keys and any read key pinned to it (those are revoked, so the admin list keeps the history), alert rules, events and digests, the Cloudflare and GitHub recovery connectors (the encrypted GitHub token is destroyed with its row, but the token itself lives on GitHub, so revoke it there), App Care journeys, incidents and runs, security policies (the single highest policy-activation number per environment is kept, without any configuration, so other apps' verification status never changes), findings and journey verifications, issue triage and state, bug reports, investigations and their approvals for the app, saved Explore views, sampling and replay settings, and the app's session-replay and symbol-map files. While a GitHub recovery run is live for the app it answers `409 {error:"recovery_in_progress", message, runs:[{state, run_url}]}` and deletes nothing: wait for the run or cancel it on GitHub. The check happens just before the delete and is not atomic with it: a run that starts in that instant is not seen. `blobs` reports how many files were removed now; `remaining: true` and `{error:true}` mean some files are left, and a scheduled sweep finishes them within a few minutes.

**Telemetry is not deleted.** Telemetry already received stays visible in organisation-wide views and SQL until it expires (within 30 days); deleting it sooner would need costly bulk deletes. Nothing new arrives for the app, and app ids are random and never reused, so the old data cannot attach to a new app. The deleted app's own pages, issue and session links, overview and inbox answer `404`, but analytics reads that name the deleted app (traces, logs, metrics, problems) can still return its remaining telemetry until it expires.

### Workspace & members

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/org` | — | `{id, name, slug, membersCount}` | read (people) |
| `PATCH /api/org` | `{name}` | `{id, name}` | admin |
| `GET /api/org/members` | — | `{members:[{userId, email, name, role}]}` | read (people) |
| `PATCH /api/org/members/:userId` | `{role: "org:admin" \| "org:member"}` | `{ok:true}` | admin |
| `DELETE /api/org/members/:userId` | — | `{ok:true}` | admin |
| `GET /api/org/invites` | — | `{invites:[{id, email, role, createdAt}]}` | read (people) |
| `POST /api/org/invites` | `{email, role?}` | `201 {invite}` | admin |
| `DELETE /api/org/invites/:id` | — | `{ok:true}` | admin |
| `POST /api/org/provision` | — | `{tenant_id, created}`: your oldest workspace, or a new personal one | console session only (`403 session_required` for any token) |

### Agent audit & feedback

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/audit` | `limit`, `before?` (ISO `created_at` cursor, exclusive; newest first), `action?`, `actor?` (a user id), `auth?` (`session` \| `oauth` \| `pat` \| `read_key`), `format?=csv` | `{events:[{id, user_id, auth, token_id, client_id, agent, agent_client, tool, action, target, method, path, status, duration_ms, investigation_id, created_at}]}` — every API/MCP call by agents, tokens and read keys, and every change a person makes in the console. See [Audit log](#audit-log) | admin |
| `POST /api/agent-feedback` | `{kind: "missing_capability" \| "wrong_result" \| "other", message, tool?, context?}` | `201 {id}` | read |

### Usage budget

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/analytics-budget` | — | `{level: "normal" \| "elevated" \| "critical", ttlMultiplier: 1 \| 3, tenant: {used, share, level}}` (Heystack operator orgs additionally get `day, used, allowance, families, reserved_total`). `tenant` is your own organisation: on-demand lookups used today, its plan's daily share (`null` = unlimited) and its level (`elevated` from 60% of the share, `critical` at 100%) | admin |

Heystack tracks an analytics request budget that is shared across the whole platform. Customers see only the current throttling level; detailed platform-wide counts are operator-only. Counters are batched, so they can lag by up to a minute, and nothing is throttled yet. Read keys and read-only tokens cannot call this endpoint; `503 {error: "budget_unavailable"}` means the budget could not be read.

### Ingest counters

```
GET /v1/ingest/counters?window=15m
```

Returns a periodic summary of records Heystack ingested during the window, grouped by app and then by signal. Summaries refresh at most once every **30 minutes** and are not a live ingestion-health check. Any read credential works; a read key is the usual choice. Telemetry collection, incident alerts, and interactive log/trace queries are unchanged.

```
GET /v1/ingest/counters?window=15m
Authorization: Bearer hs_read_<32 hex>

{ "at": "2026-09-16T10:15:00.000Z", "window": "15m",
  "apps": { "my-api": { "log": 1234, "trace": 1180 },
            "my-ios-app": { "crash": 0, "event": 87 } },
  "refresh_after": "2026-09-16T10:45:00.000Z",
  "refresh_interval_ms": 1800000, "stale": false }
```

- `at` — when the source snapshot was observed (UTC), **not** when this cached response was served. The requested window ends at this observation. Preserve this timestamp in history; a cached observation is not a new sample.
- `window` — the window that was applied. A number plus a unit (`5m`, `15m`, `1h`, `24h`, `7d`); **default `15m`, maximum `7d`** — longer returns `400 {"error":"window too long (max 7d)"}`, as does a malformed value.
- `apps` — one entry per app, keyed by the app's `service.name`. Crash and replay records don't carry a service name of their own, so they are filed under the service name configured for that app in the console (or the app id if none is set). Inside each app, one entry per signal with the record count.
- `refresh_after` / `refresh_interval_ms` — earliest next refresh and normal refresh interval. Respect these and `Retry-After` on errors; polling faster does not refresh the database.
- `stale` — a refresh could not complete or its budget is exhausted. The previous snapshot may be returned for **less than two hours from observation**, with its original `at`. Display it as stale; never call it current or insert repeated samples. When no usable snapshot exists, the endpoint returns `503` (upstream/cache unavailable) or `429` (budget exhausted), not empty counters.

Values are **window totals**, not per-minute rates. To display an average per minute, divide by the applied window's number of minutes. For a half-hourly summary use `?window=30m`; fetching a 15-minute window only once every 30 minutes would leave intervals unobserved. These are snapshots, not gap-free historical ingestion accounting.

### Counter cost and request limits

The endpoint shares durable snapshots across credentials, app filters, Worker instances and locations within an authenticated tenant. Authentication and app-scope checks still run on every request. Equivalent window spellings (`60m` and `1h`) share a cache entry; arbitrary parameters, request cache headers, new keys, and new viewers cannot force a refresh.

- At most **120 endpoint requests per UTC minute per tenant**, including cache hits, across all credential types. Existing read-key/IP limits also apply.
- At most **8 database refresh attempts per UTC hour and 192 per UTC day per tenant**, shared across all windows/apps/keys. Failed attempts count. One repeatedly polled window normally needs about **48/day**, without multiplying by app filters.
- Failures have a durable exponential retry delay (1 minute up to 30 minutes), one refresh at a time, and no direct-query fallback if the coordinator is unavailable. `429` and `503` include `Retry-After` seconds.
- Snapshots are bounded to 1 MB and 10,000 result rows; overflow fails rather than returning a partial count. Expired snapshots are pruned on successful refresh.

These limits protect this endpoint, not every analytics query or an entire provider organization's quota. Multiple tenants and other query endpoints have separate workloads. There is no caller-controlled cache bypass; use ordinary log/trace investigation endpoints when you need current incident evidence. Clients must not automatically fall back to those endpoints on a counter error.

A signal that had **no records** in the window is simply absent from the response — treat a missing key as `0`. An app-scoped read key only ever returns its own app; other callers can optionally narrow to one app with `&app=<app id>`.

| Signal   | What it counts                                                                                  |
|----------|-------------------------------------------------------------------------------------------------|
| `trace`  | Spans — each traced operation                                                                   |
| `log`    | Log records without an `event.name`                                                             |
| `event`  | Log records that carry an `event.name` (structured events, e.g. mobile lifecycle events)        |
| `crash`  | Crash reports                                                                                   |
| `replay` | Session-replay chunks                                                                           |

Counts are kept at **minute granularity** and are **approximate** under delivery retries — if an app's SDK retries a batch after a network hiccup, that batch can be counted twice. This is fine for dashboards, health checks, and "did anything arrive?" alerts. Do not use these counters for billing or reconciliation.

A tiny health check in shell — alert if `my-api` sent no traces in the last 15 minutes:

```bash
count=$(curl -s "https://ingest.heystack.dev/v1/ingest/counters?window=15m" \
  -H "Authorization: Bearer $HEYSTACK_READ_KEY" \
  | jq -r '.apps["my-api"].trace // 0')

if [ "$count" -eq 0 ]; then
  echo "my-api has sent no traces in the last 15 minutes"
  exit 1
fi
```

## Investigations

An investigation is the saved record of what an agent (or you) looked at and concluded. Agents journal their work into one as they go; the console follows it. These routes are for people and agent credentials only: a read key gets `403 {"error":"forbidden","reason":"read_key_not_allowed"}`.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/investigations/steps` | `{investigation_id?, traceparent?, actor: "agent", steps: [{kind: "tool_call" \| "external", tool?, args?, status?, duration_ms?, snapshot?, console_url?, text?}]}` (1 to 10 steps) | `{investigation: {id, status, control, control_epoch, console_url, inferred} \| null, recorded}` | read + `write` |
| `POST /api/investigations/hook-events` | `{client_session_id, event: "edit" \| "command" \| "prompt_submit" \| "session_end", path?, cwd?, description?, pr_url?}` | `{recorded: 0 \| 1, dropped?: "consent" \| "no_investigation" \| "empty", investigation_id?, console_url?, control?, user_messages?}` | read + `write` |
| `GET /api/investigations/preferences` | none | `{show_hook_steps}` | read |
| `PUT /api/investigations/preferences` | `{show_hook_steps: boolean}` | `{show_hook_steps}` | signed-in session only (`403 session_required` for a token) |

**Hook events are forward-compatible.** On `POST /api/investigations/hook-events`, unknown fields and unknown `event` values are **ignored** (`2xx`; an unknown event answers `{"recorded":0}`), and an ignored field is never stored or logged. `pr_url` accepts a pull or merge request link on **any** forge (GitHub, GitLab, Bitbucket, Azure DevOps, …): `https://`, at most 500 characters, no user name or password, no query string, no fragment. A body without a valid `client_session_id`, or with a malformed known field, is still `400 {"error":"invalid_event"}`.

### Reading and steering investigations (console)

All of these are for people and agent credentials (a read key gets `403 read_key_not_allowed`). Anything you cannot read answers `404 {"error":"not_found"}`, the same as an id that does not exist.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/investigations` | `?app&origin=agent\|console\|alert&status=live\|done&issue_key&limit` (1 to 50, default 20)`&before=<cursor>` | `{investigations}` newest activity first. `live` is active or waiting for you; `done` is concluded or abandoned. Drafts are never listed | read |
| `GET /api/investigations/live` | `?app` | `{count, agents: [{investigation_id, agent_client, agent_state, last_activity_at, console_url}]}`: investigations you can read that are live and that an agent worked on in the last 30 minutes (whatever their origin); `agents` holds the 3 most recent | read |
| `GET /api/investigations/:id` | none | `{investigation, hypotheses, approvals}` (pending approvals). Every investigation carries `is_mine` (you created it) and `can_write` (you may take over, hand back and share: the creator, the person who handed it off, or an admin with the `admin` scope; false for a credential without `write`). A Care investigation id answers `404 {"error":"not_found","care_issue_key"}` so the console can open that issue | read |
| `GET /api/investigations/:id/steps` | `?after=<seq>&limit` (1 to 200, default 100) | `{steps, last_seq, status, control, control_epoch, updated_at, etag}` and an `ETag` header | read |
| `POST /api/investigations` | `{app, title (1 to 200), question?, issue_key?, window?, visibility? = "org"}` | `201 {investigation}` (origin `console`, waiting for you, you in control) | signed-in session |
| `POST /api/investigations/:id/notes` | `{text (1 to 4096 UTF-8 bytes)}` | `201 {step}` | signed-in session, read |
| `POST /api/investigations/:id/control` | `{control: "agent" \| "user", expected_epoch}` | `{investigation}`; `409 {"error":"epoch_conflict","control","control_epoch"}` when someone else changed control first | signed-in session; the owner, the person the investigation was handed to, or an admin (`403 not_writer`) |
| `PATCH /api/investigations/:id` | `{visibility?: "private" \| "org", status?: "concluded" \| "abandoned"}` (at least one) | `{investigation}`; sharing to `org` needs the `write` scope. `status` is a person's Conclude (`concluded`) or Stop (`abandoned`): it stamps the finish time and records a step on the timeline; sending the status it already has records nothing. A draft can't be concluded (`400 invalid_investigation`) | the owner, the handoff person or an admin, and the `write` scope in both directions (`403 scope_required`). `status` needs a console session (`403 session_required`; agents conclude through `/:id/update`). A non-session credential gets `409 {"error":"user_in_control","investigation_id"}` while a person holds control, whatever headers it sends |
| `POST /api/investigations/approvals` | `{kind: "repair_execute", app, plan_id, investigation_id?, client_session_id?}` | `201 {approval, approval_url, investigation_id}`. Asks for console approval of an awaiting-permission repair plan; the request is bound to a hash of everything the approver is shown and lasts 24 hours. A pending request with the same hash is reused within the same investigation (another investigation gets its own request). `409 investigation_app_mismatch` when the investigation is about a different app. A draft investigation becomes active so the link resolves. `409 repair_not_ready` / `managed_review_missing`, `404` unknown plan. Allowed while a person has taken control (it is a request, not a change) | read + `write` (a credential, not necessarily a session) |
| `GET /api/investigations/:id/approvals/:aid` | none | `{approval, payload, payload_hash, stale}`. `payload` is exactly what the hash binds: action, parameters, target release and commit, policy version, the plan's summary and incident title, the checks and, for a managed repair, the reviewed files and diff. Send `payload_hash` back to `decide`; `stale` is true when anything in it changed after the request | read |
| `POST /api/investigations/:id/approvals/:aid/decide` | `{decision: "approve" \| "decline", payload_hash}` (`payload_hash` is required to approve; a stale request can still be declined without it) | `{approval}`. Approving updates the Care plan and the approval in one transaction (both change or neither) and journals the decision. `409 approval_stale` (plan or hash changed), `409 already_decided`, `409 repair_not_ready` / `managed_review_missing`, `410 approval_expired`, `403 session_required` for a token, `403 admin_required` | signed-in session, `org:admin`, `admin` scope |

**Approvals.** An agent can ask for approval but never grant it: only a signed-in organization admin can decide, in the console. An admin token can still approve directly through `POST /api/care/apps/:id/repair-plans/:planId/approve`, so "an agent can never approve its own request" holds for the MCP and investigation path only; do not give an agent an admin token you do not want to approve repairs.

**Paging.** `before` is the cursor `<last_activity_at>|<id>` of the last item you received; rows sharing a timestamp are never skipped. A bare timestamp is also accepted. An empty `limit=` uses the default.

**Polling.** Send the last `etag` from the JSON body back as `If-None-Match` together with `after=<last_seq>`; an unchanged investigation answers `304` without reading any steps. The `ETag` header carries the same value and is exposed to browsers. Polling never touches the analytics store.

**Taking control.** `control` is optimistic on `control_epoch`: read the investigation, then send the epoch you saw. A person's session can always take control back, even while the control lock is turning agent writes away.

**Which investigation a step lands in.** An explicit `investigation_id` (body, or the `x-heystack-investigation` header) must be one you can read (`404` otherwise) and write (`409 not_writer`). Without one, Heystack reattaches to your most recent open investigation from the same client session (12 hours), the same trace, or, as a last resort, the same credential and client within 30 minutes (the response says `inferred: true`). Otherwise it starts a private draft that becomes active after three tool calls. Send `x-heystack-agent-client: name/version` so upgrades of the same client do not split an investigation.

**Read-only credentials cannot journal.** Journaling needs the `write` scope. A read-only token or a read-only MCP session is not an error: both `steps` and `hook-events` answer `200` with `{"investigation": null, "recorded": 0, "journaling": "off", "reason": "read_only_credential"}` (hook events omit `investigation`), so the agent can see that nothing was saved. Nothing is stored.

**Errors.** `400 invalid_steps` (empty or more than 10 steps, an unknown kind, a malformed id), `404 not_found`, `409 not_writer`, `429 step_rate_limited` (a per-organization request ceiling, 600 steps per investigation per hour, or the organization's daily step budget).

**Hook events (opt in).** Editor hooks can report that a file was edited or a command ran, so the console timeline shows work that did not go through Heystack. Events are dropped (`dropped: "consent"`) unless the person has turned on "Show my coding-agent steps" (Settings › Profile; `PUT /preferences`); turning it off deletes that person's hook steps. The body is allow-listed: any other field (prompt text, file contents, diffs, output) is refused with `400 forbidden_field` before anything is stored. Paths are stored repo-relative only: an absolute path is accepted when it is inside `cwd` (which is never stored), otherwise `400 invalid_path`. Command descriptions are redacted for tokens and keys and cut to 200 characters; an empty or unsubstituted description records nothing (`dropped: "empty"`). `pr_url` is kept only when it is a `https://github.com/<owner>/<repo>/pull/<n>` link. Whenever an event resolves to an investigation the answer names it (`investigation_id`, `console_url`). `prompt_submit` returns the current `control` and any console notes the agent has not seen (`user_messages`, delivered once) so a hook can inform the agent; `session_end` marks the agent idle.

**Control lock.** When a person has taken control of an investigation, an agent credential that names it in `x-heystack-investigation` cannot make state-changing calls anywhere under `/api/*`: the answer is `409 {"error":"user_in_control","investigation_id"}`. Not affected: reads (`GET`), the read-only `POST /api/query/sql`, `POST /api/security/evaluate` and `POST /api/agent-feedback`, the person's own session, ids that do not exist or that the caller cannot read, and the journaling calls `POST /api/investigations/steps`, `POST /api/investigations/hook-events` and `POST /api/investigations/:id/update`. `start` is locked like any other write. Changing an investigation (for example sharing it) is locked like any other write.

### Agent sessions, handoff and automatic checks

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/investigations/start` | `{title (1 to 200), app?, question?, window?, client_session_id?, repo?, branch?, issue_key?, resume?: id \| console URL}` | `{investigation, resumed, handoff?}` | read + `write` (a read-only credential: `403 scope_required`) |
| `POST /api/investigations/:id/update` | `{hypotheses? (up to 10: key, statement, status open\|supported\|ruled_out, evidence up to 5), notes? (up to 10: kind finding\|next_action\|conclusion, text), external_steps? (up to 20: kind edit\|test\|command\|pr\|commit, label, path?, url?), status? (active\|waiting_user\|concluded\|abandoned), summary?, repo?, branch?, pr_url?}` (all optional; `{}` just fetches new notes) | `{investigation, control, user_messages (up to 20), approvals, recorded}` | owner, handoff user or admin, `write` (`403 not_writer`) |
| `GET /api/investigations/:id/handoff` | none | `{handoff, text}`: everything an agent needs to continue (read-only; marks nothing as seen) | read |
| `POST /api/investigations/:id/handoff` | `{expected_epoch}` | `{investigation}`: control to the agent, epoch + 1, you become the handoff user | signed-in session, `write` |
| `POST /api/investigations/auto` | `{app, metric: "error_rate" \| "latency_p95", window, include_ai?, persist?, investigation_id?}` | the automatic check result, plus `investigation_id` (the saved run, or the alert investigation it was added to; omitted with `persist:false`); `metric` and `window` are ignored when `investigation_id` is given (the alert rule's own window, anchored at when it fired, is used instead) | signed-in session |

**Start.** Idempotent per `client_session_id`: calling again for the same open session returns the same investigation. A draft that earlier steps created is promoted to `active` and keeps its steps. An unnamed investigation ("Untitled investigation") takes the first real title it is given; `question`, `repo`, `branch`, `issue_key`, `app` and `window` only fill empty fields. Agent-started investigations are private. `resume` takes an id or a console URL, needs you to be allowed to write it (owner, the person who handed it off, or an admin), reopens it as `active`, returns the `handoff` and binds your `client_session_id` to it, so that session's hook events and `prompt_submit` land on it. While a person holds control, `start` (resume or session match) returns the investigation and handoff with `control: "user"` but changes neither its status nor its control (no reopening) (`404` if you cannot read it, `403 not_writer` if you can only read it).

**Update.** Hypotheses, notes and external (code) steps are recorded as steps; a `conclusion` note also becomes the summary unless `summary` is sent, and `status: "concluded"` stamps the finish time. Paths must be repo-relative: one bad path fails the whole request with `400 invalid_path` (other bad input is `400 invalid_update`). Every response carries `user_messages`: notes people wrote in the console since the agent last looked, each with its `author` (`is_you` says whether the note came from the agent's own user; a teammate's note is context, not an instruction). They are delivered once. While a person holds control, journaling continues: hypotheses, notes and external steps are accepted, and `repo`, `branch` and `pr_url` only fill empty fields; the response says `control: "user"` and the agent should pause and ask. A body carrying `status` or `summary`, or a `conclusion` note (which would set the summary), is refused as a whole with `409 {"error":"user_in_control","investigation_id"}` and nothing is written. `repo` (`owner/name`), `branch` (git ref characters), `pr_url` (an `http(s)` link without spaces) and hypothesis `key` (letters, digits, `. _ : -`) are validated strictly (`400 invalid_update`).

**Handoff.** `GET .../handoff` returns `{handoff, text}`; `text` is markdown of at most 8000 characters where everything written by people, agents or telemetry sits inside code fences. `POST .../handoff` is the console's "Continue in your coding agent". Any signed-in reader with `write` can hand an org-visible investigation to their own agent. If a person has taken control, only someone allowed to write it can take it back; anyone else gets `409 {"error":"user_in_control","investigation_id"}`. The step it records names the previous handoff user (`previous_handoff_user_id`). `409 epoch_conflict` works as for `control`.

**Status changes.** Handoff, and `resume` while the agent is in control, reopen the investigation as `active` (clearing a finish time) whatever it was before. `control` (taking over, or handing control back) never changes the status. Only `update` (`status`) or a draft's first recorded work moves it otherwise: a draft becomes `active` when the first hypothesis, note or external step is recorded.

**Automatic checks.** `POST /api/investigations/auto` behaves as before and now also saves the run as a concluded, organization-visible investigation (origin `console`, one dossier step) and returns its `investigation_id`. A model-written narrative is stored with an `[AI-generated]` prefix. If saving fails the result is still returned, without the field. Three request shapes: (1) no extras saves a new investigation; (2) `persist: false` runs the check again without saving anything (no `investigation_id`); the rate limit and AI gating are unchanged; (3) `investigation_id` (an alert investigation of the same app, shared with the organisation) adds the finding to that investigation's timeline, and the returned `investigation_id` is that same id (any other id is `404`). `persist:false` together with `investigation_id` is `400 {error:"invalid_body", reason:"investigation_id_requires_persist"}`, answered before anything is read. With `investigation_id` the server ignores `metric` and `window`: it checks the alert rule's own metric and window (5 minutes is checked over 15), ending when the alert fired, not when the button is pressed, and writes the range it checked ("Checked YYYY-MM-DD HH:MM–YYYY-MM-DD HH:MM UTC.") into the finding. One check per alert investigation: `409 already_checked` (with the id), `409 investigation_closed` (concluded or abandoned), `409 alert_gone` (the rule or event no longer exists) and `409 alert_too_old` (the checked range and its 7-day baseline are past analytics retention) all answer before the rate limiter and before any analytics read.

**Alert investigations.** When an alert rule fires, Heystack opens one organisation-visible investigation for that firing (`origin: "alert"`, `issue_key: "alert:<app>:<rule>"`, started by `system:alert:<rule_id>`) with one system note. It is created once per alert event even if delivery is retried, uses the database only (no analytics read), and never delays or fails the delivery: if it cannot be created, the notification still goes out and its link opens the alert's issue page instead. The Slack button links to `/investigations/<id>?app=<app>`. When the app's cached Issues list names a failing operation, the firing also attaches that issue's brief (core depth: at most 2 analytics reads, none when the brief is already cached; once per alert event; skipped at the critical budget or when the organisation is over its share) as a system step (`kind: "tool_call"`, `tool: "issue_brief"`, `render_kind: "issue"`), and every channel's message carries the brief summary and a link to `/issues/<issue key>?app=<app>`. The generic webhook payload then appends `likely_cause` and `issue_url`; otherwise it is unchanged and carries no link.

**Audit.** Agent calls that carry `x-heystack-investigation` record the id in `GET /api/audit`. The journaling calls `POST /api/investigations/steps` and `POST /api/investigations/hook-events` are not themselves audited.

### Ask

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/ask` | `{question (3 to 300), app?, window?, context?: {page: "home" \| "issue" \| "investigation" \| "explore" \| "other", issue_key?, investigation_id?}}` | `{kind: "query", source: "traces" \| "logs", filters, applied_to: {app, window}}` for a lookup question, or `{kind: "investigation", investigation, reason: "needs_reasoning" \| "untranslatable"}` when the question asks for a cause (why, what happened, explain) or could not be turned into a filter, or `{kind: "unsupported"}` when the credential cannot start an investigation. Only a lookup question uses AI (one credit): out of credits it answers `429 {error:"quota_exceeded", signal:"ai_credits", …}` with `Retry-After`, and `403 {reason:"ai_processing_disabled"}` when AI processing is off. A cause question never uses a credit | read (people) |

**Ask** turns a plain-English question into a structured Explore filter, or starts an investigation for you. It reads no telemetry: a lookup question costs one small model call and returns only the filter, which the console opens in Explore. A question that asks for a cause does not call the model at all; it creates an investigation (origin `console`, waiting for you, you in control) that is **private** to you until you share it. Only a signed-in session creates an investigation; other credentials get `{kind: "unsupported"}` for those questions. A read key gets `403 read_key_not_allowed` (it would spend model budget). Each organization may ask **20 questions per minute**; past that the answer is `429` with `Retry-After: 60`. An unknown `app` is `404`; a malformed body is `400 {"error":"invalid_ask"}`.

## SQL queries

`GET /api/query/schema` lists the tables a query may use and their columns (`{ "tables": [{ name, engine, order_by, description, columns: [{ name, type }] }] }`). It is static, makes no analytics request, is cached for an hour (`Cache-Control: private, max-age=3600`), and any credential with `read` scope may call it, including read keys; `tenant_id` is omitted because the tenant filter is added for you. Session recordings (`replay_chunks`) are not queryable.

`POST /api/query/sql` runs a **read-only** SQL statement over your own telemetry. It exists for the questions the structured endpoints can't answer (multi-way joins, unusual group-bys) and powers `heystack_query_sql` in the MCP server. It takes a person's credential (PAT, OAuth or session) — a read key is refused, because free-form SQL can't be pinned to one app or capped at 7 days the way the endpoints above are.

```bash
curl -X POST https://ingest.heystack.dev/api/query/sql \
  -H "Authorization: Bearer $HEYSTACK_TOKEN" -H "Content-Type: application/json" \
  -d '{ "sql": "SELECT http_route, count() AS n, quantile(0.95)(duration_ms) AS p95 FROM otel_traces WHERE app_id = '"'"'app_123'"'"' AND timestamp > now() - INTERVAL 1 HOUR GROUP BY http_route ORDER BY n DESC", "limit": 20 }'
```

```json
{ "rows": [ { "http_route": "/api/chat", "n": 1204, "p95": 812.4 }, … ],
  "sql_executed": "WITH … SELECT * FROM (…) LIMIT {limit:UInt32}", "elapsed_ms": 42, "truncated": false }
```

Rules:

- **Body:** `{ sql, limit? }`. `limit` defaults to 200, max **1 000**; `truncated: true` when the cap was hit.
- **Tables:** `otel_traces`, `otel_logs`, `otel_metrics`, `otel_span_events`, `otel_span_links`, `crashes`, `otel_traces_red_rollup`, `otel_traces_genai_rollup`. Column references are served as MCP resources (`heystack://schema/*`) and by the `heystack_schema` tool.
- **Read-only.** A single `SELECT` (or `WITH … SELECT`). These are rejected with `400 { "error": "invalid_sql", "message" }`, where the message names the problem:
  - DDL, DML, `INSERT`, `SYSTEM`, `SETTINGS`, `FORMAT` and `FINAL`
  - multiple statements
  - SQL comments (`--`, `/* */`, `#`)
  - query parameters (`{name:Type}`)
  - anything touching other databases or tables
- **Functions.** Common analytics functions are allowed: aggregates and their `-If`/`-Merge`/`-State` combinators, string, date and time, math, JSON, array, map, tuple, conditional, conversion, hashing and window functions. Table functions and functions that read other data or the server are rejected. Examples are `numbers()`, `url()`, `file()`, `dictGet()`, `joinGet()` and `getSetting()`. The function form of `in(…)` is also rejected; write `x IN (…)`. A subquery passed to a function needs its own parentheses: `has((SELECT …), x)`.
- **CTEs.** `WITH name AS (SELECT …)` works at the top level and inside subqueries. A CTE is visible only within the query that defines it and the queries nested inside it. It cannot reuse the name of an existing table.
- **Tenant scoping is automatic.** Each allowed table is rewritten into a workspace-scoped view before execution (`sql_executed` shows the result). You cannot see, or accidentally query, anyone else's data.
- **Caps:** A tenant-scoped time window, execution timeout, and the row cap above. Always add a time predicate (`timestamp > now() - INTERVAL …`).
- **Query errors** come back as `400 { "error": "clickhouse_error", "code", "name", "message" }`. `code` and `name` are the database error code and name, for example `47` / `UNKNOWN_IDENTIFIER`, and are `null` when unknown. `message` is a fixed hint, such as "check column names", so a script or agent can correct the SQL and retry. The database's own error text is never returned, because it can quote stored values. Scan, time and memory caps come back this way too, with their code and a hint.
- **Too large to return.** A result that is too large to send back (wide rows such as full attribute columns, even under the row cap) is `413 { "error": "too_broad", "message" }` with a fixed hint: select fewer columns, aggregate, or lower the limit.
- Every SQL call is audited (`GET /api/audit`).

### Issue brief, affected people, dossier and fix paths

Every issue carries a **brief**: what is happening, the likely cause with its evidence and "what would rule it out", the suspect release with commit and compare links, examples, reproduction hints, and what "fixed" will mean. It is worked out by rules (no AI), cached per issue, and shared by the console, MCP and hand-offs.

| Route | Body / query | Response | Auth |
|---|---|---|---|
| `GET /api/inbox/:issueKey` | `?app`, `?window`, `?depth=core` (skip the deeper checks), `?refresh=1` (recompute, same rule as the inbox snapshot refresh) | The issue story, now with `brief` (full depth unless `depth=core`). `likely_cause` and `confirm` are kept for one release and derived from the brief. A cached brief costs no analytics read; a new one costs at most 6 (2 at `core`). When analytics is paused a cached brief is served; with none, the paused checks appear in `brief.limited` | read; a read key gets the brief without logs, sessions, replays, visitor attributes or AI text (`limited: read_key`) |
| `GET /api/inbox/:issueKey/people` | `?app`, `?window` | `{issue_key, window, people: [{user_id, events, last_seen, console_path}], measured, impact, profiles, names_shown}`; each person links to their page, and `profiles` carries their names when the app shows names (one more profile read at most; email for admins only). One on-demand read; `503 analytics_paused`, `413 too_broad` | read; `403 read_key_not_allowed` for a read key |
| `GET /api/investigate/dossier` | `?app` (required), `?window` | `{app, window, computed_at, stale, open_issues, issues: [{issue_key, title, summary, top_cause, console_path}] (top 3), limited, deltas: [{metric, current, prior, ratio}]}` (`requests`, `error_rate`, `p95_ms`, largest change first). Built from the inbox snapshot, cached briefs (a missing one costs at most 2 reads) and the overview's request, error-rate and p95 changes. No AI text | read; a read key gets redacted briefs |
| `POST /api/inbox/:issueKey/github-issue-draft` | none | `{url, title}`: a prefilled `https://github.com/<repo>/issues/new` link (body at most 6,000 characters, fenced, no user ids). Nothing is sent to GitHub; the draft is recorded on the issue. `409 repository_not_linked` when the app has no linked GitHub repository | `write`; `403 read_key_not_allowed` |
| `POST /api/inbox/:issueKey/send` | `{user_id}` or `{email}`, optional `note` (at most 500 characters) | `{sent: true, to: {user_id, name}}`: the teammate (only them, not your organisation's channels) gets an "issue assigned"-style notification with the brief's summary. When nothing was sent it answers `200 {sent: false, reason}`: `reason` is `"notifications_off"` (notifications aren't switched on yet) or `"not_queued"` (it could not be queued; try again). An address that is not a member answers `{invite_required: true}`; an unknown `user_id` is `404 not_a_member` | signed-in session with `write` (`403 session_required`) |
| `POST /api/inbox/:issueKey/suggested-fix` | none | `{text, model, generated_at, ai_generated: true, brief_hash, cached}`: a plain-language suggestion written by AI from the brief (at most about 150 words, links removed). Generated once per brief state and kept with the issue's brief, so asking again is free until the brief changes; uses one AI credit. `503 disabled` when the feature is off, `403 ai_processing_disabled`, `429 quota_exceeded` (the standard AI-credit body, with `Retry-After`), `502 ai_failed` | read; `403 read_key_not_allowed` |

`POST /api/ask` answers a "why" question asked on an issue page with that issue's cached brief: `{kind: "brief", issue_key, summary, causes, limited, console_url, next_step: "continue_in_agent"}` (no AI call). With no cached brief it starts an investigation as before.

`GET /api/investigations/:id/handoff` includes the linked issue's cached brief in `handoff.issue_brief` and in the text (cause, links, examples, reproduction hints, what fixed means, and the `heystack_link_fix` step), within the 8,000-character cap.

The automatic check (`POST /api/investigations/auto`) reports its release verdict as `regressed`, `always` or `insufficient` (`always_failing` is gone), using the same release comparison as the brief.
## Fixes and deploys

Link a fix to an issue, and Heystack watches the release that contains it and tells you whether the issue stopped. `:issueKey` is the issue's key from `GET /api/inbox`, URL-encoded. An issue in another app than an app-scoped read key's own, or in an app that doesn't exist, is `404`.

Fix checking is available once it's switched on for your workspace. Every response below except the narrative carries `fix_watch_available` (boolean): while it is `false`, fixes and "resolve in next release" are still recorded but are never decided (they stay `awaiting_release` or `watching`), so don't treat that state as progress.

| Method & path | Body / params | Returns | Access |
|---|---|---|---|
| `POST /api/inbox/:issueKey/fixes` | `commit_sha?` (7 to 40 hex characters), `pr_url?` (https, on github.com, gitlab.com or bitbucket.org), `investigation_id?`, `mode?` (`commit`, the default when a commit or PR is given; `next_release`; `release` with `release`) | `201 {fix, created:true, fix_watch_available}`; the same fix linked again is `200 {fix, created:false, fix_watch_available}`. More than 5 active watches on one issue or 50 in the workspace is `409 {error:"too_many_watches"}`. A fix on a failing request, or on an error whose service is known, is watched on that service only: another service of the same app shipping a release, or its traffic, never verifies it | write; read keys `403` |
| `GET /api/inbox/:issueKey/fixes` | none | `{fixes:[…], events:[{id, fix_id, kind, actor_kind, detail, occurred_at}], fix_watch_available}`; events never name who acted, only whether it was a person, an agent or Heystack | read; read keys allowed |
| `GET /api/inbox/:issueKey/verify` | none | `{state, confirm, fixes, statement, fix_watch_available}`: `state` is the leading fix's state (`awaiting_release`, `watching`, `verified`, `regressed`, `expired`) or `none`; `statement` is a sentence you can show as is. Useful as a CI gate after a deploy (check `fix_watch_available` first: while it is `false` the state never becomes `verified`) | read; read keys allowed |
| `DELETE /api/inbox/:issueKey/fixes/:id` | none | `{fix, fix_watch_available}` with `fix.state:"cancelled"`; a fix that is already decided is `409 {error:"already_decided"}` | write; read keys `403` |
| `POST /api/inbox/:issueKey/resolve-in-release` | `mode` (`next_release` or `release`), `release` (required for `release`) | as linking a fix. `release` resolves the issue now; `next_release` resolves it when the next release is confirmed clean | write; read keys `403` |
| `POST /api/inbox/:issueKey/narrative` | `{}` | `{narrative:{text, model, generated_at, ai_generated:true, brief_hash} \| null, cached, reason?}`; `reason:"guard_rejected"` when the model's answer named something the evidence doesn't contain (it is not retried until the evidence changes). `409 {error:"brief_not_ready"}` until the issue page has been opened; `503 {error:"narrative_disabled"}` when the feature is off; `403 {reason:"ai_processing_disabled"}` when your organisation turned AI processing off; out of AI credits is the standard `429 {error:"quota_exceeded", signal:"ai_credits", …}` | read; read keys `403` |

Each fix has a `state`, `mode`, `commit_sha`, `pr_url`, `fixed_in_release` and `release_basis` (`deploy_commit` or `deploy_commit_list` when a deploy marker named the commit, `named_release` when you named it, `assumed_next_release` when Heystack assumed the first new release contains it), `baseline` (`{matched, total, rate, measured_at}`, or `null` with `baseline_unknown:true`), `after` (the same counts in the fix's release), `min_volume`, `statement`, `commit_url`, `linked_by_kind`, `created_at`, `expires_at` and `decided_at`.

**Budget.** Linking a fix, and resolving in a release, runs one on-demand read: the issue's rate over the 7 days before the link. A fix linked automatically from a merged GitHub pull request (see [GitHub App](#github-app)) gets the same single baseline read, under the same pause rule. If analytics are paused or the read fails, the fix is still linked, with an unknown baseline (it can then be shown as "not seen since", never "confirmed fixed"). Everything after the link is counted as telemetry arrives; watching a fix makes no further analytics reads. The narrative uses the issue page's cached evidence and makes no analytics read.

### Deploy markers

| Method & path | Body / params | Returns | Access |
|---|---|---|---|
| `POST /api/deploys` | `version` (required, up to 128 characters, no spaces), `build?` (usually the commit SHA), `previous_build?`, `environment?`, `deployed_at?` (ISO-8601, default now; at most 5 minutes ahead and 30 days back), `pr_url?`, `commits?` (up to 100 SHAs), `source?` (`api`, `ci`, `github`, `vercel`, `cloudflare`; default `api`); `app` (required unless you use a server key) | `201 {deploy, created:true}`; the same deploy again is `200 {deploy, created:false}`. More than 60 deploys per app per hour is `429` | a server ingest key (`sk_live_…`, for the app it belongs to), or `write`. Browser and mobile keys `403 {reason:"server_key_required"}`; read keys `403` |
| `GET /api/deploys` | `app?`, `limit?` (1 to 100, default 20) | `{deploys:[{id, app_id, version, build, previous_build, environment, deployed_at, source, pr_url, commits, commit_url, compare_url, created_at}]}`, newest first. Who sent a deploy is not returned | read; read keys allowed (an app-scoped key sees its own app) |

`POST /api/deploys` is the only `/api` route that accepts a server ingest key, so a deploy job can use the key your app already has. Calls made with an ingest key appear in the audit log. A copy-paste CI step is in the [quickstart](https://heystack.dev/docs/quickstart#deploy-markers).

`GET /api/releases` rows also carry `deploy` (`{deployed_at, source, pr_url, commit_url, compare_url}` for the newest marker of that version, or `null`) and `traffic` (`true`). Releases known only from a deploy marker or from their first telemetry, with no traffic in the window, are added at the end with zero counts and `traffic:false`.

### GitHub App

Ships switched off: while `GITHUB_APP_ENABLED` is not `"true"` (it ships `"false"` until the Heystack GitHub App is registered), every route below and the webhook answer `404`. All of it is D1 only (no analytics reads, never paused at the critical budget), except the one baseline read when a merged pull request links a fix. Read keys are refused on every `/api/github` route (`403 read_key_not_allowed`). "Configured" means the App's slug, its webhook secret and the recovery service are all set.

| Method & path | Body / params | Returns | Access |
|---|---|---|---|
| `GET /api/github/status` | `app` | `{configured, installations: [{installation_id, account_login, account_type, repository_selection, suspended, repositories[], truncated, created_at}], app: {id, repository, covered, installation_id} \| null}` | read (people only) |
| `GET /api/github/install-url` | `app` | `{url, expires_in: 600}`: the GitHub install page with a single-use state (only its hash is stored). `503 github_app_not_configured` when not configured | admin |
| `GET /api/github/setup` | — (browser redirect) | The App's callback URL. Redirects (302) to the app's **Settings › App › Code repository** page with `github_setup=1&installation_id&state&code`, or to `/settings?github_setup=expired` for an unknown or expired state. Changes nothing | none |
| `POST /api/github/callback` | `{installation_id, state, code}` | `201 {installation, app: {id, repository, covered, bound_now}}`. `400 state_invalid \| state_expired \| state_used` (the state is bound to the person who started the install), `403 session_required`, `403 github_installation_not_accessible` (your GitHub account can't see that installation), `403 github_installation_not_administered` (you are not that account itself or an owner of that organisation; only the repositories you can reach through the installation are stored), `400 github_authorization_required`, `503 github_app_not_configured` | admin, signed-in session only |
| `DELETE /api/github/installations/:id` | — | Forget an installation (uninstalling happens on GitHub). `{removed: true}`, `404` when unknown | admin |
| `POST /api/github/issues/:issueKey` | — | Files a GitHub issue from the issue's brief in the app's repository (no end-user names or emails). `201 {url, number, title, created: true}`; an issue already filed returns `200 {…, created: false}`. `409 repository_not_linked`, `409 github_app_not_installed {repository}`, `404` when the issue is not in the current snapshot, `503 github_app_not_configured`, `502` when GitHub refused. The URL is kept as the issue's external link (kind `github_issue`) | write |
| `POST /webhooks/github` | GitHub signature | `X-Hub-Signature-256` over the raw body (constant time), `401` otherwise; `503` without the secret; `413` over 2 MB. Each `X-GitHub-Delivery` is applied once (`{duplicate: true}` after). Events: `installation`, `installation_repositories`, `push`, `pull_request` (merged only), `deployment_status` (success only); others, unknown installations and uncovered repositories answer `202` | GitHub |

Audit labels: `github_app.install`, `github_app.forget`, `issue.github_issue`.

A merged pull request is linked as the fix (`linked_by: "github"`, kind `system`, mode `commit`) of each issue it names in an app bound to that repository: `Fixes|Closes|Resolves HS-<issue key>` in the description, the console issue link, or a `hs/<source>/<app>/<id>` branch (at most 5 per PR). Its baseline is measured with the same single read as a manual link, and is unknown when analytics are paused. A successful deployment becomes a deploy marker with `source: "github"`, `external_id: "github:deployment:<id>"`, `repo`, and the commit's `author_login` and merged `pr_url`.

### Activation milestones

Heystack records the first time an organisation or app reaches each setup and usage step, once (a later repeat changes nothing). They are Heystack's own records: reading them never runs an analytics query.

| Milestone | Recorded when |
|---|---|
| `signed_up` | An account and its organisation are created |
| `app_created` | An app is created |
| `test_event_received` | `POST /v1/test-event` succeeds with the app's server key |
| `first_signal:<kind>` | The first stored data of that kind for the app: `trace`, `log`, `event` (a log with an event name, such as a browser error or product event), `replay`, `crash`, `metric` |
| `setup_check_passed` | `GET /api/setup-check` first reports every required row passing |
| `home_viewed` | A person first opens Home (organisation-wide, or for one app) |
| `agent_connected` | The first API call for the organisation from a coding agent (the MCP server announces itself) |
| `channel_configured`, `invite_sent`, `invite_accepted`, `first_issue_opened`, `investigation_opened`, `second_app_created`, `fix_linked`, `fix_verified`, `plan_upgraded` | At the matching action |

An app is **activated** when, within 24 hours of its creation, it sent its first data of any kind, its required setup rows passed, the organisation has a notification channel, and someone opened Home or an issue. `activation.next` names the first step still missing.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/apps/:id/milestones` | — | see [Apps, keys & configuration](#apps-keys--configuration) | read (read keys allowed) |
| `GET /api/operator/funnel` | `weeks?` (1–26, default 8) | `{weeks, milestones:[{milestone, counts[]}], activation:{apps_created, activated, rate, window_hours}, loop:{since, stages:[{stage, count}], issues_considered, capped}, generated_at}`. `loop.stages` is the identified → opened → cause accepted → remedy → shipped → confirmed funnel over issues first seen in the window; an issue counts at a stage only if it reached every earlier one, and a fix with too little traffic is shipped, never confirmed | Heystack operators only (an admin of an organisation in `HEYSTACK_OPERATOR_ORG_IDS`); everyone else `403`, read keys `403 read_key_not_allowed` |

### Key events

Every route is D1 only except `POST /api/key-events/suggest` (one on-demand read). `app` / `app_id` must be an app of your organisation (`404 {error:"not_found"}` otherwise); an app-scoped read key is pinned to its own app. Errors: `400 {error:"invalid", field|message}`, `404 {error:"not_found"}`, `403 {error:"forbidden", reason:"scope_required", scope}`, `403 {error:"read_key_not_allowed"}`. Every write is in the audit log. Tagging is behind `KEY_EVENT_TAGGING` and the daily counts behind `DERIVE_KEY_EVENTS_ENABLED` (both ship `"true"`). See [Key events](https://heystack.dev/docs/key-events).

A key event (`KeyEventView`) is `{id, app_id, name, label, source (span|event|autocapture|connector), matcher, grammar_version:1, evidence (observed|verified), enabled, effective_from, superseded_by, backfill_state (none|pending|running|done|capped|deferred|failed), backfill_rows, backfill_from, backfill_error, suggested_by, created_by, created_at, updated_at, summary, counts:{today, d7, d30}, daily:[{day, events}] (the last 30 UTC days, zero-filled, oldest first), counted_from (backfill_from, else effective_from)}`. `observed` means matching traffic was seen; it never says the action succeeded for the person. Only an `event` matcher with `outcome eq "succeeded"` is `verified` (connector key events are verified by the provider).

| Method & path | Body / params | Returns | Access |
|---|---|---|---|
| `GET /api/key-events` | `app` (required), `include=all` (also turned-off and older versions) | `{key_events: KeyEventView[], limit: 50}` | read; read keys allowed |
| `GET /api/key-events/:id` | — | `{key_event}` | read; read keys allowed |
| `POST /api/key-events` | `{app_id, label (1–80 chars), name? ([a-z0-9_]{1,64}; made from the label when absent), matcher, suggested_by? ("pattern"\|"model"), backfill? (default true)}` | `201 {key_event}`. Counting starts at `effective_from` = now + 120 s. `409 {error:"name_taken"}` when another enabled key event of the app has the name; `409 {error:"limit", limit:50}` past 50 enabled; a `connector` matcher is `400` (connector key events are created by connecting a provider). With `backfill` and a `span` or `autocapture` matcher the history count starts in about 5 minutes (`backfill_state:"pending"`); an `event` matcher is counted retroactively with no backfill (`none`) | admin; read keys `403` |
| `PATCH /api/key-events/:id` | `{label?, enabled?, matcher?}` | `{key_event}`. `label` and `enabled` change in place (turning one on respects the 50 limit). A `matcher` never edits: it creates a new definition (new id, new `effective_from`, history counted again as on create), and the old one gets `superseded_by` and `enabled:false`; the response is the new one | admin; read keys `403` |
| `DELETE /api/key-events/:id` | — | `{ok:true}`. Turns it off (definitions are kept; counts stay readable with `include=all`) | admin; read keys `403` |
| `POST /api/key-events/:id/backfill` | `{days? (30 default \| 7), earlier? (kept for compatibility: every run continues back from backfill_from, so nothing already counted is counted again)}` | `202 {key_event}` with `backfill_state:"pending"`. `span`/`autocapture` only (else `400`). `429 {error:"backfill_limit", limit:5, retry_after}` past 5 per organisation per UTC day | admin; read keys `403` |
| `POST /api/key-events/preview` | `{app_id, matcher}` | `{valid, error?, summary?, estimate: {count_7d, matched:[{label, count_7d}]} \| null}`. No analytics read: the estimate evaluates the matcher against the route list stored with the app's last suggestions and the event catalogue; `null` when neither exists yet | read, people only (read keys `403 read_key_not_allowed`) |
| `GET /api/key-events/suggestions` | `app` | `{suggestions: SuggestionSet \| null, requests_today, limit: 3}` | read, people only |
| `POST /api/key-events/suggest` | `{app_id, refresh?}` | `{suggestions, cached, requests_today, limit: 3}`. A set computed in the last 24 h is returned (`cached:true`) without a read or a count unless `refresh`. Otherwise at most 3 per app per UTC day (`429 {error:"suggest_limit", limit:3, retry_after}`), and the on-demand rules apply (`503 analytics_paused {can_force}`, `413 too_broad`). The optional AI pass runs only when `KEY_EVENT_SUGGEST_MODEL` is `"true"` (its ship value), the organisation's AI processing is on and an AI credit is charged; otherwise `used_model:false` with `model_skipped` (`ai_off`, `credits`, `disabled` or `error`) and pattern suggestions only. Nothing is enabled: each suggestion must be created with `POST /api/key-events` | write, people only |
| `GET /api/key-events/journeys` | `app` | `{journeys:[{id, name, steps, window_seconds, enabled:false, suggested_by, created_at}]}` | read |
| `POST /api/key-events/journeys` | `{app_id, name, steps (2–10 key-event labels), suggested_by?}` | `201 {journey}`, stored turned off (funnels arrive later) | admin; read keys `403` |

`SuggestionSet` = `{computed_at, used_model, model_skipped?, key_events:[{name, label, source, matcher, evidence, count_7d, reason ("pattern"|"model"), pattern?, already_defined}], journeys:[{name, steps, reason}], catalogue:{routes:[{http_method, http_route, service_name, count, ok, client_errors, server_errors}], events:[{event_name, source}]}}`. The AI pass sees route templates, methods, the 2xx/4xx/5xx mix, counts and event names only (no ids, content or query strings).

**Matcher grammar v1.** `{ "v": 1, "source": "span"|"event"|"autocapture", "all": [{ "field", "op", "value" }] }`. Fields: `span` — `http_route`, `http_method`, `span_name`, `service_name`, `span_kind`, `status_class` (`2xx`–`5xx`), `is_error` (`0`/`1`); `event` — `event_name`, `feature`, `surface`, `action`, `outcome`; `autocapture` — `event_name`, `target`, `url_path`, `surface`. Operators `eq`, `in` (≤ 20 values) and `prefix` (a literal prefix); `status_class` and `is_error` take `eq`/`in` only. 1–6 clauses, AND only, each field once, values ≤ 256 characters. A `span` matcher needs `http_route` or `span_name`. No regular expressions, negation, OR, attribute fields or time conditions. No caller text ever reaches a query: values travel only as bound parameters.

### Events catalogue

Product events are stored as their own rows while `PRODUCT_EVENTS_MATERIALIZE` is `"true"` (its ship value); Activity reads them when they cover the window (`PRODUCT_EVENTS_READS`, ships `"auto"`).

| Method & path | Body / params | Returns | Access |
|---|---|---|---|
| `GET /api/events/catalogue` | `app` | `{events:[{event_name, source, status (visible\|hidden\|merged), display_name, merged_into, first_seen, last_seen}], cap: 500, property_rules:[{property, rule (allow\|deny)}], budget:{daily_budget, today:{events, dropped_budget, dropped_names, dropped_attrs}, by_source:[{source, events, dropped_budget, dropped_names, dropped_attrs}]}}`. `daily_budget` is 200,000 when the app never set one | read; read keys allowed |
| `PATCH /api/events/catalogue/:name` | `app` (query); `{status?, display_name? (≤ 80, null clears), merged_into? (another event of the app; required with status merged)}` | `{event}`. Display only: stored events are never rewritten | admin; read keys `403` |
| `PUT /api/events/property-rules` | `{app_id, rules:[{property ([A-Za-z0-9_.-]{1,64}), rule}] (≤ 100)}` | `{property_rules}`; replaces the app's whole set. With no rules, SDK events keep the client's allow-list and automatic capture keeps only its contract fields; with rules, only `allow` properties are kept | admin; read keys `403` |
| `PUT /api/events/budget` | `{app_id, daily_budget (integer 1,000–5,000,000)}` | `{daily_budget}` | admin; read keys `403` |
| `GET /api/events/volume` | `app`, `days?` (≤ 90, default 30) | `{days:[{day, events, dropped_budget, dropped_names, dropped_attrs}]}` summed over senders, zero-filled | read; read keys allowed |

Over the daily budget, automatic capture is dropped first, then SDK events; key events Heystack derives and connector events are never dropped. The budget is checked against a count up to 60 s old, so it is soft by about a minute of traffic.

### People, accounts and profiles

All routes below need a person or key holding `read` unless noted. `app` is the app id; an app-scoped read key is pinned to its app. Names follow the rules in [Security](https://heystack.dev/docs/security#the-names-boundary).

**Additions to existing people reads.** `GET /api/users`, `GET /api/users/{userId}`, `GET /api/sessions` and `GET /api/sessions/{sessionId}` gain:

- `profiles`: `{ [userId]: {id, display_name?, email?, avatar_url?, account?:{id, name?}, plan?} }`, empty for a read key, or when no app on the page shows names. `email` is present for organisation admins only. When the same id is named differently by two apps on the page, it is left out of `profiles`.
- `profiles_by_app` (`GET /api/users` and `GET /api/sessions` without `app`, when the page spans several apps): `{ [appId]: { [userId]: ProfileRef } }`, exactly the names each app shows. Name a row of one app from its own app's entry, so an app with names off (or whose ids mean someone else) never shows another app's name.
- `names_shown`: `true` when names are on for the page and the caller is a person.
- `GET /api/users` also gains `accounts` (`{ [accountId]: name }`) and each user row gains `account_id` (or `null`). With names on, `q` also matches names and, for admins, emails (one extra read, at most 200 matching ids).
- `GET /api/users/{userId}` gains `linked_devices` (devices linked to this person in the last 30 days, at most 50; their anonymous activity is included). An erased person is `404`.
- An erased person never appears in any of these lists; a visit of theirs shows no user id.
- App Care synthetic traffic (`is_synthetic = 1`: the `Heystack-Care/` user agent, the `x-heystack-synthetic` request header, or a registered Care test identity) is left out of people, visits and everything built on them. Metrics, traces and logs still include it.

| Method & path | Params | Returns | Access |
|---|---|---|---|
| `GET /api/accounts` | `app?`, `window` (`1h`/`24h`/`7d`, default `24h`), `q?` (≤ 256; matches the account id), `limit?` | `{accounts:[{account_id, app_ids, users, requests, errors, sessions, first_seen, last_seen}], truncated, names:{[accountId]: name}, names_shown, window}`. Users join an account by `heystack.account.id` on their data or, for people whose data carries none, by the account on their profile (at most 1,000 people). `names` is empty for a read key or with names off | read; on-demand |
| `GET /api/accounts/{accountId}` | `app?`, `window`, `limit?` | `{account:{id, name?, plan?}, users:[…as /api/users], truncated, risky_capped, totals:{users, requests, errors, sessions, last_seen}, profiles, names_shown, window}` | read; on-demand |
| `GET /api/profiles` | `app` (required), `kind` (`user` default, or `account`), `ids` (csv, at most 100, each ≤ 256) | `{profiles:{[id]: ProfileRef}, accounts:{[accountId]: name}, names_shown}`; names only when the app shows them; email for admins only. Cached 5 minutes per server instance. `400 too_many_ids` / `bad_id` / `bad_kind` / `app_required` | people only: a read key is `403 {error:"forbidden", reason:"read_key_not_allowed"}`; on-demand |
| `DELETE /api/apps/{id}/users/{userId}` | — | `{erased:true, already, effect}`; repeating it is harmless (`already:true`). No analytics read. Also forgets the person in every people-data connection (and suppresses their Stripe customers and email there) and deletes their export files. From then on their traces, logs, metrics, replay chunks and gateway-routed AI calls are dropped at ingest, and security decisions are stored without their user id | admin; a read key is `403` |
| `POST /api/apps/{id}/users/{userId}/export` | — | `201 {id, state:"ready", expires_at, bytes, events, events_truncated, download}`; `429 {error:"rate_limited", reason:"export_daily_limit", limit:2}`; `409 {error:"erased"}` | admin; on-demand |
| `GET /api/apps/{id}/user-exports/{exportId}` | — | the export as `application/x-ndjson` (an attachment). Line 1 is `{type:"export", …}`, then `profile` (one per source), `link` (devices, at most 500), `event` (at most 5,000, last 30 days) and one `activity` line (7-day summary). `410 {error:"expired"}` after 7 days | admin |

Explore: `account_id` is a new filter and facet field for traces and logs (`account.id` in search). Audit labels: `app.end_user.erase`, `app.end_user.export`.

### People data connectors

The customer's own Clerk, Stripe and Supabase, connected per app (see [People data](https://heystack.dev/docs/connectors)). D1 only; no analytics compute. Switch: `CONNECTORS_ENABLED` (on only when exactly `"true"`, its ship value). With any other value, `POST /api/connectors`, confirm, backfill and the bulk upload answer `503 {error:"connectors_disabled"}`; webhooks answer `503`; backfill pages stop and keep their cursor; reads still work.

All routes need a signed-in person (session, OAuth or PAT). A read key gets `403 {error:"forbidden", reason:"read_key_not_allowed"}` on every route here. Reads need `read`; every change needs `admin` (`403 {error:"forbidden", reason:"admin_required"}`). Credentials, signing secrets and the webhook token are write-only: no answer ever contains them, except the one-time `webhook` object on create and rotate.

**Profile cap.** Each app holds at most **200,000** imported profiles across all its connections and the bulk profile API together. An import that reaches the cap stops with `backfill.state: "capped"`; a request that would go past it (a backfill restart or a bulk upload) answers `409 {error:"profile_cap_reached", cap:200000}`.

| Method & path | Scope | What it does |
|---|---|---|
| `GET /api/connectors?app=<id>` | read | `{enabled, names_shown, connectors[], providers[]}`. Each connector: `id, app_id, provider (clerk\|stripe\|supabase), status (pending\|active\|error\|disabled), has_credential, has_webhook_secret, config {project_url?}, key_events_enabled, backfill {state (none\|running\|done\|error\|capped), profiles_synced, profiles_matched, match_rate (Stripe only, else null), cap}, last_event_at, last_error_code, created_at, updated_at`. `providers[]` lists each provider's webhook events and key events. 404 for another organisation's app |
| `GET /api/connectors/:id` | read | `{connector}` plus `names_shown` |
| `POST /api/connectors` | admin | Body `{app_id, provider, credential, project_url?}`. The key's form is checked (`400 invalid_credential` with a message: Clerk `sk_live_`/`sk_test_`; Stripe restricted `rk_live_`/`rk_test_` only; Supabase `service_role` JWT or `sb_secret_`, and `project_url` must be `https://<20-char ref>.supabase.co`), then one read call to the provider (`400 credential_rejected`; `503 provider_unavailable` when it doesn't answer). `409 connector_exists` for a second connection of the same provider on one app. `201 {connector, webhook: {url, events, secret_header?, secret?}}`: the webhook object is shown once (`secret_header`/`secret` for Supabase only, which Heystack generates). Starts `pending` |
| `PATCH /api/connectors/:id` | admin | Any of `credential`, `project_url` (re-validated with the provider; an `error` connector becomes `active`), `webhook_secret` (`whsec_…`; `400 invalid_webhook_secret`; refused for Supabase), `key_events_enabled` (`409 key_event_limit` past 50 enabled key events for the app), `enabled` (`disabled` ⇄ `active`) |
| `POST /api/connectors/:id/confirm` | admin | Body must be `{show_names: true}` (`400 names_ack_required`). Needs a signing secret (`409 webhook_secret_required`). Sets `active`, switches the app's "Show people's names" on, starts the import |
| `POST /api/connectors/:id/backfill[?resume=1]` | admin | Restarts the import, or resumes it from its cursor (after `error`, or with `resume=1` while running). `409 connector_not_active`, `409 backfill_running`, `409 profile_cap_reached`, `503 queue_unavailable` |
| `POST /api/connectors/:id/webhook-url` | admin | New webhook address (and a new Supabase header secret); the old one stops working. `{webhook}` shown once |
| `DELETE /api/connectors/:id` | admin | Deletes the key, the webhook token, the match index and received-event ids, and turns the connection's key events off. Imported profiles stay (erase or hide names in Privacy) |
| `POST /webhooks/connectors/:token` | none (signature) | Provider webhooks. Pre-auth per-IP limit; an unknown token or a bad signature is `401` and counts as a failed sign-in attempt (`429` once over). Clerk: Svix headers, 5-minute tolerance. Stripe: `Stripe-Signature`, 300 s tolerance. Supabase: header `x-heystack-webhook-secret`. Body ≤ 512 KB (`413`). Replayed provider event id: `200 {ok:true, duplicate:true}`. Unknown event type: `200 {ok:true, ignored:true}`. Before confirm: `200 {ok:true, stored:false, reason:"not_confirmed"}` (only `last_event_at` is recorded). A provider outage while handling: `503` and the event id is released so the provider's retry is processed |

**Bulk profiles.** `PUT /api/apps/:id/profiles` — admin (session or PAT with `admin`); read key `403 read_key_not_allowed`. Body `{profiles: [{id, kind?: "user"|"account", display_name? (≤128), email? (≤254), avatar_url? (https), account_id?, plan? (≤64), traits? (≤20 keys, ≤2 KB), deleted?: true}]}`. ≤ 1,000 profiles (`413 too_many_profiles`) and ≤ 1 MB (`413`) per call. The first bad entry is named: `400 {error:"invalid_profile", index, field, reason}`; unknown fields are refused. Rows are written with `source = 'api'`; `deleted: true` writes a tombstone. Erased people are skipped. New profiles count toward the app's 200,000 cap: an upload that would pass it is refused whole with `409 {error:"profile_cap_reached", cap:200000}`. Answer `{accepted, skipped_erased}`. D1 plus queued appends only. Audit labels: `connector.create|update|confirm|backfill|webhook_rotate|delete`, `profiles.bulk_upsert`.

### SDK configuration

`GET /v1/config` (available from SDK 0.20.0) is one document that tells an SDK what to capture: kill switches, session replay, autocapture (page views, clicks, form submits, web vitals and the other kinds) with sampling and caps, the consent requirement, event-property and identity-trait allow-lists, capture rules and the plan's quota state. The full field list and defaults are in the client contract (`docs/contracts/client-contract-v1.md` §1). Switch: `SDK_CONFIG_ENABLED` (ships `"true"`).

- **Auth:** `Authorization: Bearer <ingest key>`, any key class (`sk_live_`, `hs_web_`, `hs_ios_`, `hs_android_`).
- **Request headers:** `X-Heystack-SDK: <name>/<version>; cap=<n>; entry=<entry>` (sent by 0.20.0), optional `If-None-Match`.
- **Answers:** `200` with the document, `ETag` and `Cache-Control: private, max-age=<≤ 300>`; `304` when unchanged; `401` for a bad key; `503` with `Retry-After` while the endpoint is switched off.
- **Browsers:** CORS is open to any origin (the key is the credential). `X-Heystack-SDK` is an allowed request header, and `ETag` and `Retry-After` are readable from the page on every browser path (`/v1/config`, `/v1/replay/config`, `/v1/traces`, `/v1/logs`, `/v1/replay`), error answers included.
- **What a new app gets:** everything off and nothing killed. Nothing turns a capture feature on for an existing app except an admin's change in Settings › App › Data (or `PUT /api/apps/:id/sdk-config`).
- **When it cannot be read:** a client keeps its last good document for up to 24 hours, then falls back to safe defaults (tracing on, replay and autocapture off). **A kill switch stays in force** through that fallback until a fresh document says otherwise, so a device that was offline for a day does not start up un-killed.
- If the server cannot read the app's settings it answers the last document it composed for the app (kills and privacy settings included), and the default document only when it has none.

Older SDKs (0.19.x) keep reading `GET /v1/replay/config`, which is unchanged; the Data settings write the same replay row, so they follow the same replay and browser-tracing switches.

**`GET` / `PUT /api/apps/:id/sdk-config`** — the app's stored SDK settings and what `/v1/config` serves it.

- `GET` (any reader of the app; an app-scoped read key sees its own app): `{ app_id, revision, updated_at, updated_by, overrides, document, clients, capable }`. `clients` lists the SDK name, entry, version and capability last seen for the app; `capable` is true once an SDK that reads `/v1/config` (0.20.0 or later) has been seen.
- `PUT` (admins only; a read key is `403 read_key_not_allowed`): `{ overrides, revision? }`. `overrides` replaces the stored settings as a whole: read them first, change what you need and send everything back. Unknown keys are kept as sent. The five `replay` fields are written to the app's replay settings (the row `/v1/replay/config` serves). `rules`, `quota`, `v` and `revision` cannot be set (`400`). A field with the wrong type is `400 {"error":"invalid_config","field","reason"}`; a stale `revision` is `409 {"error":"revision_conflict","revision"}`; a change whose resulting document would break the contract (over 32 KB) is `400 {"error":"invalid_config","field":"overrides"}`. Capture rules compiled from autocapture key events stop at 100 rules or 12 KB, whichever comes first.

**Operator overrides: `/api/operator/sdk-overrides`** (operators only). For a defective SDK release. `POST { sdk_name, version_min?, version_max?, patch, reason }` adds a patch that applies to every app whose SDK (from `X-Heystack-SDK`) matches the name and the inclusive semver range. A patch may only switch things **off**: `kill.<k>: true`, `autocapture.enabled: false`, `autocapture.kinds.<kind>.enabled: false`. `GET` lists them; `PATCH /:id { enabled }` switches one off or back on. Changes reach clients within about a minute plus their refresh interval. Admins of an organisation listed in `HEYSTACK_OPERATOR_ORG_IDS` only.

### JSON forms for identify and feedback

`POST /v1/identify` and `POST /v1/feedback` (available from SDK 0.20.0) are for callers without an OpenTelemetry stack (mobile recipes, `curl`). Same meaning and the same stored rows as the OTLP events `heystack.identify` and `ai.feedback`. Switches: `IDENTIFY_ENABLED`, `FEEDBACK_ENABLED` (both ship `"true"`).

- **Auth:** any ingest key class. Body JSON, at most 16 KB; unknown fields are ignored.
- `POST /v1/identify` `{ user_id, device_id?, session_id?, account_id?, traits?, account_traits?, event_id? }`. Traits are flat maps of at most 20 values; only the traits the app allows are stored, and only while the app's "Accept traits sent by the SDK" setting is on.
- `POST /v1/feedback` `{ rating: "up"|"down", score?, comment?, reason?, trace_id?, span_id?, conversation_id?, user_id?, session_id?, device_id?, account_id?, event_id?, time_unix_ms? }`; `trace_id` or `conversation_id` is required.
- **Answers:** `202 {"ok":true}`; `400 {"error":"invalid","field":"<field>"}`; `401`; `413`; `429` (the plan's quota answer, or an ordinary rate limit); `503` with `Retry-After`. When the app has switched the capability off (`kill.identify`, or `kill.events` for feedback) the call is accepted and nothing is stored.

```bash
curl -X POST https://ingest.heystack.dev/v1/feedback \
  -H "Authorization: Bearer $HEYSTACK_KEY" -H "Content-Type: application/json" \
  -d '{"rating":"down","reason":"wrong_answer","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}'
```

### Source maps

`POST /api/sourcemaps?service=&version=&build=&path=&debug_id=` (available from SDK 0.20.0) uploads **one** version-3 source map per request so browser errors show your original code. Server ingest key (`sk_live_…`) only. Switch: `SOURCEMAPS_ENABLED` (ships `"true"`; any other value and the upload answers `503` and symbolication returns `no_map`).

- `path` (required): the generated file the map describes, relative to the site or bundle root; 1–512 characters, no whitespace, `?`, `#`, `\` or `..` segment. At least one of `build`, `version` (as in `POST /api/deploys`) or `debug_id` (a UUID); `service` optional.
- Body: the map as `application/json`, optionally `Content-Encoding: gzip`, **at most 20 MB** compressed and 20 MB decoded.
- Checked in this order: key class (`403`; an unknown or revoked key is `403` too, since the contract has no `401` here), parameters (`400`), headers (`400`), size (`413`), then the map (`400`). `201 {accepted:1, skipped:0, id}`; `200 {accepted:0, skipped:1, id}` when an identical map already exists for that key; `413` also when over 500 maps per release or 2 GB per app; `429` rate limited; `503` with `Retry-After`. Error bodies are informational; clients key on the status.
- Idempotent on `(app, debug_id)` when a debug id is sent, else `(app, build or version, path)`: an interrupted upload is resumed by re-posting.
- **Retention.** Heystack keeps the maps of each app's newest 20 releases and removes older ones; symbolicated stacks are kept for 30 days. Maps are private to your organisation and never served to a read key.
- **Where they are used.** The first exception events of a trace (`GET /api/traces/:traceId/events`), the issue brief's top frames and the MCP trace tools show symbolicated frames when a matching map exists.

### Cloudflare AI Gateway logs

`POST /v1/gateway-logs/cloudflare` (ingest path) takes Cloudflare AI Gateway Logpush as NDJSON. Each record becomes one stored AI call. Set-up: [AI gateways](https://heystack.dev/docs/ai-gateways#logpush).

- **Auth:** a server ingest key (`Authorization: Bearer sk_live_…`; Logpush's HTTP destination sends it as `?header_Authorization=Bearer%20…`). A browser key (`hs_web_…`) is `403`, and so is a read key or any `/api` credential. Failed auth counts as a failed sign-in attempt, as on `/v1/traces`.
- **Limits:** the per-tenant ingest rate limit applies (`429`). Body ≤ 5 MB on the wire and after gunzip (`413`); `Content-Encoding: gzip` is accepted. ≤ 5,000 records per upload (`413 too many records: maximum 5000`).
- **Errors:** a line that is not a JSON object is `400`, and nothing from that upload is stored. Blank lines are skipped. Error bodies use the OTLP JSON `Status` shape of `/v1/traces`.
- **Stored:** one CLIENT span per record, with gateway `cloudflare_ai_gateway`; provider and requested/served model; the reported cost (`gen_ai.usage.cost`); status, `cached`, `rate_limited` and latency (`duration_ms` = `Metrics.durationMs`). The consumer is `Metadata.heystack_consumer`, else `Gateway`. `is_error` when status ≥ 400 or rate limited. `ai_flags` bit 64 (gateway-feed row).
- **Not stored:** tokens (Logpush has none), request and response bodies (encrypted by Cloudflare; never read), other `Metadata` keys.
- **Dedup:** Logpush has no record id, so trace and span ids are the SHA-256 of [Gateway, Timestamp, Endpoint, Provider, RequestedModel, Model, StatusCode, Metrics.durationMs, Metrics.cost, Cached, RateLimited, RoutingDecisionID]. A re-delivered file merges on the stored identity; two distinct calls equal on every field collapse into one.
- **Other behaviour:** never sampled. Consumer routing (consumer labels mapped to apps, same tenant only) applies as it does on `/v1/traces`, and so does the app's gateway spend source (see [AI gateways](https://heystack.dev/docs/ai-gateways#spend-counting-each-call-once)).

### Privacy controls

Two per-app switches, applied at ingest **before anything is stored**. Your SDK keeps sending what it sends; Heystack removes the fields on arrival. Both default to keeping what the app sends (the SDKs already capture neither prompts nor visitor addresses unless you turn that on).

| Switch | When off, removed from every span, log, event and crash row |
|---|---|
| `ai_content` (prompt and completion text) | Every prompt and completion attribute (`gen_ai.prompt`, `gen_ai.completion`, `gen_ai.input.messages`, `gen_ai.output.messages`, the Vercel AI SDK's `ai.prompt` and `ai.response.*`, OpenInference and OpenLLMetry input and output values), and the body of a `gen_ai.*` message event. Model names, token counts and timings stay |
| `visitor_network` (visitor address and location) | Client and peer addresses, `geo.*` and Cloudflare visitor location attributes, forwarded-for style request headers, and the address and location columns. The user agent stays |

Values are not pattern-matched: an address or prompt written inside a log message, an exception message or a custom attribute outside these families is kept. If the setting cannot be read, both fields are removed.

The same settings (`GET`/`PUT /api/apps/:id/privacy`, [above](#apps-keys--configuration)) hold the app's people and gateway choices:

- `show_names` ("Show people's names") lets names and avatars from your sign-in provider reach your team; emails go to admins only. Connecting a people-data connector switches it on.
- `sdk_traits_enabled` ("Accept traits sent by the SDK") stores `identify()` and `group()` traits; off, they are dropped before storage.
- `gateway_spend_source` decides which side counts when this app reports its own AI calls **and** receives an AI gateway's records for the same calls: `app` counts the app's calls and sets the gateway's records aside; `gateway` counts the gateway's records and sets aside the app's own calls to that gateway's host. `null` (the default) sets nothing aside, which suits the recommended set-up where the gateway sends to an app of its own. Set-aside calls are kept but not counted in calls, tokens or spend. See [AI gateways](https://heystack.dev/docs/ai-gateways#spend-counting-each-call-once).

## Usage, plans and billing

Every organisation is on a plan: **Free**, **Pro**, **Team**, **Enterprise** (custom limits) or **Early access** (organisations that existed before plans; no event limit). Usage is counted per calendar month (UTC).

| Plan | Events / month | Session replays | AI credits | Apps | Alert rules | On-demand lookups / day |
|---|---|---|---|---|---|---|
| Free | 1,000,000 | 100 | 10 | 1 | 3 | 40 |
| Pro ($29) | 10,000,000 | 1,000 | 100 | 5 | 20 | 150 |
| Team ($99) | 50,000,000 | 10,000 | 500 | no limit | 100 | 300 |
| Early access | no limit | no limit | 500 | no limit | 20 | 400 |

**What counts.** An *event* is one stored span or log record (tracked product events are log records). Metrics, span events and links are not counted. A *session replay* is counted once, when its first chunk is stored. An *AI credit* is one model call made for you: a trace explanation, an Ask answer that uses the model, an automatic investigation, an issue narrative or suggested fix, or a repair summary. A daily ceiling of 50 AI credits per organisation applies on every plan as a runaway guard.

### `GET /api/org/usage`

Any member (`read` scope). A read key gets `403 {error:"forbidden", reason:"read_key_not_allowed"}`. Served from stored counters only: it never runs an analytics query and is not subject to the analytics pause.

```json
{
  "plan": "free", "plan_name": "Free",
  "period": { "key": "2026-11", "start": "2026-11-01T00:00:00.000Z", "end": "2026-12-01T00:00:00.000Z" },
  "limits": { "events_month": 1000000, "replay_sessions_month": 100, "ai_credits_month": 10, "apps": 1, "alert_rules": 3, "analytics_queries_day": 40 },
  "usage": { "events": 912345, "replay_sessions": 12, "ai_credits": 3 },
  "would_reject": 0,
  "by_app": [{ "app_id": "app_…", "name": "Shop", "events": 912000, "errors": 41, "crashes": 0, "replay_chunks": 96, "product_events": 310 }],
  "quota_state": { "events": "warn", "replay_sessions": "ok", "ai_credits": "ok", "period_end": "2026-12-01T00:00:00.000Z" },
  "quota_computed_at": "2026-11-17T10:05:00.000Z",
  "analytics": { "used_today": 12, "share": 40, "level": "normal" },
  "mode": "observe",
  "billing_enabled": false
}
```

`quota_state` is `ok` below 80% of a limit, `warn` from 80% and `over` at the limit. It is recomputed every five minutes, so it can lag usage by that much. `mode` is how limits are applied: `observe` counts and warns but never refuses (`would_reject` is how many uploads would have been refused this month); `enforce` refuses; `off` does neither. Counters are delivered with the data they count, so a figure can trail by up to a minute.

### The quota response (`429 quota_exceeded`)

In `enforce` mode, an upload to `/v1/traces`, `/v1/logs`, `/v1/metrics` or `/v1/replay` from an organisation over its event limit (or, for `/v1/replay`, its session-replay limit) is answered before the body is read:

```
HTTP/1.1 429 Too Many Requests
Retry-After: 3600

{"error":"quota_exceeded","signal":"events","limit":1000000,"period_end":"2026-12-01T00:00:00Z","upgrade_url":"https://console.heystack.dev/settings/org/billing"}
```

`Retry-After` is the number of seconds until the period ends, capped at one hour. Early-access organisations are never refused. A refusal does not count against the failed-authentication budget. The organisation's state is read from a cache that refreshes within about a minute, so an organisation can go a little over its limit before uploads are refused, and is accepted again as soon as the new period starts or the plan changes.

In `enforce` mode the write routes also apply the plan's count limits: creating an app or an alert rule over the limit is `403 {error:"forbidden", reason:"plan_limit", limit, plan, resource}` (`resource` is `apps` or `alert_rules`), and a model call over the AI-credit allowance is `429 {error:"quota_exceeded", signal:"ai_credits", reason:"quota_exceeded", limit, period_end, upgrade_url}` with `Retry-After`. Each organisation also has a daily ceiling of AI credits in every mode (50 by default, whatever the plan); reaching it answers the same body with `reason:"daily_ceiling"` and `period_end` at the next UTC midnight. One credit is used per AI answer, only when the model is actually asked: trace explanations, Ask lookups, issue summaries and suggested fixes refuse with this `429`; the automatic check (`POST /api/investigations/auto` with `include_ai`) and incident investigations still answer with their evidence and no AI-written summary (the automatic check adds the warning `ai_credits_exhausted` or `ai_daily_ceiling`). A downgrade never deletes anything: apps and rules over the new limit stay readable and working, and only new ones are refused.

### Billing

| Route | Who | Notes |
|---|---|---|
| `GET /api/org/billing` | Admin; read key `403` | `{plan, plan_name, billing_enabled, subscription: {status, cancel_at, has_customer} \| null, prices: {pro, team}, can_manage}` |
| `POST /api/org/billing/checkout` | Admin, **console session only** (`403 session_required` for tokens) | Body `{plan: "pro" \| "team"}` → `{url}` of a hosted checkout page. `409 already_subscribed` when a subscription exists (change plans in the portal). |
| `POST /api/org/billing/portal` | Admin, console session only | → `{url}` of the hosted billing portal (card, invoices, cancel, change plan). `409 no_customer` before the first checkout. |

Both `POST` routes answer `503 {error:"billing_disabled"}` until paid plans open. Payment details are entered on the payment provider's hosted pages and never reach Heystack. The plan changes only when the payment provider confirms the subscription, usually within a minute of checkout. When a subscription ends (cancelled, or unpaid after the provider's retries), the organisation moves to Free.

### Analytics pause scope

Each organisation also has a daily share of on-demand lookups (the last column above). The share is applied once it's switched on for your workspace; until then lookups are counted (and reported in `tenant`) but never paused for it. The share counts lookups people and agents make (the console, MCP and the shared Home and Issues summaries); alert checks, digests and App Care checks Heystack runs for you never count toward it. When an organisation has used its whole share for the day, on-demand reads answer `503 {error:"analytics_paused", reason:"tenant_share", scope:"tenant", can_force}` for that organisation only; an admin may retry with `force=1`, as for the platform-wide pause (`reason:"budget"`), which is always checked first. `GET /api/analytics-budget` reports the platform level as before, plus your organisation's own `tenant: {used, share, level}`. While your organisation is at `elevated` or above, Home and Issues summaries are reused three times longer before they are refreshed.

### `GET /api/operator/tenants`

Heystack operators only (an admin of an organisation listed in `HEYSTACK_OPERATOR_ORG_IDS`; everyone else `403`). `?period=YYYY-MM` (default: this month) → `{period, tenants: [{tenant_id, plan, subscription_status, events, replay_sessions, ai_credits, would_reject, analytics: {total, families}, quota_state}]}`, at most 500 rows, busiest first. Stored counters only.

## Audit log

`GET /api/audit` (admins, `admin` scope; a read key gets `403 admin_required`) records two kinds of row:

- **Every call made by a coding agent, an access token, an OAuth client or a read key**, reads included. A console session call that sends `X-Heystack-Agent` counts as an agent call.
- **Every change a person makes in the console**: each `POST`, `PUT`, `PATCH` or `DELETE` under `/api/`. Their reads, and a few high-volume calls that change nothing for others (`POST /api/query/sql`, `POST /api/ask`, the journaling calls, opening a notification, drafting an issue's story or suggested fix), are not recorded.

Changes carry `action`, a stable name such as `member.remove`, `read_key.create`, `org.settings.update` or `investigation.share` (`other` for a route without a name yet), and `target`, the id the change applied to (`null` when there isn't one). `path` never includes the query string. Rows are kept for 365 days.

Filter with `action`, `actor` (a user id, or `key:<id>` for a read key) and `auth`; unknown values are `400`. `format=csv` returns `text/csv` as an attachment (`heystack-audit-YYYY-MM-DD.csv`) with the same filters, at most 10,000 rows, newest first. A cell that starts with `=`, `+`, `-`, `@`, a tab or a carriage return is prefixed with `'` so a spreadsheet shows it as text.

## Organisation settings

| Method & path | Body | Returns | Access |
|---|---|---|---|
| `GET /api/org/settings` | — | `{ai_processing, public_shares, updated_at, updated_by, public_shares_available, org_deletion_available}` | read (people only) |
| `PATCH /api/org/settings` | `{ai_processing?: boolean, public_shares?: boolean}` (anything else is `400`) | the settings, as above | admin |
| `GET /api/org/viewers` | — | `{user_ids:[…]}`: the members held to read-only | read (people only) |
| `PATCH /api/org/members/:userId/viewer` | `{viewer: boolean}` | `{user_id, viewer}`. `404` when the user isn't a member, `409 admin_cannot_be_viewer` for an admin, `502 directory_unavailable` when the member list can't be checked | admin |

Both switches are on for a new organisation. `*_available` says whether the deployment offers public links and organisation deletion at all; when it doesn't, the matching routes answer `503`.

**`ai_processing`.** Off, Heystack sends nothing from this organisation to an AI model. `GET /api/traces/:id/explain` and the AI path of `POST /api/ask` answer `403 {error:"forbidden", reason:"ai_processing_disabled"}` before reading any data. `POST /api/investigations/auto` and incident investigations still answer, with the evidence they found and no AI-written summary (`narrative.status: "unavailable"`, warning `ai_processing_disabled`). Rules, alerts and issue briefs are not affected.

**Read-only members.** A member held to read-only gets role `org:viewer` and only the `read` scope from every credential: the console, OAuth agents, and their access tokens (an existing token keeps `minted ∩ read`). Writes answer `403 {error:"forbidden", reason:"scope_required", scope:"write"}`. The hold takes effect within a minute everywhere, and lifts when it is released or the person leaves the organisation. If the read-only list can't be checked, members (not admins) are treated as read-only for that request.

## Deleting an organisation

| Method & path | Body | Returns | Access |
|---|---|---|---|
| `DELETE /api/org` | `{confirm: "<organisation name>"}` | `202 {state, deleted_at}` | admin, console session only |
| `GET /api/org/deletion` | — | `{state: "none" \| "pending" \| "purging" \| "completed" \| "failed", deleted_at, completed_at}` | admin |

`confirm` must equal the organisation's name (surrounding spaces ignored); otherwise `400 confirm_mismatch`. An access token, OAuth agent or read key gets `403 session_required`.

From the moment the deletion is requested, every credential of the organisation (console sessions, access tokens, OAuth agents and read keys) gets `410 {error:"organization_deleted"}` on every `/api` route except `GET /api/org/deletion`, so nothing can be written while it is removed. Other servers notice within a minute: each checks for deleted organisations at most once every 60 seconds, so for up to 60 s a request handled elsewhere may still be served for the deleted organisation. If that check cannot read its database, it fails open (the server keeps the list it had and tries again a few seconds later) rather than refusing every request. Both are by design.

Deletion stops intake at once (ingest keys stop working), cancels a paid plan, then removes every app, key, read key, access token, alert rule, channel, investigation, share, journey and setting, and finally the organisation and its memberships. Telemetry already received is unreadable from that moment and expires on its normal schedule (30 days; 90 for AI safety decisions). A small record that the organisation was deleted, billing records and legal acceptances are kept, as required to account for them.

## Legal acceptance

| Method & path | Body | Returns | Access |
|---|---|---|---|
| `GET /api/me/legal-acceptance` | — | `{current:{terms, privacy}, accepted:[{doc, version, accepted_at}]}` | console session |
| `POST /api/me/legal-acceptance` | `{doc: "terms" \| "privacy", version}` | `201 {doc, version, accepted_at}`; recording the same version again returns the first record | console session |

`version` must be the current one (`400 unknown_document` otherwise). Other credentials get `403`. The console asks for acceptance only once the legal documents are published at heystack.dev; until then it records nothing.

## Sharing an investigation

| Method & path | Body | Returns | Access |
|---|---|---|---|
| `POST /api/investigations/:id/shares` | `{expires_in_days?: 1–30}` (default 7) | `201 {share, token, url}` | write (not read keys) |
| `GET /api/investigations/:id/shares` | — | `{shares:[{id, investigation_id, created_by, created_at, expires_at, revoked_at, views, last_viewed_at, active}]}` | write (not read keys) |
| `DELETE /api/investigations/:id/shares/:shareId` | — | `{share}`; `403 not_share_owner` unless you created it or are an admin | write (not read keys) |
| `GET /share/i/:token` | — | the shared copy | anyone with the link |

The `token` is shown once; Heystack keeps only its hash. Creating a link answers `503 public_shares_unavailable` where the deployment doesn't offer them and `403 public_shares_disabled` when the organisation has switched them off.

A share is a **frozen copy** made when the link is created: the title, question, summary, status, possible causes and steps (at most the latest 1,000, and 512 KB; the oldest pictures and then the oldest steps are left out first, and the copy says so). It holds no data that a read key couldn't see, no member ids or names, no links into the console, and no app ids, issue keys or trace ids. Tables are kept only from tools whose columns are fixed (search, metrics, AI usage, overview, issue list); any other table, such as a SQL result or a grouped breakdown, is left out and marked as omitted, because a renamed column could hide data a read key can't see. Opening a link never runs a query.

`GET /share/i/:token` answers the same `404 {error:"not_found"}` for an unknown, expired or revoked link and while the organisation's switch is off, and is rate limited per address (`429`). Responses are `Cache-Control: private, no-store`, `X-Robots-Tag: noindex, nofollow` and `Referrer-Policy: no-referrer`.

### Event notifications

When something happens to an app (a new issue, an issue getting worse, a fix that held or regressed, a journey going down, an approval waiting, a spike in blocked AI requests, a quota reached), Heystack sends one message per subscribed [notification channel](#notification-channels). Events are detected from Heystack's own records, never from an extra analytics query. Each event is delivered at most once per channel: a repeat of the same event (for example a retried detection) is ignored. Delivery is retried with backoff for up to five attempts; anything still undelivered after 24 hours is dropped. To keep noise down a workspace receives at most **50** event deliveries per UTC day in total (every delivery to every channel or person counts once) and at most **10** about any one issue; past either cap the rest are kept as `suppressed`, and each channel that had something held back gets one "more activity in Heystack today" message. Alert rules are not capped. Every link in a message opens the console page for that event and carries `nid=<delivery id>`, which the console reports back once (see `opened` below).

Event notifications are available once they're switched on for your workspace, and the weekly summary and setup-tip emails once those are. Until then channels, subscriptions and preferences can be set, but nothing is sent. `GET` and `PUT /api/notifications/subscriptions` and `GET` and `PUT /api/notifications/prefs` carry `event_notifications_available` and `weekly_digest_available` (booleans) so you can say so.

Which events go where is set per app, with organisation-wide defaults (`app_id: ""`); an app row overrides the organisation-wide row for the same event and channel. A workspace's first channel starts subscribed to: new issue, issue back, fix verified, fix regressed, journey down, journey recovered, approval waiting and quota reached.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `GET /api/notifications/subscriptions` | `app?` (omit for organisation-wide rows only) | `{subscriptions:[{app_id, event_kind, channel_id, enabled, params}], event_kinds:[{kind, label, description, scope: "app" \| "org", default_on}], event_notifications_available, weekly_digest_available}` | read (people) |
| `PUT /api/notifications/subscriptions` | `{app_id ("" = all apps), event_kind, channel_id, enabled, params?: {threshold_per_hour (1–100000)}}` — `threshold_per_hour` is used by `safety_block_spike` (default 20); unknown kind or channel `400`, unknown app `404`. Leaving `params` out keeps the stored threshold (switching a subscription on or off doesn't erase it); `params: null` clears it | `{subscription, event_notifications_available, weekly_digest_available}` | admin |
| `GET /api/notifications/prefs` | — | `{prefs:{event_email, assigned_email, weekly_digest, lifecycle_email}, weekly:{enabled, weekday (0 = Sunday), hour_utc}, email, email_verified, event_notifications_available, weekly_digest_available}` — the caller's own switches; the weekly summary is on by default for the organisation's owner only (Mondays 22:00 UTC) | session only (`403 session_required`) |
| `PUT /api/notifications/prefs` | any of `{prefs:{…booleans}, weekly:{enabled?, weekday?, hour_utc?}}` | same shape as `GET` | session only |
| `GET /api/notifications/outbox` | `app?`, `limit` (1–200, default 50) | `{deliveries:[{id, app_id, event_kind, channel_id, channel_name, channel_kind, title, status: "pending" \| "sending" \| "sent" \| "failed" \| "suppressed" \| "expired", attempts, created_at, sent_at, opened_at, last_error}]}` — titles only, never message bodies or destinations | admin |
| `POST /api/notifications/:id/opened` | — | `{ok:true}`; `404` | session (people) |

Event kinds: `issue_new`, `issue_worse` (the last full hour has at least 10 events and at least 3× the previous 24-hour average; at most once per 6 hours), `issue_back`, `issue_assigned` (emailed to the assignee only), `fix_verified`, `fix_regressed`, `journey_down`, `journey_recovered`, `approval_waiting`, `safety_block_spike`, `alert_fired`, `alert_resolved`, `quota_warning`, `quota_reached`, `analytics_paused`, `ai_budget_threshold` and `ai_budget_forecast` (organisation AI budgets; nothing sends these two until AI budgets are available, and an organisation's first channel is subscribed to them by default). A new issue waits two minutes before it is announced, and a failing operation needs at least five failures in the last hour. Issues you marked ignored are never announced.

**Email.** Email goes only to confirmed addresses. A workspace member whose sign-in email is verified is confirmed at once; anyone else receives a confirmation email and gets nothing else until they click it (links last 7 days). Every email has a one-click unsubscribe link (`List-Unsubscribe` and `List-Unsubscribe-Post`) and a link to your email preferences. Unsubscribing from a channel's email stops that list for that address; unsubscribing from a personal email (assignments, the weekly summary, setup tips) turns that switch off in your preferences.

**Read keys** get `403 read_key_not_allowed` on every route in this section: subscriptions and the outbox describe delivery configuration, and preferences belong to a person.

### Notification channel kinds and recipients

Channels can be `slack`, `generic` (any HTTPS endpoint, signed with `X-Heystack-Signature`), `discord`, `teams`, `email` or `pagerduty`. Discord URLs must be `https://discord.com/api/webhooks/…` (or `discordapp.com`); Teams URLs must be a Teams Workflows or incoming-webhook URL (`*.webhook.office.com`, `*.logic.azure.com`, `*.environment.api.powerplatform.com`). Every URL also passes the same public-address checks as before, at save time and at delivery time. A PagerDuty channel stores an Events API v2 integration key (32 characters), encrypted; responses show only its last four characters. PagerDuty events open on a firing event and resolve on the matching recovery. An email channel holds up to **10** addresses.

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/notification-channels` | `{name, kind?, url?, recipients?, routing_key?}` — `kind` defaults from the URL (`slack` or `generic`); `discord`/`teams` need `url`; `email` needs `recipients` (1–10 addresses); `pagerduty` needs `routing_key` | `201 {channel}`; `400 invalid_kind` / `invalid_url` / `invalid_recipients` / `invalid_routing_key`; `503 email_not_configured` / `encryption_unavailable` | admin |
| `PATCH /api/notification-channels/:id` | any of `{name, url, routing_key}` (`url` only for URL kinds, `routing_key` only for PagerDuty) | `{channel}` | admin |
| `POST /api/notification-channels/:id/recipients` | `{email}` | `201 {recipient:{id, email, user_id, status: "verified" \| "pending" \| "unsubscribed", verify_sent_at, created_at}}`; `409 recipient_exists`; `409 recipient_limit` | admin |
| `DELETE /api/notification-channels/:id/recipients/:rid` | — | `{ok:true}`; `404` | admin |
| `POST /api/notification-channels/:id/recipients/:rid/resend` | — | `{recipient}`; `429` within 10 minutes of the last confirmation email | admin |

Channel objects gain `disabled_at`, `used_by.subscriptions` and, for email channels, `recipients`. `destination_hint` is `Routing key …abcd` for PagerDuty and `N addresses` for email. Test messages (`POST /:id/test`) work for every kind; a PagerDuty test opens and then resolves one event.

The public links in emails are `GET /n/verify?t=…` and `GET /n/unsubscribe?t=…` on `ingest.heystack.dev`. Both show a page with a button, and only the button's `POST` acts, so a mail scanner that opens links cannot confirm or unsubscribe anyone. Mail providers' one-click unsubscribe `POST`s directly. These routes take no other credential and are rate limited per IP address.

### Team triage: assignment, bulk changes and comments

| Method & path | Params / body | Returns | Access |
|---|---|---|---|
| `POST /api/inbox/:issueKey/triage` | gains `assignee_user_id` (a member's user id, or `null` to unassign); sending it with the free-text `assignee` is `400` | per-field results gain reason `not_a_member` | write |
| `POST /api/inbox/triage/bulk` | `{issue_keys (1–50), status?, assignee_user_id?, snoozed_until?}` | `{results:[{issue_key, field, ok, reason?}]}` — the same rules as single triage, per issue | write |
| `GET /api/inbox` | gains `assignee=me \| none \| <user_id>` and `sort=rank \| last_seen \| first_seen \| impact`; every issue gains `assignee_user_id` | — | read (a read key gets `assignee_user_id: null`, and `403 read_key_not_allowed` if it sends `assignee`) |
| `GET /api/inbox/:issueKey/comments` | — | `{comments:[{id, author, author_name, author_kind: "user" \| "agent", body, created_at, edited_at, can_edit}]}` (newest 200, oldest first) | read (people) |
| `POST /api/inbox/:issueKey/comments` | `{body}` (plain text, 1–4000 characters) | `201 {comment}`; `400 invalid_body` | write (people) |
| `PATCH /api/inbox/:issueKey/comments/:id` | `{body}` | `{comment}`; `403 not_author` | write (people; the author, or an admin) |
| `DELETE /api/inbox/:issueKey/comments/:id` | — | `{ok:true}` | write (people; the author, or an admin) |

Assigning an issue to someone else emails them (if their email is verified and they have not turned assignment emails off). Comments on security findings follow the findings rule: admin only. Read keys get `403 read_key_not_allowed` on every comment route.

### Alert rule types

`POST`/`PATCH /api/alert-rules` also accept `type: "crash_rate"` (crashes per hour, averaged over the window; fires above `threshold`) and `type: "no_data"` (fires when the app sends nothing for the whole window; `threshold` is ignored; checked by the hour, so it can fire up to an hour late but never early). Both take only `window: "1h" | "6h" | "24h"` (`400 invalid window` otherwise, also on `PATCH`) and are read from Heystack's own hourly counters, not from analytics queries. Rules gain `window_label` (for example "over the last hour"). A rule can point at a channel of any kind; email, PagerDuty, Discord and Teams deliveries go through the event delivery queue above.

Four more types are read from Heystack's own daily or hourly counters, never from analytics queries:

- `key_event_rate`: `threshold` is a drop percentage (0–100); window `24h` only. Optional `key_event_id` (one of the app's key events; `400` otherwise) watches that key event; without it the value is the largest known drop among the app's enabled key events. The drop is the `usage_drop` comparison (yesterday's complete UTC day against the same weekday over the previous 4 weeks). Editing a key event's matcher moves its rules to the new version. The rule never fires while the baseline is below 50 events or unknown.
- `ai_failure_rate` (%, windows `1h`/`6h`/`24h`) and `ai_flagged_rate` (%, same windows): no value below 30 answers in the window.
- `ai_daily_spend` (USD for the current UTC day, window `24h`).

A window a type does not take is `400 invalid window` on `POST` and on `PATCH`.

## Rate limits

Every read has a bounded time window and response size. Read keys are limited to **120 requests per minute per key** on the API itself (`429` + `Retry-After: 60`), and the MCP server adds a per-token limit of 300 requests per minute. AI-backed endpoints (`/explain`, natural-language search, investigate) and `POST /api/query/sql` carry tighter execution budgets than plain reads. Poll no faster than every 30 seconds — new telemetry becomes queryable in batches of roughly that cadence anyway, so tighter loops only burn your budget.

## Examples

**Is my app healthy right now?**

```bash
curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" \
  "https://ingest.heystack.dev/api/metrics/red?app=app_123&window=1h" | jq '.routes[] | select(.error_rate > 1)'
```

**New exceptions in the last 24 hours**

```bash
curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" \
  "https://ingest.heystack.dev/api/issues?app=app_123&window=24h&limit=10"
```

**Pull one failing trace with its logs**

```bash
TRACE=$(curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" \
  "https://ingest.heystack.dev/api/example-trace?app=app_123&route=/api/chat&prefer=error" | jq -r .trace.trace_id)
curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" "https://ingest.heystack.dev/api/traces/$TRACE"
curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" "https://ingest.heystack.dev/api/logs?app=app_123&trace=$TRACE"
```

**Fail a CI job if the error rate crossed 2% after a deploy**

```bash
RATE=$(curl -s -H "Authorization: Bearer $HEYSTACK_TOKEN" \
  "https://ingest.heystack.dev/api/telemetry/summary?app=app_123&window=15m" \
  | jq '(.errors / (.total | if . == 0 then 1 else . end)) * 100')
awk -v r="$RATE" 'BEGIN { exit (r > 2) ? 1 : 0 }'
```

**Create an alert rule**

```bash
curl -X POST https://ingest.heystack.dev/api/alert-rules \
  -H "Authorization: Bearer $HEYSTACK_TOKEN" -H "Content-Type: application/json" \
  -d '{ "app": "app_123", "name": "Checkout errors", "type": "error_rate", "threshold": 5, "window": "15m", "webhook_url": "https://hooks.slack.com/…" }'
```

**Errors by service and release** (a read key works for every read here)

```bash
curl -s "https://ingest.heystack.dev/api/logs?service=my-api&severity=ERROR&cf=service_version:1.8.2&window=6h" \
  -H "Authorization: Bearer $HEYSTACK_READ_KEY"
```

**A user's logs** — everything that mentions an end-user id in the last day:

```bash
curl -s "https://ingest.heystack.dev/api/logs?q=enduser.id:usr_42&window=24h" \
  -H "Authorization: Bearer $HEYSTACK_READ_KEY"
```

## Handing a human a console link

When an agent finds something worth a human's eyes, give them a link straight into the console. The console keeps its whole view in the URL, so these open exactly the right place:

- **An app's traces, last hour:** `https://console.heystack.dev/explore/traces?app=<app id>&w=1h`
- **A specific request, with one step selected:** `https://console.heystack.dev/explore/traces/<trace id>?app=<app id>&span=<span id>`
- **Errors for a release in Logs:** `https://console.heystack.dev/explore/logs?app=<app id>&w=24h&f=severity_text:ERROR&f=service_version:1.8.2`
- **A visit (session replay):** `https://console.heystack.dev/sessions/<session id>?app=<app id>`

The window `w` accepts `15m`, `1h`, `6h`, `24h`, `7d` and `30d`. The full list of pages and parameters is in [Linking into the console](https://heystack.dev/docs/deep-links). Links in the older `/apps/<app id>?tab=…` form still work and are listed there under "Older links".

Prefer a conversational interface? Every endpoint here is also an [MCP tool](https://heystack.dev/docs/mcp#tool-reference).

### Outcome check details

Journey `assertions` supports `body_contains` (`value`, optional `case_sensitive`), `json_path_equals` (`path`, scalar `value`), `content_type` (`value`), and `max_latency_ms` (`value`, 100–30000). Maximum 10 assertions; body and JSON checks require GET. The response body is bounded to 64 KiB and is not retained.

Alternatively, `browser_steps` accepts up to 12 `click` (`selector`), `fill` (`selector`, `value`), `expect_text` (`text`, optional `selector`), and `expect_url` (`path`) steps, with at least one expectation. HTTP assertions and browser steps are mutually exclusive. `browser_allowed_origins` allows up to five additional public origins. Use disposable test data; fill values are not a secret store.

| Route | Body | Result | Scope |
| --- | --- | --- | --- |
| `GET /api/care/apps/:id/journeys/:journeyId/runs` | — | `{runs}`; latest 20 assertion results | read |
| `POST /api/care/apps/:id/safe-launch` | `{preview_url,journey_ids}`; 1–5 journeys | `{id,preview_origin,decision,checks}`; production status unchanged; browser checks with extra production origins return unknown | write |
| `GET /api/care/apps/:id/security/findings` | — | `{repository,scanned_at,sources}`; each source is available with up to 10 sanitized findings, `open_numbers` (every open alert number, up to 1000), `dropped` (alerts that could not be used) and `truncated` (more than 1000 open, or a page failed), or unknown with a reason | admin |
| `POST /api/care/apps/:id/security/findings/scan` | — | Scans the connected GitHub repository now and updates the saved findings: `{scanned_at,repository,status,open,last_error}`. A source GitHub could not answer stays `unknown` and never closes findings. `last_error: "not_configured"` means no recovery workflow is connected; a GitHub or recovery-service failure other than an unavailable service answers `200` with `last_error: "github_unavailable"` (saved findings are kept); `last_success_at` is the last scan that reached GitHub; `429 scan_too_soon` (with `Retry-After`) within 60 s of the last scan, including a scan still running; `503` when the recovery service is unavailable | admin |
| `GET /api/care/apps/:id/security/findings/state` | — | `{state}`: the last scan of the saved findings (`null` before the first scan): `scanned_at`, `repository`, `status` per source (`available`, `unknown`, `not_configured`), `open` (saved open findings), `capped` per source (`true` when more alerts are open on GitHub than are saved, because Heystack keeps up to 10 per source, some could not be used, or the listing was cut short; `open` is then a lower bound), `last_error` and `last_success_at`. The scan route returns the same shape. Reads only saved data. Findings are scanned daily | admin |

Source repair parameters may include `allowed_source_files` (1–10 safe repository-relative source files) for managed draft-PR preparation. Protected paths, new dependencies and network calls, likely secrets, and edits outside the allowlist are rejected. Release, approval, trusted-workflow, immutable-head, and verification fences still apply.


## Product monitoring

`GET /api/monitoring/:section`, where section is `services`, `usage`, `features`,
`events`, `users`, `sessions`, `experience`, `problems`, `network` or `security`. Requires read scope through the common read gate;
app-scoped read keys cannot broaden scope. Parameters: `app`, `service`,
`window=1h|24h|7d` (default 24h), and exact `event`, `feature`, `surface`, `user`,
`session` filters. `errors=1` narrows activity to error-severity events. Other windows fall back to 24h (read-key limits still apply).

`events` and `experience` also return `profiles` (`{[userId]: ProfileRef}`), `profiles_by_app` (when the page spans
several apps; name each row from its own app's entry) and `names_shown` for the people on the page: one profile read at most, none for a read key, with names off or with no people (email for admins only).

Activity supports `q` (bounded text search), exact `environment`, `release` and
`outcome=started|succeeded|failed|cancelled`. Services additionally support
environment/release through on-demand bounded reads; default service monitoring
uses rollups. Security uses app/user/session/time only,
not service or feature, because security records do not have a service column.
Activity aggregate/event sections apply those activity filters. Returns `{ rows, truncated,
window }`, up to 100 services/events/decisions, 50 event-feature-surface or identity groups,
or one usage aggregate. `network` is people-only (`403 read_key_not_allowed` for a read key), and a read key's `events`, `experience` and search results carry no IP, geo, user-agent or end-user profile attributes (every `user.*`, `enduser.*` and `heystack.user.*` attribute except the id keys `user.id`, `enduser.id` and `heystack.user.id`), and a key cannot filter or group by them. Security records retain enforcement vs shadow status.
Requests use a tenant-and-parameter-scoped 60-second cache, a 10-second execution
cap and tightened ClickHouse scan limits (Tinybird uses its supported execution, memory and thread caps); failures return 502, never zero-filled success.

Usage reports named-event counts, distinct nonempty users/sessions, identified,
session-linked and trace-linked event counts, explicitly tagged product events,
errors and last-seen time. Counts cover received records and may include retries.
The events response includes app/service, event, user/session/trace, release,
feature, surface and outcome for exact investigation pivots. No new storage or
migration is required. Existing logs promote record-scoped user/session identity
before resource fallback; old stored records are not rewritten.

`experience` analyses the latest 10,000 explicit product events, deduplicating
`event.id` per app inside that snapshot. It returns coverage, up to 100 observed
screen connections, 50 feature-outcome groups, 50 impact groups and 100 matching
events. `pathFrom` plus `pathTo` selects sessions with that exact observed edge;
search/outcome filters select events within those sessions. It does not infer
missing transitions, conversion, abandonment or anonymous identity merges.
`truncated` reports a capped input snapshot. These counts can differ from raw
aggregate counts, which include retries and legacy named events.

`problems` returns up to 50 failing operations ranked by identified users affected,
with app/service/time/environment/release/user/session and text-search filters.
Product feature, outcome and path filters do not apply. `network` requires `ip`
and returns up to 10 observed geography/ASN groups from traces for that address,
scoped by app/service/time/environment/release. It performs no external lookup.

The read-only advanced MCP tool `heystack_monitor_product` exposes the product
analysis and investigation sections with the same authorization boundaries.


Security decision cursors are opaque navigation state, not authorization. Keep all
filters and page size unchanged when submitting one. Tenant/app scope is always
revalidated from authentication. Read keys cannot request more than seven days;
all cursors expire after 24 hours. The response range is anchored across pages,
but late arrival and replacement/retention can change rows. Refresh without a
cursor to include newly received reviews. No exact total or snapshot-export
completeness is implied. Invalid limits, filters or cursors return HTTP 400;
analytics failure returns HTTP 502 rather than empty history.

### Ask release verification (coordinated release)

`POST /api/security/policies/:id/versions/:version/evaluate-release` requires
admin authority and returns a persisted `id`, `passed`, check results,
`detector_version`, `corpus_version` and `evidence: server_local_regression`. It answers `409 minimum_unavailable` when the organisation policy this one inherits is unsigned or no longer verifies; publish that one again first.
Pass its ID as `evaluation_id` to publish or roll back. Tests bind the exact saved
configuration and inherited activation, expire after one hour and are rejected
with 409 if stale, failed or mismatched. This finite regression gate does not
replace the representative quality corpus or real-client acceptance.

`POST /api/security/verifications` requires admin authority and accepts only
`app_id`, `deployment_environment`, `release`, `profile`, `turn_id`, `outcome`
(`allowed`, `redacted`, `denied`, `cancelled`), `client_build`, explicit
`client_observed: true`, `billing_checked: true`, and an optional
`issue_fingerprint`. Identifiers are bounded to 160 characters. No prompt or
answer field is accepted. The server independently reads the last seven days of
bounded turn evidence and rejects incomplete, wrong-scope, wrong-outcome or stale
policy evidence with 409. The turn must belong to a feature that the release
**declared** for that profile (latest declaration of the environment and release),
and a completed `allowed` or `redacted` turn must have receipts for every inspected
boundary of that feature whose surface produces receipts (answer text is `caption`,
speech input `tts`, model request `provider_request`, tool action or result `tool`,
context `context`, voice consent `rights`). A feature with no such boundary, or one
the release never declared, cannot be verified. The console applies the same rule
(`canVerifyFeatures`, shared in `@heystack/insights`).

A verification tied to an issue (`issue_fingerprint`) must also prove **that issue's surface**: the turn's
feature must declare and inspect the surface, and the turn must have reported its receipt boundary. The
map is `output` → `caption`, `tts_input` → `tts`, `tool_action`/`tool_result` → `tool`, `context`, `voice_rights` → `rights`,
`provider_request`, and the input side (`input`, `post_stt`, `batch_input`) → `provider_request`. A surface with
no receipt boundary (`provider_response`, `batch_output`, raw audio, embeddings) cannot be verified from a turn
yet. A refusal is a 409 with a `reason`: `surface_unverifiable`, `surface_not_declared` or `surface_not_reported`.
The console shows that reason and offers no form for such an issue. This holds for every outcome, `cancelled` included: a cancelled turn must carry the surface's receipt, so cancel after the step the issue is about has happened.

A verification records the operator's attestation; it cannot observe
client playback itself. When a linked issue matches, recording and resolution
are atomic; false-positive fixes require an allowed result.

`GET /api/security/verifications?app=...&deployment_environment=...&release=...`
returns at most 20 records and a truncation flag. `current_policy` describes the
policy at read time. Older verification remains historical after any environment
activation change. App and tenant restrictions apply to all reads and writes.

Release declarations, read by the console's AI & Safety › Releases page, come from
D1 and never touch analytics storage. `POST /api/security/manifests` requires admin
authority and takes one strict declaration (`schema_version: 1`, `app_id`,
`deployment_environment`, `release`, `revision`, and 1 to 64 `features`, each with
`id`, `name`, `profile`, `owner_id` and `boundaries`). It answers 201 for a new
declaration, 200 for an identical one, `409 release_manifest_conflict` when the same
release and revision already hold different content, `400 invalid_feature_manifest`
and `413 manifest_too_large` above 64 KB. `GET /api/security/manifests?app=...` lists
the latest 50 declarations (optionally `deployment_environment=`), `GET
/api/security/manifests/{digest}?app=...` returns one, and `GET
/api/security/manifests/{digest}/adoptions?app=...` returns what runtimes reported
for it, with a `freshness` and an `activation` (`latest`, `behind` or `unknown`) for
each reporter. A declaration is intent and a report only says a policy was loaded;
neither shows that a request was checked.
