{
  "openapi": "3.1.0",
  "info": {
    "title": "Agent Analytics API",
    "version": "1.0.0",
    "x-api-versioning": {
      "strategy": "header",
      "name": "AA-Version",
      "in": "header",
      "current": "1",
      "required": false,
      "default": "1",
      "paths": "stable",
      "deprecationWindowDays": 90,
      "deprecationHeaders": [
        "Deprecation",
        "Sunset"
      ],
      "policyUrl": "https://docs.agentanalytics.sh/reference/api-versioning/",
      "changelogUrl": "https://docs.agentanalytics.sh/reference/release-notes/",
      "hosted": {
        "enforced": true
      }
    },
    "description": "Web analytics platform with an HTTP API that AI agents can query.\n\n**Docs:** [Home](https://docs.agentanalytics.sh) · [Getting Started](https://docs.agentanalytics.sh/getting-started/) · [Installation](https://docs.agentanalytics.sh/installation/) · [API Reference](https://docs.agentanalytics.sh/api/) · [API versioning policy](https://docs.agentanalytics.sh/reference/api-versioning/) · [OpenAPI YAML](https://docs.agentanalytics.sh/openapi.yaml) · [OpenAPI JSON](https://docs.agentanalytics.sh/openapi.json)\n\n**Sandbox / test environment:** the public read-only demo project `agentanalytics-demo`. The sandbox base is `https://api.agentanalytics.sh/sandbox`. `GET` that URL for the descriptor. `POST https://api.agentanalytics.sh/sandbox/demo/session` returns a short-lived read-only session, then reads stay under that base. A real API key on the sandbox base returns `403`. Writes return `403` `DEMO_READ_ONLY`. See [Sandbox](https://docs.agentanalytics.sh/sandbox/) and [CLI sandbox](https://docs.agentanalytics.sh/reference/cli/#sandbox).\n\n**Quick start:**\n\n1. Start an agent session with `POST /agent-sessions/start` or sign in on the dashboard.\n2. Create a project with `POST /projects`.\n3. Add the returned tracker snippet to your site.\n4. Query analytics with `GET /stats`.\n\n**Authentication:**\n\n- `aas_*` agent sessions are the primary machine-auth mechanism for CLI, MCP, and managed runtimes. The owner grants one level (`read`, `manage`, or `admin`) and one project, or All projects.\n- `aapk_*` project keys belong to one project, carry a level (`read`, `manage`, or `admin`), and may set `expires_at`. Create, list, and revoke them only from a dashboard login. The secret is shown once and stored hashed. An agent session cannot create one.\n- `aak_*` account keys remain a fallback for direct HTTP users. They can no longer erase. `POST /erasures` and `GET /erasures` return `403` `FORBIDDEN_SCOPE` with message `account API key cannot erase; use a project key or agent session with manage or admin`.\n- `aat_*` project tokens are public and used for ingestion only.\n- A dashboard session cookie keeps full owner access, including erasure. `ADMIN_API_KEY` is unchanged and is never accepted as a customer credential.\n\n**Levels:** `read` is `account:read`, `projects:read`, `analytics:read`, `experiments:read`, `live:read`, `replays:read`. `manage` adds `projects:write`, `experiments:write`, `feedback:write`, `replays:write`, `erasures:write`. `admin` is `manage` plus account-level management sessions already have, such as creating projects. Agent sessions still cannot create, rotate, or reveal API keys, and cannot touch billing checkout. Erasure needs `manage` or `admin`. `read` receives `403` `FORBIDDEN_SCOPE` on `GET /erasures` and `POST /erasures`.\n\n**Project grant:** the owner picks exactly one project or All projects. `project` null means all projects. A project-limited caller sees only that project in `GET /projects` and in any list. A route that names another project returns `404` `PROJECT_NOT_FOUND`, not `403`, including query, compare, funnel, paths, errors, vitals, live, replays, experiments, erasures, and sql. Portfolio and cross-project reads, and email portfolio erasure, stay inside the granted project. Creating a project needs `admin` and All projects.\n\n**Legacy sessions:** sessions with no level keep their stored scopes and all-projects access. Session info reports `level` `legacy`.\n\n**API versioning policy:** the API version token is `1`. `info.version` (`1.0.0`) is the OpenAPI document version, and its major matches that token. Send the optional header `AA-Version: 1`, or omit the header. Omitting it means version `1`. Existing paths keep their current names.\n\nA breaking change makes a call that works today fail, or changes the meaning of a field, an error code, or an enum value a client already reads. Adding an optional request field, a response field, or a new path is backward compatible. Removing or renaming a path or a response field is a breaking change. Making an optional request field required is a breaking change. Tightening authorization so an accepted call starts failing is a breaking change.\n\nA breaking change ships as a new version token only after a deprecation window of at least 90 days. During that window the previous behavior stays available. Responses that use the retiring behavior include a `Deprecation` header (the HTTP-date the deprecation started) and a `Sunset` header (the HTTP-date that behavior stops). The changelog is the release notes: https://docs.agentanalytics.sh/reference/release-notes/. The policy page is https://docs.agentanalytics.sh/reference/api-versioning/.\n\nThe hosted API enforces `AA-Version` on read and management routes. Every response includes `AA-Version: 1`. Omitting the header, or sending a blank value, selects version `1`. Any other value is `400` `UNKNOWN_API_VERSION`. Ingest, tracker, beacon, collect, and replay-recording routes ignore the request header and still respond with `AA-Version: 1`. Nothing is deprecated, so responses do not send `Deprecation` or `Sunset`. `Access-Control-Allow-Headers` does not list `AA-Version`, so a browser on another origin cannot send it.\n\nInstallation guides for Claude Code, Claude Desktop / Cowork, Cursor, and ChatGPT (Codex) now live in the docs site instead of this OpenAPI intro block.\n",
    "contact": {
      "email": "support@agentanalytics.sh",
      "url": "https://agentanalytics.sh"
    },
    "license": {
      "name": "MIT",
      "url": "https://github.com/Agent-Analytics/agent-analytics/blob/main/LICENSE"
    }
  },
  "servers": [
    {
      "url": "https://api.agentanalytics.sh",
      "description": "Production (hosted)"
    },
    {
      "url": "https://api.agentanalytics.sh/sandbox",
      "description": "Sandbox and test environment. Public read-only demo project agentanalytics-demo.\nNo account and no API key. GET this base for the sandbox descriptor.\nPOST https://api.agentanalytics.sh/sandbox/demo/session mints a short-lived read-only session, then reads stay under this base.\nA real API key on this base returns 403. Writes return 403 DEMO_READ_ONLY.\nDocs: https://docs.agentanalytics.sh/sandbox/\n",
      "x-sandbox": {
        "method": "post",
        "url": "https://api.agentanalytics.sh/sandbox/demo/session"
      }
    }
  ],
  "x-sandbox": {
    "method": "post",
    "url": "https://api.agentanalytics.sh/sandbox/demo/session",
    "description": "Read-only sandbox for project agentanalytics-demo.\nPOST this URL with an empty JSON body. No account and no API key.\nThe response is a short-lived read-only agent session. Access lasts 15 minutes.\nLater reads stay under https://api.agentanalytics.sh/sandbox.\nA real API key on that base returns 403.\nWrites with that session return 403 DEMO_READ_ONLY.\nGuide: https://docs.agentanalytics.sh/sandbox/\n"
  },
  "tags": [
    {
      "name": "Ingestion",
      "description": "Event tracking endpoints called by the browser `tracker.js` script. These use a public project token (`aat_*`) — not your API key. You don't call these directly; the tracker handles it."
    },
    {
      "name": "Analytics",
      "description": "Query analytics data. Requires account auth. Agent-session bearer auth is preferred; API keys remain a supported fallback."
    },
    {
      "name": "Session Replay",
      "description": "Explicitly opt in projects, list linked replay metadata, create short-lived viewer links, inspect usage, and delete retained recordings. Pro or complimentary access only."
    },
    {
      "name": "Projects",
      "description": "Manage projects programmatically. Requires account auth. Agent-session bearer auth is preferred; API keys remain a supported fallback. A project-limited session or project key lists only its granted project. Creating a project needs `admin` and All projects."
    },
    {
      "name": "Project Context",
      "description": "Store compact goals, activation events, event-name glossary entries, and date annotations so agents can interpret analytics results with project-specific meaning. `PUT /project-context` replaces the whole document. `POST /project-context/annotations` appends one annotation."
    },
    {
      "name": "Website Analysis",
      "description": "Product Growth Scanner. Anonymous previews return growth questions, measurement blind spots, and first instrumentation decisions; full analysis and project linking require account auth."
    },
    {
      "name": "Account",
      "description": "Account information and feedback. Agent-session bearer auth is preferred for scoped account reads and feedback; raw API-key management is dashboard-only or API-key fallback only."
    },
    {
      "name": "Erasures",
      "description": "Delete one subject's rows. One subject per request. Available on all plans, including free.\nErasure needs `manage` or `admin`, which include `erasures:write`.\nA dashboard session can erase. A project key (`aapk_*`) can erase at `manage` or `admin`.\nThe legacy account key (`aak_*`) cannot erase.\n`analytics:read` and `projects:write` are not enough.\n"
    },
    {
      "name": "Agent Sessions",
      "description": "Agent-session signup/login, detached approval, refresh, revocation, and account-side session management.\n`POST /agent-sessions/start` accepts optional `project` and `level` (`read`, `manage`, or `admin`). `scopes` still map to the smallest level that covers them. The default level is `read`, and the project picker preselects nothing.\nThe owner grants one project or All projects, and a level, and may grant less or more than requested.\nExchange, refresh, and session info return `level`, `project` (name or null), and expanded `scopes`. Refresh keeps the project and level. Access tokens last 1 hour. Refresh tokens last 30 days.\nLegacy sessions report `level` `legacy` and keep stored scopes and all-projects access.\n"
    },
    {
      "name": "Experiments",
      "description": "A/B testing experiments. Create experiments, assign variants client-side via tracker.js, and query results with Bayesian significance. Pro tier only.\n\n## Declarative Experiments (recommended)\n\nThe simplest way to run experiments — no custom JavaScript needed. Mark elements with HTML attributes and tracker.js handles variant assignment automatically.\n\n### Anti-Flicker Snippet\n\nAdd this in `<head>` **before** the tracker.js script tag to prevent flash of control content:\n\n```html\n<style>.aa-loading [data-aa-experiment]{visibility:hidden!important}</style>\n<script>document.documentElement.classList.add('aa-loading');\nsetTimeout(function(){document.documentElement.classList.remove('aa-loading')},3000)</script>\n```\n\n- Uses `visibility: hidden` to preserve layout (not `display: none`)\n- Only hides `[data-aa-experiment]` elements, not the entire page\n- 3-second timeout fallback shows control content if config fetch fails\n- tracker.js removes the `aa-loading` class after applying variants\n\n### Declarative Attributes\n\n```html\n<h1 data-aa-experiment=\"hero_text\"\n    data-aa-variant-b=\"Try it free today!\">\n  Start your free trial\n</h1>\n```\n\n- Original element content = control variant\n- `data-aa-variant-{key}` attributes provide replacement text for non-control variants\n- Multiple elements can share the same experiment name (same variant assigned to all)\n- Variant keys are lowercased for attribute lookup\n- Requires a server-side experiment config (created via `POST /experiments`)\n\n### Programmatic API\n\nFor complex cases that can't be expressed as text swaps:\n\n```js\nvar variant = window.aa?.experiment('signup_cta', ['control', 'new_cta']);\nif (variant === 'new_cta') {\n  document.querySelector('.cta').style.backgroundColor = 'green';\n}\n```\n\n### URL Param Variant Forcing\n\nForce a specific variant via URL parameter — useful for ad landing pages, QA testing, or sharing a specific variant with teammates.\n\n```\nhttps://yoursite.com/pricing/?aa_variant_signup_cta=new_cta\n```\n\nFormat: `?aa_variant_<experiment_name>=<variant_key>`\n\n- The forced variant must exist in the experiment config — invalid values fall through to normal hash assignment\n- Works with both declarative and programmatic experiments\n- Exposure events include `forced: true` so you can filter them in analytics\n- No URL param = existing hash-based assignment (backward compatible)\n"
    },
    {
      "name": "Funnels",
      "description": "Ad-hoc funnel analysis — track where users drop off across a sequence of events.\nNo saved funnels — agents query in one shot via `POST /funnel`.\n"
    },
    {
      "name": "Paths",
      "description": "Bounded session path analysis from entry pages to goal, drop-off, or truncation.\nBuilt for agent workflows: pages → funnels → retention → experiments.\n"
    },
    {
      "name": "Streaming",
      "description": "Real-time event streaming.\n\n`/stream` and `/live` are Pro-only on hosted cloud. Both read from an in-memory ring buffer — no D1 query.\n"
    },
    {
      "name": "Tracking",
      "description": "Browser tracker delivery endpoint.\n\nFull tracker setup, script attributes, declarative events, consent, and performance options now live in the docs guide:\nhttps://docs.agentanalytics.sh/reference/tracker-js/\n"
    }
  ],
  "components": {
    "securitySchemes": {
      "AgentSessionBearer": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "Agent Session",
        "description": "Agent session bearer token (`aas_*`). Primary auth for CLI, MCP, and managed runtimes.\n"
      },
      "ApiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "Secret key in `X-API-Key`, or `?key=`.\n`aapk_*` is a project key: one project, a level (`read`, `manage`, or `admin`), optional `expires_at`, a label, and `last_used_at`. Created, listed, and revoked only from a dashboard login. Shown once, stored hashed. Several per account. Same level and project enforcement as an agent session.\n`aak_*` is the legacy account key. It still works for the calls it works for today, except erasure. `POST /erasures` and `GET /erasures` return `403` `FORBIDDEN_SCOPE` with message `account API key cannot erase; use a project key or agent session with manage or admin`.\n"
      },
      "ProjectToken": {
        "type": "apiKey",
        "in": "query",
        "name": "token",
        "description": "Public project token (`aat_*`) for event ingestion. Passed in the request body (not a query parameter).\nThis is not a secret — it's embedded in your site's HTML.\n"
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": [
          "error",
          "message"
        ],
        "properties": {
          "error": {
            "type": "string",
            "description": "Machine-readable error code",
            "example": "AUTH_REQUIRED"
          },
          "message": {
            "type": "string",
            "description": "Human-readable error message",
            "example": "API key required"
          },
          "payment": {
            "$ref": "#/components/schemas/PaymentHandoff",
            "description": "Optional commercial guidance on Pro requirements or monthly read exhaustion; agent sessions require account:read for this field."
          }
        }
      },
      "PaymentHandoff": {
        "type": "object",
        "description": "Versioned, read-only commercial guidance for the authenticated account.\nThis is an Agent Analytics contract, not a Personal Agent Protocol compliance claim.\nA handoff URL does not authorize billing or prove payment. Hosted Pro entitlement\nand ready account setup are the completion evidence. Checkout pending does not\ndistinguish an abandoned checkout from payment still processing.\n",
        "required": [
          "version",
          "account_id",
          "state",
          "entitlement_source",
          "billing_status",
          "provider",
          "human_approval_required",
          "agent_can_charge",
          "pricing",
          "next_action",
          "status"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "const": 1
          },
          "account_id": {
            "type": "string"
          },
          "state": {
            "type": "string",
            "enum": [
              "upgrade_available",
              "checkout_pending",
              "active",
              "payment_attention",
              "setup_required",
              "unavailable"
            ]
          },
          "entitlement_source": {
            "type": "string",
            "enum": [
              "free",
              "subscription",
              "complimentary"
            ]
          },
          "billing_status": {
            "type": "string"
          },
          "provider": {
            "type": "string",
            "enum": [
              "lemonsqueezy",
              "dodo"
            ],
            "example": "dodo"
          },
          "human_approval_required": {
            "type": "boolean",
            "const": true
          },
          "agent_can_charge": {
            "type": "boolean",
            "const": false
          },
          "pricing": {
            "type": "object",
            "required": [
              "plan",
              "currency",
              "model",
              "billing_period",
              "unit",
              "events_per_unit",
              "unit_price_cents",
              "rounding",
              "applies_to",
              "excludes"
            ],
            "properties": {
              "plan": {
                "type": "string",
                "const": "pro"
              },
              "currency": {
                "type": "string",
                "const": "USD"
              },
              "model": {
                "type": "string",
                "const": "usage_based"
              },
              "billing_period": {
                "type": "string",
                "const": "monthly"
              },
              "unit": {
                "type": "string",
                "const": "accepted_event"
              },
              "events_per_unit": {
                "type": "integer",
                "example": 10000
              },
              "unit_price_cents": {
                "type": "integer",
                "example": 100
              },
              "rounding": {
                "type": "string",
                "const": "started_units",
                "description": "Zero events costs zero; each started 10,000-event block costs $1."
              },
              "applies_to": {
                "type": "string",
                "const": "subscription",
                "description": "Complimentary Pro access is not a paid subscription."
              },
              "excludes": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "example": [
                  "taxes",
                  "discounts"
                ]
              }
            }
          },
          "next_action": {
            "type": [
              "object",
              "null"
            ],
            "properties": {
              "type": {
                "type": "string",
                "const": "human_browser"
              },
              "url": {
                "type": "string",
                "format": "uri",
                "description": "Agent Analytics account confirmation or billing page, never a payment credential."
              },
              "reason": {
                "type": "string"
              }
            }
          },
          "status": {
            "type": "object",
            "required": [
              "method",
              "path",
              "required_scope",
              "poll_interval_seconds",
              "max_wait_seconds",
              "can_retry_pro_task",
              "completion_evidence"
            ],
            "properties": {
              "method": {
                "type": "string",
                "const": "GET"
              },
              "path": {
                "type": "string",
                "const": "/account/usage"
              },
              "required_scope": {
                "type": "string",
                "const": "account:read"
              },
              "poll_interval_seconds": {
                "type": "integer",
                "const": 5
              },
              "max_wait_seconds": {
                "type": "integer",
                "const": 900,
                "description": "Suggested bounded polling window; timeout does not mean cancellation."
              },
              "can_retry_pro_task": {
                "type": "boolean",
                "description": "Pro entitlement and account setup are ready. The retried route still enforces scopes and request limits."
              },
              "completion_evidence": {
                "type": "string",
                "const": "hosted_entitlement"
              }
            }
          }
        }
      },
      "ProjectContextGlossaryEntry": {
        "type": "object",
        "required": [
          "event_name",
          "term",
          "definition"
        ],
        "properties": {
          "event_name": {
            "type": "string",
            "maxLength": 96,
            "description": "Event name this glossary entry explains. Use `/properties` or `/properties/received` to inspect current project event names before updating.",
            "example": "first_event_received"
          },
          "term": {
            "type": "string",
            "maxLength": 64,
            "description": "Human or product term for the event.",
            "example": "AA Activation"
          },
          "definition": {
            "type": "string",
            "maxLength": 240,
            "description": "Short meaning that helps an agent interpret analytics results.",
            "example": "Signup, project created, and first event received."
          }
        }
      },
      "ProjectContextAnnotation": {
        "type": "object",
        "required": [
          "occurred_at",
          "title"
        ],
        "additionalProperties": false,
        "properties": {
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "description": "ISO-8601 datetime when a major product change happened. Stored as a UTC ISO string.",
            "example": "2026-04-25T13:00:00.000Z"
          },
          "title": {
            "type": "string",
            "maxLength": 120,
            "description": "Short annotation title for a meaningful product, pricing, release, landing-page, onboarding, feature, or experiment change.",
            "example": "Changed pricing page offer"
          },
          "note": {
            "type": "string",
            "maxLength": 500,
            "description": "Optional short note. Do not store commit logs, PII, secrets, or long release notes.",
            "example": "Moved annual plan discount above the fold."
          }
        }
      },
      "ProjectContext": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "goals": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string",
              "maxLength": 160
            },
            "default": [],
            "example": [
              "Increase activated Agent Analytics accounts"
            ]
          },
          "activation_events": {
            "type": "array",
            "maxItems": 8,
            "items": {
              "type": "string",
              "maxLength": 96
            },
            "default": [],
            "description": "Event names that define activation or the main success path.",
            "example": [
              "signup_completed",
              "project_created",
              "first_event_received"
            ]
          },
          "glossary": {
            "type": "array",
            "maxItems": 10,
            "items": {
              "$ref": "#/components/schemas/ProjectContextGlossaryEntry"
            },
            "default": []
          },
          "annotations": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/ProjectContextAnnotation"
            },
            "default": [],
            "description": "Major date annotations. Project-scoped analytics responses include only annotations inside the requested date range plus one day before and after."
          }
        }
      },
      "ProjectContextRequest": {
        "type": "object",
        "required": [
          "project"
        ],
        "additionalProperties": false,
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name or ID.",
            "example": "my-site"
          },
          "goals": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string",
              "maxLength": 160
            },
            "default": [],
            "example": [
              "Increase activated Agent Analytics accounts"
            ]
          },
          "activation_events": {
            "type": "array",
            "maxItems": 8,
            "items": {
              "type": "string",
              "maxLength": 96
            },
            "default": [],
            "description": "Event names that define activation or the main success path.",
            "example": [
              "signup_completed",
              "project_created",
              "first_event_received"
            ]
          },
          "glossary": {
            "type": "array",
            "maxItems": 10,
            "items": {
              "$ref": "#/components/schemas/ProjectContextGlossaryEntry"
            },
            "default": []
          },
          "annotations": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/ProjectContextAnnotation"
            },
            "default": [],
            "description": "Major date annotations. Use sparingly for human-meaningful changes, not git commit logs."
          }
        }
      },
      "ProjectContextResponse": {
        "type": "object",
        "required": [
          "project",
          "project_id",
          "project_context"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "description": "Present on successful updates.",
            "example": true
          },
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_id": {
            "type": "string",
            "example": "proj_123"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          }
        }
      },
      "ProjectContextAnnotationAppendRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "occurred_at",
          "title"
        ],
        "description": "Append one annotation. Allowed fields are `project`, `occurred_at`, `title`, and `note`.\nThe identity of an annotation is the normalized `occurred_at` plus `title`.\n",
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name or ID.",
            "example": "my-site"
          },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "description": "ISO-8601 datetime. Stored as a UTC ISO string.",
            "example": "2026-04-20T15:00:00+03:00"
          },
          "title": {
            "type": "string",
            "maxLength": 120,
            "description": "Required. Trimmed. Max 120 characters.",
            "example": "Shipped landing edit"
          },
          "note": {
            "type": "string",
            "maxLength": 500,
            "description": "Optional. Trimmed. Max 500 characters. An empty note is omitted from the stored object.",
            "example": "Moved the signup form above the fold."
          }
        }
      },
      "ProjectContextAnnotationAppendResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "ok",
          "appended",
          "project",
          "project_id",
          "annotation",
          "annotation_count"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "const": true,
            "example": true
          },
          "appended": {
            "type": "boolean",
            "description": "False when the same normalized `occurred_at` and `title` were already stored. The new note is not written.",
            "example": true
          },
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_id": {
            "type": "string",
            "example": "proj_123"
          },
          "annotation": {
            "$ref": "#/components/schemas/ProjectContextAnnotation",
            "description": "The stored annotation. On a duplicate this is the existing object, not the request."
          },
          "annotation_count": {
            "type": "integer",
            "minimum": 0,
            "maximum": 100,
            "description": "Annotation count after the call. Unchanged when `appended` is false.",
            "example": 2
          }
        }
      },
      "CompareFilter": {
        "type": "object",
        "required": [
          "field",
          "op",
          "value"
        ],
        "description": "Same filter object as `POST /query`. A filter whose `field` is `event` is rejected.",
        "properties": {
          "field": {
            "type": "string",
            "description": "Built-in field (`user_id`, `date`, `country`, `session_id`, `timestamp`) or `properties.<key>`. `event` is not allowed.",
            "example": "country"
          },
          "op": {
            "type": "string",
            "enum": [
              "eq",
              "neq",
              "gt",
              "lt",
              "gte",
              "lte",
              "contains"
            ],
            "example": "eq"
          },
          "value": {
            "description": "Value to compare against.",
            "example": "US"
          }
        }
      },
      "CompareWindowInput": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date_from",
          "date_to"
        ],
        "properties": {
          "date_from": {
            "type": "string",
            "format": "date",
            "description": "Inclusive UTC calendar date, `YYYY-MM-DD`.",
            "example": "2020-06-01"
          },
          "date_to": {
            "type": "string",
            "format": "date",
            "description": "Inclusive UTC calendar date, `YYYY-MM-DD`. Must be on or after `date_from` and on or before today UTC. The window is at most 90 days.",
            "example": "2020-06-07"
          }
        }
      },
      "CompareRule": {
        "type": "object",
        "additionalProperties": false,
        "description": "Optional. Omitted fields use the documented day-7 recipe examples, not product policy:\n`keep_threshold` 0.15, `revert_threshold` -0.1, `min_denominator` 200, `min_goal_events` 20.\nThresholds are relative fractions. `0.15` means +15%.\nAn absolute value above 5 is `400` `VALIDATION_ERROR`.\n`keep_threshold` must be greater than `revert_threshold`.\n`min_goal_events` is the minimum number of unique converters across both windows. The field name is unchanged.\n",
        "properties": {
          "keep_threshold": {
            "type": "number",
            "minimum": -5,
            "maximum": 5,
            "description": "Minimum relative lift to keep, as a fraction. Compared to lift rounded to 6 decimal places. On a conversion-rate compare, keep also requires the 90% rate-difference interval to lie entirely above zero.\nWhen `metric` is set, a lift that meets this threshold is `extend` / `no_interval_for_metric`. v1 does not compute an interval for a metric compare.\nAbsolute value must be 5 or less.\n",
            "example": 0.15
          },
          "revert_threshold": {
            "type": "number",
            "minimum": -5,
            "maximum": 5,
            "description": "On a conversion-rate compare, relative lift at or below this fraction is `revert` only when the 90% interval lies entirely below zero. A drop that does not clear that bar is `extend` / `inconclusive`.\nWhen `metric` is set, a lift that meets this threshold is `extend` / `no_interval_for_metric`.\nAbsolute value must be 5 or less.\n",
            "example": -0.1
          },
          "min_denominator": {
            "type": "integer",
            "minimum": 0,
            "description": "Minimum denominator `unique_users` required in each window.",
            "example": 200
          },
          "min_goal_events": {
            "type": "integer",
            "minimum": 0,
            "description": "On a conversion-rate compare, the minimum number of unique converters across both windows together.\nWhen `metric` is set, this is the minimum numeric values (`n`) on `metric_event` across both windows together, not unique converters.\nThe field name is `min_goal_events`. Default 20.\n",
            "example": 20
          }
        }
      },
      "CompareRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "goal_event"
        ],
        "description": "Allowed fields only: `project`, `goal_event`, `denominator_event`, `filters`, `denominator_filters`, `ship_date`, `window_days`, `baseline`, `compare`, `rule`, `metric`, `metric_event`, `better`.\n\nPass either `ship_date` or both `baseline` and `compare`. Not both, and not `window_days` with explicit windows.\n\nOmit `metric` for the conversion-rate compare. That response is unchanged: Newcombe interval, keep/revert verdicts, and no `metric`, `raw_lift`, `interval_method`, or window `value` / `n` / `skipped`.\n",
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name or ID.",
            "example": "my-site"
          },
          "goal_event": {
            "type": "string",
            "maxLength": 256,
            "description": "Goal event name. Trimmed. Required.",
            "example": "signup"
          },
          "denominator_event": {
            "type": "string",
            "maxLength": 256,
            "default": "page_view",
            "description": "Denominator event name. Trimmed. Defaults to `page_view`.",
            "example": "page_view"
          },
          "filters": {
            "type": "array",
            "description": "Optional `/query` filters applied to both windows. Not applied to traffic mix. Unchanged by `denominator_filters`.",
            "items": {
              "$ref": "#/components/schemas/CompareFilter"
            }
          },
          "denominator_filters": {
            "type": "array",
            "maxItems": 10,
            "description": "Optional. Same `{ field, op, value }` shape as `filters`. Ops are `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, and `contains`.\nApplied only when counting `denominator_unique_users` for `denominator_event` (default `page_view`).\n`goal_converters` still counts only goal users inside that filtered denominator set.\nOmit the field or send `[]` for the unfiltered denominator. At most 10 entries.\nEach `value` must be a string or a number. A bad field, a bad op, a value that is not a string or number, or more than 10 entries is `400` `VALIDATION_ERROR`.\n",
            "items": {
              "$ref": "#/components/schemas/CompareFilter"
            },
            "example": [
              {
                "field": "properties.title",
                "op": "neq",
                "value": "Page not found | grokbotpages.com"
              }
            ]
          },
          "ship_date": {
            "type": "string",
            "format": "date",
            "description": "Ship day, `YYYY-MM-DD` UTC. That day is in neither window.",
            "example": "2020-06-10"
          },
          "window_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 90,
            "multipleOf": 7,
            "default": 7,
            "description": "Length of each ship-date window. Integer from 1 to 90 and a multiple of 7, so the weekday sets match.\nThe longest ship window is 84 days. Defaults to 7. Omit when passing `baseline` and `compare`.\n",
            "example": 7
          },
          "baseline": {
            "$ref": "#/components/schemas/CompareWindowInput"
          },
          "compare": {
            "$ref": "#/components/schemas/CompareWindowInput"
          },
          "rule": {
            "$ref": "#/components/schemas/CompareRule"
          },
          "metric": {
            "type": "string",
            "pattern": "^(sum|avg|p50|p75|p95)\\([A-Za-z0-9_]{1,128}\\)$",
            "description": "Optional. One of `sum(<key>)`, `avg(<key>)`, `p50(<key>)`, `p75(<key>)`, or `p95(<key>)`.\n`<key>` matches `^[A-Za-z0-9_]+$` and is at most 128 characters. An invalid key is `400` `INVALID_PROPERTY_KEY`.\nOmit `metric` to keep the conversion-rate compare.\n",
            "example": "p75(cwv_lcp)"
          },
          "metric_event": {
            "type": "string",
            "maxLength": 256,
            "description": "Event whose property `metric` reads. Defaults to `goal_event`.\nOn hosted, Web Vitals properties are on `page_view`. Self-hosted core stores them on `$web_vitals`.\nSet it when the measured event is not the goal, for example goal `signup` and metric event `page_view`.\n",
            "example": "page_view"
          },
          "better": {
            "type": "string",
            "enum": [
              "higher",
              "lower"
            ],
            "default": "higher",
            "description": "Direction of a good change when `metric` is set. Default `higher`.\nNot inferred from the property name. Set `lower` for `cwv_lcp` and the other Web Vitals.\n",
            "example": "lower"
          }
        }
      },
      "CompareWindowResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date_from",
          "date_to",
          "day_count",
          "denominator_unique_users",
          "goal_unique_users",
          "goal_converters",
          "goal_users_outside_denominator",
          "count_mode",
          "rate"
        ],
        "properties": {
          "date_from": {
            "type": "string",
            "format": "date",
            "example": "2020-06-03"
          },
          "date_to": {
            "type": "string",
            "format": "date",
            "example": "2020-06-09"
          },
          "day_count": {
            "type": "integer",
            "example": 7
          },
          "denominator_unique_users": {
            "type": "integer",
            "example": 2000
          },
          "goal_unique_users": {
            "type": "integer",
            "description": "Distinct users who fired the goal. A user who fires it three times counts once.",
            "example": 200
          },
          "goal_converters": {
            "type": "integer",
            "description": "`min(goal_unique_users, denominator_unique_users)` after `denominator_filters`. Goal users outside that filtered denominator are not converters.",
            "example": 200
          },
          "goal_users_outside_denominator": {
            "type": "integer",
            "description": "Goal users who are not in the denominator set used for `denominator_unique_users`. With no `denominator_filters`, that is goal users who did not fire the denominator event.",
            "example": 0
          },
          "count_mode": {
            "type": "string",
            "const": "unique_users"
          },
          "rate": {
            "type": [
              "number",
              "null"
            ],
            "description": "`goal_converters / denominator_unique_users`, rounded to 6 decimal places. Null when the denominator is 0. At most 1, because `goal_converters` is capped at the denominator. Still returned when `metric` is set.",
            "example": 0.1
          },
          "value": {
            "type": [
              "number",
              "null"
            ],
            "description": "Present when the request set `metric`. The metric for this window on `metric_event`.\nOnly JSON numbers are used. `avg`, `p50`, `p75`, and `p95` are that aggregate.\nPercentiles are nearest-rank: sort ascending, break ties by event id, and take rank `ceil(p/100 * n)` where p is 50, 75, or 95. Rank 1 is the smallest value.\n`sum` is the property sum divided by `denominator_unique_users`. The sum ignores `denominator_filters`. The divisor still uses `denominator_unique_users`, which applies `denominator_filters`.\n"
          },
          "n": {
            "type": "integer",
            "minimum": 0,
            "description": "Present when the request set `metric`. Count of JSON-number property values used in this window."
          },
          "skipped": {
            "type": "integer",
            "minimum": 0,
            "description": "Present when the request set `metric`. Rows in the window whose property was not a JSON number (numeric strings, booleans, nulls, and missing keys)."
          }
        }
      },
      "CompareInterval": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "level",
          "method",
          "estimate",
          "low",
          "high",
          "excludes_zero",
          "note"
        ],
        "properties": {
          "level": {
            "type": "number",
            "const": 0.9
          },
          "method": {
            "type": "string",
            "const": "newcombe_wilson_90",
            "description": "90% Newcombe hybrid score interval (method 10) on Wilson limits. Rates are unique-converter proportions, so they are in `[0, 1]`."
          },
          "estimate": {
            "type": "string",
            "const": "rate_difference",
            "description": "Compare rate minus baseline rate. Not the relative lift."
          },
          "low": {
            "type": "number",
            "description": "Rounded to 6 decimal places. `keep` requires `low > 0`.",
            "example": 0.081597
          },
          "high": {
            "type": "number",
            "description": "Rounded to 6 decimal places.",
            "example": 0.118402
          },
          "excludes_zero": {
            "type": "boolean",
            "description": "True when the interval is entirely above zero or entirely below zero.",
            "example": true
          },
          "note": {
            "type": "string",
            "const": "90% interval for compare_rate - baseline_rate. Rates are unique goal converters divided by denominator unique_users. Each converter counts once. The Newcombe/Wilson interval treats the rate as a binomial proportion. keep requires the interval to lie entirely above zero. revert requires the interval to lie entirely below zero."
          }
        }
      },
      "CompareRuleResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "keep_threshold",
          "revert_threshold",
          "min_denominator",
          "min_goal_events",
          "defaults_applied"
        ],
        "properties": {
          "keep_threshold": {
            "type": "number",
            "example": 0.15
          },
          "revert_threshold": {
            "type": "number",
            "example": -0.1
          },
          "min_denominator": {
            "type": "integer",
            "example": 200
          },
          "min_goal_events": {
            "type": "integer",
            "example": 20
          },
          "defaults_applied": {
            "type": "array",
            "description": "Rule fields that were omitted and filled from the day-7 examples.",
            "items": {
              "type": "string",
              "enum": [
                "keep_threshold",
                "revert_threshold",
                "min_denominator",
                "min_goal_events"
              ]
            },
            "example": []
          },
          "defaults_note": {
            "type": "string",
            "description": "Present only when `defaults_applied` is not empty.",
            "const": "Omitted rule fields use the documented day-7 recipe examples (200 denominator users per window, 20 unique converters across both windows, +0.15 keep, -0.10 revert). They are example defaults, not Agent Analytics policy."
          }
        }
      },
      "CompareMixValue": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "value",
          "event_count",
          "share"
        ],
        "properties": {
          "value": {
            "type": "string",
            "example": "google"
          },
          "event_count": {
            "type": "integer",
            "example": 100
          },
          "share": {
            "type": "number",
            "description": "Share of tagged events for that property in the window, rounded to 6 decimal places.",
            "example": 0.05
          }
        }
      },
      "CompareMixShift": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "property",
          "value",
          "baseline_share",
          "compare_share",
          "share_change"
        ],
        "properties": {
          "property": {
            "type": "string",
            "enum": [
              "utm_source",
              "referrer"
            ]
          },
          "value": {
            "type": "string",
            "example": "google"
          },
          "baseline_share": {
            "type": "number",
            "example": 0.05
          },
          "compare_share": {
            "type": "number",
            "example": 0.8
          },
          "share_change": {
            "type": "number",
            "description": "Compare share minus baseline share. A shift is an absolute change of at least 0.20.",
            "example": 0.75
          }
        }
      },
      "CompareMixProperty": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "coverage",
          "baseline",
          "compare",
          "shifts"
        ],
        "properties": {
          "coverage": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "baseline",
              "compare"
            ],
            "description": "Tagged events for this property divided by all denominator events in the window. 0 when the window has no denominator events.",
            "properties": {
              "baseline": {
                "type": "number",
                "example": 0
              },
              "compare": {
                "type": "number",
                "example": 0
              }
            }
          },
          "baseline": {
            "type": "array",
            "description": "Top 20 values by event count.",
            "items": {
              "$ref": "#/components/schemas/CompareMixValue"
            }
          },
          "compare": {
            "type": "array",
            "description": "Top 20 values by event count.",
            "items": {
              "$ref": "#/components/schemas/CompareMixValue"
            }
          },
          "shifts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CompareMixShift"
            }
          }
        }
      },
      "CompareTrafficMix": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "basis",
          "shift_threshold",
          "shifted",
          "filters_applied",
          "properties"
        ],
        "properties": {
          "basis": {
            "type": "string",
            "const": "denominator_event"
          },
          "shift_threshold": {
            "type": "number",
            "const": 0.2
          },
          "shifted": {
            "type": "boolean",
            "example": false
          },
          "filters_applied": {
            "type": "boolean",
            "description": "True when the request included filters. Those filters are not applied to the mix.",
            "example": false
          },
          "note": {
            "type": "string",
            "description": "Present when `filters_applied` is true.",
            "const": "Request filters are applied to the window counts. Traffic mix counts the denominator event over the window dates and does not apply those filters."
          },
          "properties": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "utm_source",
              "referrer"
            ],
            "properties": {
              "utm_source": {
                "$ref": "#/components/schemas/CompareMixProperty"
              },
              "referrer": {
                "$ref": "#/components/schemas/CompareMixProperty"
              }
            }
          }
        }
      },
      "CompareConfounder": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "occurred_at",
          "title",
          "windows"
        ],
        "properties": {
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "example": "2020-06-12T15:00:00.000Z"
          },
          "title": {
            "type": "string",
            "maxLength": 120,
            "example": "Pricing copy changed"
          },
          "note": {
            "type": "string",
            "maxLength": 500,
            "example": "Possible confounder."
          },
          "windows": {
            "type": "array",
            "minItems": 1,
            "description": "Which requested windows contain this annotation. A ship-day annotation is not returned.",
            "items": {
              "type": "string",
              "enum": [
                "baseline",
                "compare"
              ]
            },
            "example": [
              "compare"
            ]
          }
        }
      },
      "CompareGuardrails": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "confounded",
          "annotations",
          "traffic_mix",
          "incomplete_current_day",
          "caveat"
        ],
        "description": "Annotations and traffic mix do not change the verdict.\nIf either window includes today UTC, the verdict is `extend` / `incomplete_current_day` and that overrides every other reason.\n",
        "properties": {
          "confounded": {
            "type": "boolean",
            "description": "True when `annotations` is not empty.",
            "example": false
          },
          "annotations": {
            "type": "array",
            "description": "Stored annotations whose `occurred_at` falls inside either window (UTC, inclusive).",
            "items": {
              "$ref": "#/components/schemas/CompareConfounder"
            }
          },
          "traffic_mix": {
            "description": "Null when the mix query throws. Otherwise the denominator-event source mix.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/CompareTrafficMix"
              },
              {
                "type": "null"
              }
            ]
          },
          "traffic_mix_note": {
            "type": "string",
            "description": "Present only when `traffic_mix` is null.",
            "const": "omitted: traffic mix could not be computed"
          },
          "incomplete_current_day": {
            "type": "boolean",
            "description": "True when either window includes today UTC. That also forces verdict `extend` and reason `incomplete_current_day`.",
            "example": false
          },
          "caveat": {
            "type": "string",
            "const": "Before/after is not causal. A keep or revert verdict is a deterministic reading of this rule on these two windows, not proof that the change caused the difference."
          }
        }
      },
      "CompareMetricResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "metric",
          "fn",
          "property",
          "metric_event",
          "better",
          "per_user",
          "percentile_method"
        ],
        "properties": {
          "metric": {
            "type": "string",
            "description": "The request expression, for example `p75(cwv_lcp)` or `sum(revenue)`.",
            "example": "p75(cwv_lcp)"
          },
          "fn": {
            "type": "string",
            "enum": [
              "sum",
              "avg",
              "p50",
              "p75",
              "p95"
            ],
            "example": "p75"
          },
          "property": {
            "type": "string",
            "example": "cwv_lcp"
          },
          "metric_event": {
            "type": "string",
            "description": "Event the property was read from. Defaults to `goal_event` when the request omitted `metric_event`.\nOn hosted, Web Vitals properties are on `page_view`. Self-hosted core stores them on `$web_vitals`.\n",
            "example": "page_view"
          },
          "better": {
            "type": "string",
            "enum": [
              "higher",
              "lower"
            ],
            "example": "lower"
          },
          "per_user": {
            "type": "boolean",
            "description": "`true` for `sum`, because `value` is the sum divided by denominator unique users. `false` for `avg` and percentiles.",
            "example": false
          },
          "percentile_method": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "nearest_rank",
              null
            ],
            "description": "`nearest_rank` when `fn` is `p50`, `p75`, or `p95`. `null` for `sum` and `avg`.",
            "example": "nearest_rank"
          }
        }
      },
      "CompareResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "project_id",
          "verdict",
          "reason",
          "reason_detail",
          "goal_event",
          "denominator_event",
          "count_mode",
          "filters",
          "denominator_filters",
          "window_source",
          "weekday_aligned",
          "windows",
          "lift",
          "interval",
          "rule",
          "guardrails"
        ],
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_id": {
            "type": "string",
            "example": "proj_123"
          },
          "verdict": {
            "type": "string",
            "enum": [
              "keep",
              "revert",
              "extend"
            ],
            "example": "keep"
          },
          "reason": {
            "type": "string",
            "enum": [
              "incomplete_current_day",
              "below_min_sample",
              "zero_denominator",
              "zero_baseline",
              "revert_threshold_met",
              "inconclusive",
              "keep_threshold_met",
              "interval_includes_zero",
              "no_evidence_of_gain",
              "no_interval_for_metric"
            ],
            "example": "keep_threshold_met"
          },
          "reason_detail": {
            "type": "string",
            "example": "Relative lift 1 is at or above the keep threshold 0.15, and the 90% interval for the rate difference lies entirely above zero."
          },
          "goal_event": {
            "type": "string",
            "example": "signup"
          },
          "denominator_event": {
            "type": "string",
            "example": "page_view"
          },
          "count_mode": {
            "type": "string",
            "const": "unique_users"
          },
          "filters": {
            "type": "array",
            "description": "The request filters. An empty array when none were sent.",
            "items": {
              "$ref": "#/components/schemas/CompareFilter"
            }
          },
          "denominator_filters": {
            "type": "array",
            "maxItems": 10,
            "description": "Echo of `denominator_filters`, normalized. An empty array when the request omitted the field.",
            "items": {
              "$ref": "#/components/schemas/CompareFilter"
            }
          },
          "window_source": {
            "type": "string",
            "enum": [
              "ship_date",
              "explicit"
            ],
            "example": "ship_date"
          },
          "ship_date": {
            "type": "string",
            "format": "date",
            "description": "Present only when `window_source` is `ship_date`.",
            "example": "2020-06-10"
          },
          "window_days": {
            "type": "integer",
            "description": "Present only when `window_source` is `ship_date`.",
            "example": 7
          },
          "weekday_aligned": {
            "type": "boolean",
            "description": "True when the two windows contain the same weekdays. Always true for `ship_date`. Informational for explicit windows.",
            "example": true
          },
          "windows": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "baseline",
              "compare"
            ],
            "properties": {
              "baseline": {
                "$ref": "#/components/schemas/CompareWindowResult"
              },
              "compare": {
                "$ref": "#/components/schemas/CompareWindowResult"
              }
            }
          },
          "metric": {
            "description": "Present when the request set `metric`. Omitted on a conversion-rate compare.",
            "allOf": [
              {
                "$ref": "#/components/schemas/CompareMetricResult"
              }
            ]
          },
          "raw_lift": {
            "type": [
              "number",
              "null"
            ],
            "description": "Present when the request set `metric`. `(compare_value - baseline_value) / baseline_value`, rounded to 6 decimal places, before `better` is applied.\nNull when `lift` is null.\n",
            "example": -0.5
          },
          "lift": {
            "type": [
              "number",
              "null"
            ],
            "description": "Relative lift, rounded to 6 decimal places.\nOn a conversion-rate compare this is `(compare_rate - baseline_rate) / baseline_rate`.\nWhen `metric` is set this is `raw_lift`, negated when `better` is `lower`, so a positive lift is a change in the good direction and the existing thresholds still apply.\nNull when the baseline rate is 0, the baseline `value` is 0 or null, or the compare `value` is missing.\n",
            "example": 1
          },
          "interval": {
            "description": "Null on `below_min_sample` and `zero_denominator`.\nAlso null when `metric` is set. That response sets `interval_method` to `none`.\n",
            "oneOf": [
              {
                "$ref": "#/components/schemas/CompareInterval"
              },
              {
                "type": "null"
              }
            ]
          },
          "interval_method": {
            "type": "string",
            "const": "none",
            "description": "Present only when `metric` is set. There is no confidence interval for a metric compare in v1. Omitted on a conversion-rate compare, which reports `newcombe_wilson_90` on `interval.method`."
          },
          "rule": {
            "$ref": "#/components/schemas/CompareRuleResult"
          },
          "guardrails": {
            "$ref": "#/components/schemas/CompareGuardrails"
          }
        }
      },
      "PortfolioContextRole": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "project": {
            "type": "string",
            "maxLength": 96,
            "example": "docs.example.com"
          },
          "role": {
            "type": "string",
            "maxLength": 120,
            "example": "discovery_surface"
          }
        }
      },
      "PortfolioContextGlossaryEntry": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "term": {
            "type": "string",
            "maxLength": 80,
            "example": "Qualified click"
          },
          "definition": {
            "type": "string",
            "maxLength": 240,
            "example": "A visitor reaches the product with relevant intent."
          }
        }
      },
      "PortfolioContext": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "goals": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string",
              "maxLength": 160
            },
            "default": [],
            "example": [
              "Increase qualified users who reach setup"
            ]
          },
          "surface_roles": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/PortfolioContextRole"
            },
            "default": []
          },
          "shared_milestones": {
            "type": "array",
            "maxItems": 12,
            "items": {
              "type": "string",
              "maxLength": 96
            },
            "default": [],
            "example": [
              "qualified_click_to_product",
              "signup",
              "project_created"
            ]
          },
          "glossary": {
            "type": "array",
            "maxItems": 12,
            "items": {
              "$ref": "#/components/schemas/PortfolioContextGlossaryEntry"
            },
            "default": []
          }
        }
      },
      "PortfolioContextResponse": {
        "type": "object",
        "required": [
          "account_id",
          "portfolio_context"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "description": "Present on successful updates.",
            "example": true
          },
          "account_id": {
            "type": "string",
            "example": "acc_123"
          },
          "portfolio_context": {
            "$ref": "#/components/schemas/PortfolioContext"
          }
        }
      },
      "TrackRequest": {
        "type": "object",
        "required": [
          "token",
          "event"
        ],
        "properties": {
          "token": {
            "type": "string",
            "description": "Project token (`aat_*`)",
            "example": "aat_51da22cdcab084ae1cdb50fd4841c642f0dafdb1d9adfa6b"
          },
          "event": {
            "type": "string",
            "description": "Event name (max 256 chars)",
            "example": "page_view"
          },
          "properties": {
            "type": [
              "object",
              "null"
            ],
            "description": "Arbitrary key-value properties (max 8KB JSON). The tracker auto-populates `path`, `url`, `hostname`, `title`, `referrer`, `screen`, `browser`, `browser_version`, `os`, `device`, `language`, `timezone` (IANA), `utm_*` params, `session_count`, `days_since_first_visit`, and `first_utm_*` (first-touch attribution).",
            "example": {
              "path": "/pricing",
              "referrer": "https://google.com",
              "browser": "Chrome",
              "os": "macOS"
            }
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Anonymous user identifier (max 256 chars). The tracker auto-generates one via localStorage.",
            "example": "usr_abc123"
          },
          "session_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Session identifier (max 256 chars). The tracker auto-generates one via sessionStorage with 30-min inactivity timeout.",
            "example": "ses_xyz789"
          },
          "timestamp": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix timestamp in milliseconds. Defaults to `Date.now()`. Must be within 30 days ago to 5 minutes in the future.",
            "example": 1706745600000
          }
        }
      },
      "TrackBatchRequest": {
        "type": "object",
        "required": [
          "events"
        ],
        "properties": {
          "events": {
            "type": "array",
            "description": "Array of events (max 100 per batch)",
            "maxItems": 100,
            "items": {
              "type": "object",
              "required": [
                "token",
                "event"
              ],
              "properties": {
                "token": {
                  "type": "string",
                  "description": "Project token (`aat_*`). All events must use the same token.",
                  "example": "aat_51da22cdcab084ae1cdb50fd4841c642f0dafdb1d9adfa6b"
                },
                "event": {
                  "type": "string",
                  "example": "page_view"
                },
                "properties": {
                  "type": [
                    "object",
                    "null"
                  ]
                },
                "user_id": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "session_id": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "timestamp": {
                  "type": [
                    "number",
                    "null"
                  ]
                }
              }
            }
          }
        }
      },
      "StatsResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "period": {
            "type": "object",
            "properties": {
              "from": {
                "type": "string",
                "example": "2025-01-01"
              },
              "to": {
                "type": "string",
                "example": "2025-01-07"
              },
              "groupBy": {
                "type": "string",
                "enum": [
                  "hour",
                  "day",
                  "week",
                  "month"
                ],
                "example": "day"
              }
            }
          },
          "totals": {
            "type": "object",
            "properties": {
              "unique_users": {
                "type": "integer",
                "example": 142
              },
              "total_events": {
                "type": "integer",
                "example": 1247
              }
            }
          },
          "timeSeries": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bucket": {
                  "type": "string",
                  "example": "2025-01-01"
                },
                "unique_users": {
                  "type": "integer"
                },
                "total_events": {
                  "type": "integer"
                }
              }
            }
          },
          "events": {
            "type": "array",
            "description": "Top event names by count (max 20)",
            "items": {
              "type": "object",
              "properties": {
                "event": {
                  "type": "string",
                  "example": "page_view"
                },
                "count": {
                  "type": "integer"
                },
                "unique_users": {
                  "type": "integer"
                }
              }
            }
          },
          "countries": {
            "type": "array",
            "description": "Country groups sorted by raw event count for the same project and period as totals.\nEvent counts sum to totals.total_events. Users may appear in multiple countries,\nso country unique-user counts are not additive. Missing/empty country, XX,\nand T1 are grouped as null (Unknown in CLI and MCP).\n",
            "items": {
              "type": "object",
              "required": [
                "country",
                "count",
                "unique_users"
              ],
              "properties": {
                "country": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "example": "NL"
                },
                "count": {
                  "type": "integer",
                  "minimum": 0,
                  "example": 80
                },
                "unique_users": {
                  "type": "integer",
                  "minimum": 0,
                  "example": 1
                }
              }
            }
          },
          "sessions": {
            "type": "object",
            "properties": {
              "total_sessions": {
                "type": "integer"
              },
              "bounce_rate": {
                "type": "number",
                "example": 0.45,
                "description": "Bounce rate computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n"
              },
              "avg_duration": {
                "type": "integer",
                "description": "Average session duration in milliseconds"
              },
              "pages_per_session": {
                "type": "number"
              },
              "sessions_per_user": {
                "type": "number"
              }
            }
          }
        }
      },
      "EventRow": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "project_id": {
            "type": "string"
          },
          "event": {
            "type": "string"
          },
          "properties": {
            "type": [
              "object",
              "null"
            ]
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "session_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "timestamp": {
            "type": "number"
          },
          "date": {
            "type": "string"
          },
          "country": {
            "type": [
              "string",
              "null"
            ],
            "description": "ISO 3166-1 alpha-2 country code derived from the request IP at ingestion time",
            "example": "US"
          }
        }
      },
      "VitalsThreshold": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "unit",
          "good_max",
          "poor_min"
        ],
        "properties": {
          "unit": {
            "type": "string",
            "enum": [
              "ms",
              "unitless"
            ]
          },
          "good_max": {
            "type": "number"
          },
          "poor_min": {
            "type": "number"
          }
        }
      },
      "VitalsShare": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "good",
          "needs_improvement",
          "poor"
        ],
        "description": "Fractions from 0 to 1, 3 decimal places. The key is `needs_improvement` (underscore).",
        "properties": {
          "good": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "needs_improvement": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "poor": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          }
        }
      },
      "VitalsTargetCount": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "target",
          "count"
        ],
        "properties": {
          "target": {
            "type": "string",
            "maxLength": 200,
            "description": "CSS selector only. No text content and no URL."
          },
          "count": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "VitalsMetric": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "p75",
          "rating",
          "n",
          "skipped",
          "share",
          "top_poor_targets"
        ],
        "properties": {
          "p75": {
            "type": [
              "number",
              "null"
            ],
            "description": "Nearest-rank 75th percentile. Null when `n` is 0."
          },
          "rating": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "good",
              "needs-improvement",
              "poor",
              null
            ],
            "description": "The p75 rating. `good` when p75 <= `good_max`. `poor` when p75 > `poor_min`. Otherwise `needs-improvement`. Null when `n` is 0.\n"
          },
          "n": {
            "type": "integer",
            "minimum": 0,
            "description": "Page views in the group that included this metric."
          },
          "skipped": {
            "type": "integer",
            "minimum": 0,
            "description": "Page views in the group that did not include this metric. A missing key is skipped, not zero."
          },
          "share": {
            "$ref": "#/components/schemas/VitalsShare"
          },
          "top_poor_targets": {
            "type": "array",
            "maxItems": 5,
            "description": "Up to 5 selectors by count among loads rated `poor`. Empty for FCP and TTFB.",
            "items": {
              "$ref": "#/components/schemas/VitalsTargetCount"
            }
          }
        }
      },
      "VitalsMetrics": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lcp",
          "inp",
          "cls",
          "fcp",
          "ttfb"
        ],
        "properties": {
          "lcp": {
            "$ref": "#/components/schemas/VitalsMetric"
          },
          "inp": {
            "$ref": "#/components/schemas/VitalsMetric"
          },
          "cls": {
            "$ref": "#/components/schemas/VitalsMetric"
          },
          "fcp": {
            "$ref": "#/components/schemas/VitalsMetric"
          },
          "ttfb": {
            "$ref": "#/components/schemas/VitalsMetric"
          }
        }
      },
      "VitalsRow": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "group",
          "cwv_pass",
          "metrics"
        ],
        "properties": {
          "group": {
            "type": [
              "string",
              "null"
            ],
            "description": "Null when `group_by` is omitted. `mobile`, `tablet`, or `desktop` when `group_by` is `device`.\nThe pathname when `group_by` is `path`.\n"
          },
          "cwv_pass": {
            "type": [
              "boolean",
              "null"
            ],
            "description": "True when the LCP, INP, and CLS p75 values are all `good`.\nWhen INP `n` is 0, the decision uses LCP and CLS only.\nNull when LCP `n` is 0 or CLS `n` is 0.\nFCP and TTFB are not part of the decision.\n"
          },
          "metrics": {
            "$ref": "#/components/schemas/VitalsMetrics"
          }
        }
      },
      "VitalsRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name",
            "example": "my-site"
          },
          "days": {
            "type": "integer",
            "minimum": 1,
            "description": "Optional day window. Omit when passing `date_from` and `date_to`."
          },
          "date_from": {
            "type": "string",
            "format": "date",
            "description": "Inclusive start, `YYYY-MM-DD`.",
            "example": "2026-11-06"
          },
          "date_to": {
            "type": "string",
            "format": "date",
            "description": "Inclusive end, `YYYY-MM-DD`.",
            "example": "2026-11-12"
          },
          "group_by": {
            "type": "string",
            "enum": [
              "device",
              "path"
            ],
            "description": "Omit for one row with `group` null.\n`device` returns `mobile`, `tablet`, and `desktop`.\n`path` returns the top `limit` paths by `n`, sorted by worst LCP p75.\n"
          },
          "limit": {
            "type": "integer",
            "minimum": 1,
            "maximum": 20,
            "default": 10,
            "description": "Used when `group_by` is `path`. Default 10. Maximum 20."
          }
        }
      },
      "VitalsResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "date_from",
          "date_to",
          "event",
          "group_by",
          "percentile",
          "percentile_method",
          "approximate",
          "thresholds",
          "rows"
        ],
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "date_from": {
            "type": "string",
            "format": "date",
            "example": "2026-11-06"
          },
          "date_to": {
            "type": "string",
            "format": "date",
            "example": "2026-11-12"
          },
          "event": {
            "type": "string",
            "const": "page_view",
            "description": "Fixed. Hosted Web Vitals live on `page_view`."
          },
          "group_by": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "device",
              "path",
              null
            ],
            "description": "Echo of the request. Null when `group_by` was omitted."
          },
          "percentile": {
            "type": "string",
            "const": "p75",
            "description": "p75 is the headline."
          },
          "percentile_method": {
            "type": "string",
            "const": "nearest_rank"
          },
          "approximate": {
            "type": "boolean",
            "description": "True when the nearest-rank sample hit the 200,000 event cap. False otherwise.\nA capped read is still `200`.\n"
          },
          "caps": {
            "type": "array",
            "description": "Present when `approximate` is true. Omitted when `approximate` is false.",
            "items": {
              "type": "string"
            }
          },
          "thresholds": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "lcp",
              "inp",
              "cls",
              "fcp",
              "ttfb"
            ],
            "properties": {
              "lcp": {
                "$ref": "#/components/schemas/VitalsThreshold"
              },
              "inp": {
                "$ref": "#/components/schemas/VitalsThreshold"
              },
              "cls": {
                "$ref": "#/components/schemas/VitalsThreshold"
              },
              "fcp": {
                "$ref": "#/components/schemas/VitalsThreshold"
              },
              "ttfb": {
                "$ref": "#/components/schemas/VitalsThreshold"
              }
            }
          },
          "rows": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/VitalsRow"
            }
          }
        }
      },
      "QueryRequest": {
        "type": "object",
        "required": [
          "project"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name",
            "example": "my-site"
          },
          "metrics": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "event_count",
                "unique_users",
                "session_count",
                "bounce_rate",
                "avg_duration",
                "sum",
                "avg",
                "p50",
                "p75",
                "p95"
              ]
            },
            "default": [
              "event_count"
            ],
            "description": "Metrics to compute.\n`sum`, `avg`, `p50`, `p75`, and `p95` are numeric aggregates of one event property and require `property`.\nThey are Pro, the same gate as the rest of `POST /query`.\n"
          },
          "property": {
            "type": "string",
            "maxLength": 128,
            "pattern": "^[A-Za-z0-9_]+$",
            "description": "Event property key for `sum`, `avg`, `p50`, `p75`, or `p95`. Example: `cwv_lcp` or `revenue`.\nThe key itself, not `properties.<key>`. Allowlist `^[A-Za-z0-9_]+$`, max 128.\nRequired when any of those metrics is present. Missing property is `400` `MISSING_FIELDS`.\nAn invalid key is `400` `INVALID_PROPERTY_KEY`.\n",
            "example": "cwv_lcp"
          },
          "group_by": {
            "type": "array",
            "items": {
              "type": "string",
              "pattern": "^(event|date|user_id|session_id|country|properties\\.[A-Za-z0-9_]{1,128})$"
            },
            "default": [],
            "description": "Built-in fields `event`, `date`, `user_id`, `session_id`, and `country`, plus at most one `properties.<key>`.\n`<key>` is 1 to 128 characters matching `[A-Za-z0-9_]`, the same rule as a `properties.<key>` filter.\nThe result row uses the key exactly `properties.<key>`. A null or missing property groups as null.\nTwo `properties.*` entries are `400` `INVALID_GROUP_BY`.\nA key that fails the filter rule is `400` `INVALID_PROPERTY_KEY`.\nAn entry that is neither a built-in field nor `properties.<key>` is `400` `INVALID_GROUP_BY`.\nWorks with the existing metrics, filters, date range, and `limit` cap of 1,000, including Pro numeric metrics.\n"
          },
          "filters": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "field": {
                  "type": "string",
                  "description": "Field to filter on. Built-in: `event`, `user_id`, `date`, `country`, `session_id`, `timestamp`. You can also filter on `properties.<key>`, including first-touch attribution fields like `properties.first_utm_source`. `<key>` is 1 to 128 characters matching `[A-Za-z0-9_]`. An invalid key is `400` `INVALID_PROPERTY_KEY`.",
                  "example": "event"
                },
                "op": {
                  "type": "string",
                  "enum": [
                    "eq",
                    "neq",
                    "gt",
                    "lt",
                    "gte",
                    "lte",
                    "contains"
                  ],
                  "example": "eq"
                },
                "value": {
                  "description": "Value to compare against",
                  "example": "page_view"
                }
              }
            }
          },
          "date_from": {
            "type": "string",
            "description": "Start date (ISO 8601 or `Nd` shorthand). Defaults to 7 days ago.",
            "example": "2025-01-01"
          },
          "date_to": {
            "type": "string",
            "description": "End date (ISO 8601). Defaults to today.",
            "example": "2025-01-07"
          },
          "count_mode": {
            "type": "string",
            "enum": [
              "raw",
              "session_then_user"
            ],
            "description": "How `event_count` is aggregated. Default for `event_count`: `session_then_user`. Session-backed rows count by session, no-session rows fall back to user only when that user has no session-backed row in the same group, and fully anonymous rows fall back to event id. Ignored for queries without `event_count`. Use `raw` to count ingested rows without dedupe."
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Optional raw email for authenticated lookup. Send only in the HTTPS POST body. The API normalizes it, computes a scoped HMAC lookup index server-side, and does not store raw email in event rows or profile traits.",
            "example": "alice@example.com"
          },
          "order_by": {
            "type": "string",
            "enum": [
              "event_count",
              "unique_users",
              "session_count",
              "date",
              "event",
              "sum",
              "avg",
              "p50",
              "p75",
              "p95"
            ],
            "description": "Field to sort by. Aggregation names are valid when that metric was requested."
          },
          "order": {
            "type": "string",
            "enum": [
              "asc",
              "desc"
            ],
            "default": "desc"
          },
          "limit": {
            "type": "integer",
            "default": 100,
            "maximum": 1000,
            "minimum": 1
          }
        }
      },
      "QueryResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "period": {
            "type": "object",
            "properties": {
              "from": {
                "type": "string"
              },
              "to": {
                "type": "string"
              }
            }
          },
          "metrics": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "group_by": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "property": {
            "type": [
              "string",
              "null"
            ],
            "description": "Echo of `property` when an aggregation metric was requested. Otherwise omitted or null.",
            "example": "cwv_lcp"
          },
          "percentile_method": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "nearest_rank",
              null
            ],
            "description": "`nearest_rank` when `metrics` includes `p50`, `p75`, or `p95`.\n`null` when the aggregation metrics are only `sum` and/or `avg`.\nOmitted when no aggregation metric was requested.\n"
          },
          "rows": {
            "type": "array",
            "description": "One object per group. Keys from `group_by` are included.\nA `properties.<key>` group is returned under that exact key. A null or missing property is null.\nCount metrics are returned under the requested names: `event_count`, `unique_users`, `session_count`, `bounce_rate`, `avg_duration`.\nWhen `metrics` includes `sum`, `avg`, `p50`, `p75`, or `p95`, each row includes those requested names plus `n` and `skipped`.\nOnly JSON numbers (`integer` or `real`) are aggregated. Numeric strings, booleans, nulls, and missing keys are `skipped`.\n`n` is the numeric count. `skipped` is the other rows in the group.\nPercentiles are nearest-rank. Sort ascending, break ties by event id, and take rank `ceil(p/100 * n)` (p is 50, 75, or 95). Rank 1 is the smallest value. The result is an observed input, not an interpolation.\nA percentile query whose filtered set is larger than 200,000 events is `400`.\n`avg` is the arithmetic mean, rounded to 6 decimal places. `sum` and `avg` are streaming aggregates.\n",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "count": {
            "type": "integer"
          }
        }
      },
      "SqlEventsRow": {
        "type": "object",
        "additionalProperties": true,
        "description": "Columns of `events` visible to `POST /sql`. These names are guaranteed, in this order when selected with `SELECT *`.\nAdding a column later is allowed. Removing or renaming one is a breaking change.\n`properties` is a JSON string. Use `json_extract` in the statement.\n`resolved_user_id` is not a column. `project_id` is not a column. The server already limits rows to the requested project.\n",
        "required": [
          "id",
          "event",
          "properties",
          "user_id",
          "session_id",
          "timestamp",
          "date",
          "country"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "Event id."
          },
          "event": {
            "type": "string"
          },
          "properties": {
            "type": "string",
            "description": "JSON text, not a parsed object."
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "session_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "timestamp": {
            "type": "number",
            "description": "Unix timestamp in milliseconds."
          },
          "date": {
            "type": "string"
          },
          "country": {
            "type": [
              "string",
              "null"
            ],
            "description": "ISO 3166-1 alpha-2 country code, or null."
          }
        }
      },
      "SqlSessionsRow": {
        "type": "object",
        "additionalProperties": true,
        "description": "Columns of `sessions` visible to `POST /sql`. These names are guaranteed, in this order when selected with `SELECT *`.\nAdding a column later is allowed. Removing or renaming one is a breaking change.\n`project_id` is the project name. `resolved_user_id` is not a column.\n",
        "required": [
          "session_id",
          "user_id",
          "project_id",
          "start_time",
          "end_time",
          "duration",
          "entry_page",
          "exit_page",
          "event_count",
          "is_bounce",
          "date"
        ],
        "properties": {
          "session_id": {
            "type": "string"
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "project_id": {
            "type": "string",
            "description": "Project name."
          },
          "start_time": {
            "type": "number"
          },
          "end_time": {
            "type": "number"
          },
          "duration": {
            "type": "integer",
            "description": "Duration in milliseconds."
          },
          "entry_page": {
            "type": [
              "string",
              "null"
            ]
          },
          "exit_page": {
            "type": [
              "string",
              "null"
            ]
          },
          "event_count": {
            "type": "integer"
          },
          "is_bounce": {
            "type": "integer",
            "enum": [
              0,
              1
            ],
            "description": "`1` when the session has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n"
          },
          "date": {
            "type": "string"
          }
        }
      },
      "SqlRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "sql"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name. The server binds this value. It is not interpolated into the SQL.",
            "example": "my-site"
          },
          "sql": {
            "type": "string",
            "maxLength": 20480,
            "description": "One `SELECT` statement, at most 20,480 bytes (20 KB). A statement that starts with `WITH` is rejected.\nA nested `WITH` is allowed only when every table it names is `events` or `sessions`.\nA recursive CTE is rejected.\nEach of `events` and `sessions` may be referenced at most once. One join of `events` to `sessions` is allowed. A self join is not.\nAfter `FROM`, `JOIN`, or `IN`, only `events`, `sessions`, a CTE name, or a parenthesized subquery or list is allowed.\nA `LIMIT` must be a plain integer. `randomblob` and `zeroblob` are rejected.\nBind parameters, table-valued functions, `sqlite_temp_schema`, and non-ASCII characters outside string literals are rejected.\nA subquery inside the `SELECT` is allowed.\nReadable tables are only `events` (`SqlEventsRow`) and `sessions` (`SqlSessionsRow`).\n",
            "example": "SELECT event, COUNT(*) AS n FROM events GROUP BY event"
          },
          "days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 90,
            "default": 7,
            "description": "Optional day count ending today. Default 7. Maximum 90.\nSend `days`, or send `date_from` and `date_to`. A window outside those rules is `400` `INVALID_WINDOW`.\n"
          },
          "date_from": {
            "type": "string",
            "description": "Inclusive start date, `YYYY-MM-DD`. Pair it with `date_to`. Parsing matches `POST /query`.\nThe span is at most 90 days.\n",
            "example": "2026-11-07"
          },
          "date_to": {
            "type": "string",
            "description": "Inclusive end date, `YYYY-MM-DD`. Must be on or after `date_from`. The span is at most 90 days.\n",
            "example": "2026-11-13"
          }
        }
      },
      "SqlWindow": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date_from",
          "date_to"
        ],
        "description": "The time window the server applied. Both `events` and `sessions` are filtered on the `date` column: `date >= ? AND date <= ?`, inclusive UTC days. That uses `idx_events_project_date` and `idx_sessions_project_date`.\n",
        "properties": {
          "date_from": {
            "type": "string",
            "description": "Inclusive start date, `YYYY-MM-DD`.",
            "example": "2026-11-07"
          },
          "date_to": {
            "type": "string",
            "description": "Inclusive end date, `YYYY-MM-DD`.",
            "example": "2026-11-13"
          }
        }
      },
      "SqlStatistics": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "elapsed_ms",
          "rows_read",
          "expensive"
        ],
        "properties": {
          "elapsed_ms": {
            "type": "number",
            "description": "Database time in milliseconds.",
            "example": 18
          },
          "rows_read": {
            "type": "integer",
            "minimum": 0,
            "description": "Rows the database read. Hosted copies D1 `meta.rows_read`.",
            "example": 1200
          },
          "expensive": {
            "type": "boolean",
            "description": "True when `rows_read` is over 1,000,000. The rows are still returned.",
            "example": false
          }
        }
      },
      "SqlResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "columns",
          "rows",
          "count",
          "truncated",
          "window",
          "statistics"
        ],
        "properties": {
          "columns": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Result column names, in order.",
            "example": [
              "event",
              "n"
            ]
          },
          "rows": {
            "type": "array",
            "maxItems": 1000,
            "description": "One object per result row. Hosted and OSS both return the database result objects.\n`columns` is the keys of the first row. When `rows` is empty, `columns` is `[]`.\n",
            "items": {
              "type": "object",
              "additionalProperties": true
            },
            "example": [
              {
                "event": "page_view",
                "n": 12
              }
            ]
          },
          "count": {
            "type": "integer",
            "minimum": 0,
            "maximum": 1000,
            "description": "Number of rows in `rows` after the 1,000 row cap.",
            "example": 1
          },
          "truncated": {
            "type": "boolean",
            "description": "True when the result was cut to 1,000 rows because more rows existed.",
            "example": false
          },
          "window": {
            "$ref": "#/components/schemas/SqlWindow"
          },
          "statistics": {
            "$ref": "#/components/schemas/SqlStatistics"
          }
        }
      },
      "IdentityLookupRequest": {
        "type": "object",
        "required": [
          "project"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name or ID",
            "example": "my-site"
          },
          "user_id": {
            "type": "string",
            "description": "Stable application user ID to look up",
            "example": "user_12345"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Raw email for authenticated lookup. Send only in the HTTPS POST body. Agent Analytics normalizes it, computes a scoped HMAC lookup index server-side, and does not store raw email in event rows or profile traits.",
            "example": "alice@example.com"
          },
          "event": {
            "type": "string",
            "description": "Optional event-name filter for `/events`",
            "example": "signup"
          },
          "since": {
            "type": "string",
            "description": "Lookback window as ISO date or `Nd` shorthand",
            "example": "30d"
          },
          "limit": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000,
            "default": 100
          }
        },
        "anyOf": [
          {
            "required": [
              "user_id"
            ]
          },
          {
            "required": [
              "email"
            ]
          }
        ]
      },
      "ErrorGroup": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "fingerprint",
          "message",
          "source",
          "line",
          "count",
          "users",
          "sessions",
          "first_seen",
          "last_seen",
          "top_paths"
        ],
        "properties": {
          "fingerprint": {
            "type": "string",
            "description": "Lowercase SHA-256 hex of the group key.\nThe key is the normalized message, the source filename, and the numeric `line`.\nMessage normalization removes URL query strings and fragments, then replaces UUIDs, hex hashes, and numbers.\nThe source contribution is the filename only, with query and hash removed.\n`col` is not part of the key. The tracker does not send `stack`, and stack is not part of the key.\n",
            "example": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
          },
          "message": {
            "type": "string",
            "description": "Sample stored message from one event in the group. This is the stored text, not the normalized fingerprint.",
            "example": "Failed request 404 https://api.example/users/99?token=zzz"
          },
          "source": {
            "type": "string",
            "description": "Source filename from the group key.",
            "example": "app.js"
          },
          "line": {
            "type": "integer",
            "description": "Numeric `line` from the group key. `0` when the tracker did not have a line.",
            "example": 10
          },
          "count": {
            "type": "integer",
            "minimum": 0,
            "description": "`$error` events in this group inside `since`/`until`.",
            "example": 4
          },
          "users": {
            "type": "integer",
            "minimum": 0,
            "description": "Distinct users in this group inside the window.",
            "example": 3
          },
          "sessions": {
            "type": "integer",
            "minimum": 0,
            "description": "Distinct sessions in this group inside the window.",
            "example": 3
          },
          "first_seen": {
            "type": "string",
            "format": "date",
            "description": "Earliest stored `$error` for this fingerprint, across retention, not only the requested window. `YYYY-MM-DD`.",
            "example": "2026-10-01"
          },
          "last_seen": {
            "type": "string",
            "format": "date",
            "description": "Latest stored `$error` for this fingerprint, across retention, not only the requested window. `YYYY-MM-DD`.",
            "example": "2026-11-11"
          },
          "top_paths": {
            "type": "array",
            "maxItems": 3,
            "description": "Up to 3 `path` values on this group's `$error` events inside the window. The tracker sets `path` from the page pathname.",
            "items": {
              "type": "string"
            },
            "example": [
              "/pricing",
              "/"
            ]
          },
          "new_since": {
            "type": "boolean",
            "description": "Present only when the `new_since` query parameter was set. Omitted when the parameter is omitted.\nA `YYYY-MM-DD` parameter is true when the earliest event's UTC date is on or after that date.\nAn annotation parameter is true when the earliest event's full UTC timestamp is at or after the annotation's `occurred_at`.\n",
            "example": false
          }
        }
      },
      "ErrorsResponse": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "since",
          "until",
          "limit",
          "truncated",
          "approximate",
          "groups"
        ],
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "since": {
            "type": "string",
            "format": "date",
            "description": "Resolved window start, UTC date.",
            "example": "2026-11-05"
          },
          "until": {
            "type": "string",
            "format": "date",
            "description": "Resolved window end, inclusive UTC date.",
            "example": "2026-11-12"
          },
          "limit": {
            "type": "integer",
            "description": "Applied limit. Requested values above 100 are clamped to 100. Default 20.",
            "example": 20
          },
          "truncated": {
            "type": "boolean",
            "description": "True when more in-window groups exist than `limit`.",
            "example": false
          },
          "approximate": {
            "type": "boolean",
            "description": "Always returned. `true` when a scan cap was hit. `false` when the scan finished inside both caps.\nA large project still returns `200`. Counts on an approximate response are not a complete scan.\n",
            "example": false
          },
          "caps": {
            "type": "array",
            "description": "Present when `approximate` is true. Omitted when `approximate` is false.\nEach string is a scan cap that was hit.\n`distinct_triples`: `first_seen` used at most 5,000 distinct message, source, and line triples.\n`window_rows`: the in-window scan used the newest 50,000 rows.\n",
            "items": {
              "type": "string",
              "enum": [
                "distinct_triples",
                "window_rows"
              ]
            },
            "example": [
              "distinct_triples",
              "window_rows"
            ]
          },
          "new_since": {
            "type": "string",
            "format": "date",
            "description": "Present only when the `new_since` query parameter was set. The resolved UTC date.",
            "example": "2026-11-05"
          },
          "new_since_annotation": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "occurred_at",
              "title"
            ],
            "description": "Present when `new_since` was an annotation reference that matched one annotation. Omitted when `new_since` was a date, and omitted when the parameter was omitted.",
            "properties": {
              "occurred_at": {
                "type": "string",
                "format": "date-time",
                "example": "2026-11-05T12:00:00.000Z"
              },
              "title": {
                "type": "string",
                "example": "Ship errors"
              }
            }
          },
          "groups": {
            "type": "array",
            "description": "Groups that have at least one `$error` in the requested window. At most `limit` groups.",
            "items": {
              "$ref": "#/components/schemas/ErrorGroup"
            }
          }
        }
      },
      "JourneyResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "profiles": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "events": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/EventRow"
            }
          }
        }
      },
      "Portfolio": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "pf_abc123"
          },
          "account_id": {
            "type": "string",
            "example": "acc_123"
          },
          "slug": {
            "type": "string",
            "example": "growth-system"
          },
          "name": {
            "type": "string",
            "example": "Growth system"
          },
          "created_at": {
            "type": "integer",
            "format": "int64"
          },
          "updated_at": {
            "type": "integer",
            "format": "int64"
          },
          "members": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "project_id": {
                  "type": "string"
                },
                "project": {
                  "type": "string"
                },
                "added_at": {
                  "type": "integer",
                  "format": "int64"
                }
              }
            }
          }
        }
      },
      "SessionRow": {
        "type": "object",
        "properties": {
          "session_id": {
            "type": "string"
          },
          "user_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "project_id": {
            "type": "string"
          },
          "start_time": {
            "type": "number"
          },
          "end_time": {
            "type": "number"
          },
          "duration": {
            "type": "integer",
            "description": "Duration in milliseconds"
          },
          "entry_page": {
            "type": [
              "string",
              "null"
            ]
          },
          "exit_page": {
            "type": [
              "string",
              "null"
            ]
          },
          "event_count": {
            "type": "integer"
          },
          "is_bounce": {
            "type": "integer",
            "enum": [
              0,
              1
            ],
            "description": "Computed from event names at query time.\n`1` means the session has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n"
          },
          "has_replay": {
            "type": "boolean",
            "description": "Present for callers with replay read authority. True when the session has at least one playable replay segment."
          },
          "replay_count": {
            "type": "integer",
            "description": "Number of playable replay segments linked to this analytics session."
          },
          "replays": {
            "type": "array",
            "description": "Bounded replay summaries. Omitted when the caller does not have replay read authority.",
            "items": {
              "$ref": "#/components/schemas/ReplaySummary"
            }
          },
          "date": {
            "type": "string"
          }
        }
      },
      "ReplaySummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "rpl_abc123"
          },
          "project_id": {
            "type": "string"
          },
          "analytics_session_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "recording",
              "complete",
              "incomplete",
              "deleting",
              "deleted"
            ]
          },
          "started_at": {
            "type": "integer",
            "format": "int64"
          },
          "ended_at": {
            "type": [
              "integer",
              "null"
            ],
            "format": "int64"
          },
          "committed_bytes": {
            "type": "integer",
            "format": "int64"
          },
          "event_count": {
            "type": "integer"
          },
          "has_full_snapshot": {
            "type": "boolean"
          },
          "stop_reason": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "BreakdownResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "property": {
            "type": "string",
            "example": "path"
          },
          "event": {
            "type": [
              "string",
              "null"
            ]
          },
          "values": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "value": {
                  "type": "string",
                  "example": "/pricing"
                },
                "count": {
                  "type": "integer",
                  "example": 342
                },
                "unique_users": {
                  "type": "integer",
                  "example": 201
                }
              }
            }
          },
          "total_events": {
            "type": "integer"
          },
          "total_with_property": {
            "type": "integer"
          }
        }
      },
      "InsightsResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "current_period": {
            "type": "object",
            "properties": {
              "from": {
                "type": "string"
              },
              "to": {
                "type": "string"
              }
            }
          },
          "previous_period": {
            "type": "object",
            "properties": {
              "from": {
                "type": "string"
              },
              "to": {
                "type": "string"
              }
            }
          },
          "metrics": {
            "type": "object",
            "properties": {
              "total_events": {
                "$ref": "#/components/schemas/DeltaMetric"
              },
              "unique_users": {
                "$ref": "#/components/schemas/DeltaMetric"
              },
              "total_sessions": {
                "$ref": "#/components/schemas/DeltaMetric"
              },
              "bounce_rate": {
                "$ref": "#/components/schemas/DeltaMetric"
              },
              "avg_duration": {
                "$ref": "#/components/schemas/DeltaMetric"
              }
            }
          },
          "trend": {
            "type": "string",
            "enum": [
              "growing",
              "stable",
              "declining"
            ]
          }
        }
      },
      "DeltaMetric": {
        "type": "object",
        "properties": {
          "current": {
            "type": "number"
          },
          "previous": {
            "type": "number"
          },
          "change": {
            "type": "number"
          },
          "change_pct": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Percentage change. Null when previous period was 0 but current is > 0."
          }
        }
      },
      "PagesResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "entry_pages": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PageRow"
            }
          },
          "exit_pages": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PageRow"
            }
          }
        }
      },
      "PathsRequest": {
        "type": "object",
        "required": [
          "project",
          "goal_event"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name",
            "example": "my-site"
          },
          "goal_event": {
            "type": "string",
            "description": "Goal event that must occur in the same session",
            "example": "signup"
          },
          "since": {
            "type": "string",
            "enum": [
              "7d",
              "14d",
              "30d",
              "90d"
            ],
            "default": "30d",
            "description": "Fixed lookback window for bounded path analysis"
          },
          "max_steps": {
            "type": "integer",
            "minimum": 1,
            "maximum": 5,
            "default": 5,
            "description": "Max mixed page/event steps before the path is marked truncated"
          },
          "entry_limit": {
            "type": "integer",
            "minimum": 1,
            "maximum": 20,
            "default": 10,
            "description": "Max entry pages to include"
          },
          "path_limit": {
            "type": "integer",
            "minimum": 1,
            "maximum": 10,
            "default": 5,
            "description": "Max children kept per tree node after aggregation"
          },
          "candidate_session_cap": {
            "type": "integer",
            "minimum": 100,
            "maximum": 10000,
            "default": 5000,
            "description": "Max sessions scanned before Worker-side path assembly"
          }
        }
      },
      "PathsBounds": {
        "type": "object",
        "properties": {
          "max_steps": {
            "type": "integer",
            "example": 5
          },
          "entry_limit": {
            "type": "integer",
            "example": 10
          },
          "path_limit": {
            "type": "integer",
            "example": 5
          },
          "candidate_session_cap": {
            "type": "integer",
            "example": 5000
          }
        }
      },
      "PathNode": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "page",
              "event",
              "goal",
              "drop_off",
              "truncated"
            ],
            "example": "page"
          },
          "value": {
            "type": "string",
            "example": "/pricing",
            "description": "For `drop_off` and `truncated` terminal nodes, this is the exit page when known, otherwise `unknown`."
          },
          "exit_page": {
            "type": [
              "string",
              "null"
            ],
            "example": "/pricing",
            "description": "Present on `drop_off` and `truncated` terminal nodes to tie path drop-off behavior to the actual session exit page."
          },
          "sessions": {
            "type": "integer",
            "example": 42
          },
          "conversions": {
            "type": "integer",
            "example": 13
          },
          "conversion_rate": {
            "type": "number",
            "example": 0.31
          },
          "children": {
            "type": "array",
            "description": "Child path nodes. The runtime shape matches `PathNode`; the schema avoids a circular `$ref` so generated docs can render reliably.",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          }
        }
      },
      "PathExitPage": {
        "type": "object",
        "properties": {
          "exit_page": {
            "type": "string",
            "example": "/pricing"
          },
          "sessions": {
            "type": "integer",
            "example": 42
          },
          "conversions": {
            "type": "integer",
            "example": 13
          },
          "conversion_rate": {
            "type": "number",
            "example": 0.31
          },
          "drop_offs": {
            "type": "integer",
            "example": 29
          },
          "drop_off_rate": {
            "type": "number",
            "example": 0.69
          }
        }
      },
      "PathEntry": {
        "type": "object",
        "properties": {
          "entry_page": {
            "type": "string",
            "example": "/landing"
          },
          "sessions": {
            "type": "integer",
            "example": 120
          },
          "conversions": {
            "type": "integer",
            "example": 32
          },
          "conversion_rate": {
            "type": "number",
            "example": 0.267
          },
          "exit_pages": {
            "type": "array",
            "description": "Exit pages reached by sessions that started on this entry page, with conversion and drop-off attribution.",
            "items": {
              "$ref": "#/components/schemas/PathExitPage"
            }
          },
          "tree": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PathNode"
            }
          }
        }
      },
      "PathsResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "goal_event": {
            "type": "string",
            "example": "signup"
          },
          "period": {
            "type": "object",
            "properties": {
              "from": {
                "type": "string",
                "format": "date",
                "example": "2026-03-11"
              },
              "to": {
                "type": "string",
                "format": "date",
                "example": "2026-04-10"
              }
            }
          },
          "bounds": {
            "$ref": "#/components/schemas/PathsBounds"
          },
          "entry_paths": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PathEntry"
            }
          }
        }
      },
      "PageRow": {
        "type": "object",
        "properties": {
          "page": {
            "type": "string",
            "example": "/pricing"
          },
          "sessions": {
            "type": "integer"
          },
          "bounces": {
            "type": "integer"
          },
          "bounce_rate": {
            "type": "number",
            "example": 0.45,
            "description": "Bounce rate computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n"
          },
          "avg_duration": {
            "type": "number",
            "description": "Average session duration in milliseconds"
          },
          "avg_events": {
            "type": "number"
          }
        }
      },
      "SessionDistributionResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "distribution": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bucket": {
                  "type": "string",
                  "enum": [
                    "0s",
                    "1-10s",
                    "10-30s",
                    "30-60s",
                    "1-3m",
                    "3-10m",
                    "10m+"
                  ]
                },
                "sessions": {
                  "type": "integer"
                },
                "bounces": {
                  "type": "integer",
                  "description": "Number of bounce sessions in this duration bucket (computed from event names at query time)."
                },
                "avg_events": {
                  "type": "number"
                },
                "pct": {
                  "type": "number",
                  "description": "Percentage of total sessions"
                }
              }
            }
          },
          "median_bucket": {
            "type": [
              "string",
              "null"
            ]
          },
          "engaged_pct": {
            "type": "number",
            "description": "Percentage of sessions >= 30 seconds"
          }
        }
      },
      "HeatmapResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "heatmap": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "day": {
                  "type": "integer",
                  "description": "Day of week (0=Sunday, 6=Saturday)"
                },
                "day_name": {
                  "type": "string",
                  "example": "Monday"
                },
                "hour": {
                  "type": "integer",
                  "description": "Hour of day (0-23)"
                },
                "events": {
                  "type": "integer"
                },
                "users": {
                  "type": "integer"
                }
              }
            }
          },
          "peak": {
            "type": [
              "object",
              "null"
            ],
            "properties": {
              "day": {
                "type": "integer"
              },
              "day_name": {
                "type": "string"
              },
              "hour": {
                "type": "integer"
              },
              "events": {
                "type": "integer"
              },
              "users": {
                "type": "integer"
              }
            }
          },
          "busiest_day": {
            "type": [
              "string",
              "null"
            ],
            "example": "Monday"
          },
          "busiest_hour": {
            "type": [
              "integer",
              "null"
            ],
            "example": 14
          }
        }
      },
      "FunnelRequest": {
        "type": "object",
        "required": [
          "project",
          "steps"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name",
            "example": "my-site"
          },
          "steps": {
            "type": "array",
            "description": "Funnel steps (2-8). Each step has an event name and optional property filters.",
            "minItems": 2,
            "maxItems": 8,
            "items": {
              "type": "object",
              "required": [
                "event"
              ],
              "properties": {
                "event": {
                  "type": "string",
                  "description": "Event name for this step",
                  "example": "page_view"
                },
                "filters": {
                  "type": "array",
                  "description": "Optional property filters for this step",
                  "items": {
                    "type": "object",
                    "required": [
                      "property",
                      "op",
                      "value"
                    ],
                    "properties": {
                      "property": {
                        "type": "string",
                        "description": "Property key (alphanumeric + underscores, max 128 chars)",
                        "example": "path"
                      },
                      "op": {
                        "type": "string",
                        "enum": [
                          "eq",
                          "neq",
                          "contains"
                        ],
                        "description": "Filter operator",
                        "example": "eq"
                      },
                      "value": {
                        "type": "string",
                        "description": "Filter value",
                        "example": "/pricing"
                      }
                    }
                  }
                }
              }
            }
          },
          "conversion_window_hours": {
            "type": "number",
            "description": "Max hours from step 1 entry to final step (1-8760, default 168 = 7 days)",
            "default": 168,
            "minimum": 1,
            "maximum": 8760
          },
          "since": {
            "type": "string",
            "description": "Lookback period (ISO date or shorthand like '30d'). Default: 30d",
            "default": "30d",
            "example": "30d"
          },
          "count_by": {
            "type": "string",
            "enum": [
              "user_id",
              "session_id"
            ],
            "default": "user_id",
            "description": "Count by unique users or sessions"
          },
          "breakdown": {
            "type": "string",
            "description": "Optional property key to segment funnel by (e.g. 'variant', 'country'). Extracted from step 1 events only.",
            "example": "country"
          },
          "breakdown_limit": {
            "type": "number",
            "description": "Max breakdown groups, ordered by step 1 users descending (1-50, default 10)",
            "default": 10,
            "minimum": 1,
            "maximum": 50
          }
        }
      },
      "FunnelResponse": {
        "type": "object",
        "properties": {
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "steps": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "step": {
                  "type": "integer",
                  "example": 1
                },
                "event": {
                  "type": "string",
                  "example": "page_view"
                },
                "users": {
                  "type": "integer",
                  "description": "Number of users (or sessions) that reached this step",
                  "example": 500
                },
                "conversion_rate": {
                  "type": "number",
                  "description": "Fraction of users from previous step that reached this step (step 1 is always 1.0)",
                  "example": 0.6
                },
                "drop_off_rate": {
                  "type": "number",
                  "description": "Fraction of users lost from previous step (step 1 is always 0)",
                  "example": 0.4
                },
                "avg_time_to_next_ms": {
                  "type": [
                    "number",
                    "null"
                  ],
                  "description": "Average time in ms from this step to the next step (null for last step)",
                  "example": 3600000
                }
              }
            }
          },
          "overall_conversion_rate": {
            "type": "number",
            "description": "Fraction of step 1 users that completed the final step",
            "example": 0.12
          },
          "breakdowns": {
            "type": "array",
            "description": "Per-group funnel results (only present when `breakdown` param is set). Ordered by step 1 users descending.",
            "items": {
              "type": "object",
              "properties": {
                "value": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "description": "Breakdown property value (null for events missing the property)",
                  "example": "US"
                },
                "steps": {
                  "type": "array",
                  "description": "Same shape as top-level steps array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "step": {
                        "type": "integer"
                      },
                      "event": {
                        "type": "string"
                      },
                      "users": {
                        "type": "integer"
                      },
                      "conversion_rate": {
                        "type": "number"
                      },
                      "drop_off_rate": {
                        "type": "number"
                      },
                      "avg_time_to_next_ms": {
                        "type": [
                          "number",
                          "null"
                        ]
                      }
                    }
                  }
                },
                "overall_conversion_rate": {
                  "type": "number",
                  "description": "End-to-end conversion for this group",
                  "example": 0.15
                }
              }
            }
          }
        }
      },
      "RetentionResponse": {
        "type": "object",
        "properties": {
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "period": {
            "type": "string",
            "enum": [
              "day",
              "week",
              "month"
            ],
            "example": "week"
          },
          "cohorts": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "date": {
                  "type": "string",
                  "format": "date",
                  "description": "Start date of this cohort period",
                  "example": "2026-01-27"
                },
                "users": {
                  "type": "integer",
                  "description": "Number of users who first appeared in this period",
                  "example": 142
                },
                "retained": {
                  "type": "array",
                  "items": {
                    "type": "integer"
                  },
                  "description": "Users active in each subsequent period (index 0 = full cohort)",
                  "example": [
                    142,
                    64,
                    55,
                    46
                  ]
                },
                "rates": {
                  "type": "array",
                  "items": {
                    "type": "number"
                  },
                  "description": "Retention rate per period (retained[i] / users, rounded to 3 decimals)",
                  "example": [
                    1,
                    0.451,
                    0.387,
                    0.324
                  ]
                }
              }
            }
          },
          "average_rates": {
            "type": "array",
            "items": {
              "type": "number"
            },
            "description": "Weighted average retention rate per period offset (weighted by cohort size)",
            "example": [
              1,
              0.441,
              0.373,
              0.324
            ]
          },
          "users_analyzed": {
            "type": "integer",
            "description": "Total users across all cohorts (capped at 10K per query)",
            "example": 560
          }
        }
      },
      "Project": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "example": "my-site"
          },
          "project_token": {
            "type": "string",
            "example": "aat_..."
          },
          "allowed_origins": {
            "type": "string",
            "example": "*"
          },
          "total_events": {
            "type": "integer"
          },
          "total_reads": {
            "type": "integer"
          },
          "source_scan_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Website analysis id linked during project creation, when present."
          }
        }
      },
      "WebsiteScanCreateRequest": {
        "type": "object",
        "required": [
          "url"
        ],
        "properties": {
          "url": {
            "type": "string",
            "description": "Website URL to analyze. Anonymous requests are normalized to the root domain.",
            "example": "https://example.com/pricing"
          },
          "full": {
            "type": "boolean",
            "description": "Request full analysis. Requires account auth.",
            "default": false
          },
          "mode": {
            "type": "string",
            "enum": [
              "preview",
              "full"
            ],
            "description": "Request a new preview or full analysis. Existing previews cannot be upgraded."
          },
          "project": {
            "type": "string",
            "description": "Project name or id. Required for signed-in scans except complimentary Pro accounts; the URL hostname must match the project's configured `allowed_origins` for normal accounts.",
            "example": "my-site"
          }
        }
      },
      "WebsiteScanEventRecommendation": {
        "type": "object",
        "required": [
          "event",
          "priority",
          "why_this_matters_now",
          "current_blindspot",
          "unlocks_questions",
          "agent_capability_after_install",
          "properties",
          "implementation_hint"
        ],
        "properties": {
          "event": {
            "type": "string",
            "description": "Stable snake_case custom event name. Recommendations should not duplicate automatic tracker signals such as page_view.",
            "example": "signup_started"
          },
          "priority": {
            "type": "integer",
            "example": 1
          },
          "why_this_matters_now": {
            "type": "string",
            "example": "This marks the moment intent becomes commitment."
          },
          "current_blindspot": {
            "type": "string",
            "example": "You cannot see whether CTA clicks turn into signup attempts."
          },
          "unlocks_questions": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "example": [
              "Which pages create signup starts?",
              "Where does signup intent drop?"
            ]
          },
          "agent_capability_after_install": {
            "type": "string",
            "example": "Your agent can detect where intent drops before account creation."
          },
          "properties": {
            "type": "array",
            "description": "Practical property names to capture with the event. Automatic tracker properties such as path, referrer, UTMs, device fields, country, session IDs, and first-touch attribution are already present on every event.",
            "items": {
              "type": "string"
            },
            "example": [
              "page_path",
              "entry_source",
              "auth_method"
            ]
          },
          "implementation_hint": {
            "type": "string",
            "description": "Tracker-aware implementation guidance, for example data-aa-event attributes, data-aa-impression attributes, window.aa.track(...), server-side tracking for durable outcomes, aa.identify()/aa.set(...) after auth, or script opt-ins when they unlock a concrete decision."
          }
        }
      },
      "WebsiteScanResult": {
        "type": "object",
        "description": "Decision-oriented instrumentation plan. Preview responses cap `minimum_viable_instrumentation` at 3-5 events; full results cap it at 5-8 events. Recommendations are tracker-aware and should not spend custom event slots on automatic page_view, attribution, device, geography, session, or visitor fields.",
        "properties": {
          "framing": {
            "type": "string",
            "example": "fastest_path_to_useful_analytics"
          },
          "normalized_url": {
            "type": "string",
            "example": "https://example.com/"
          },
          "hostname": {
            "type": "string",
            "example": "example.com"
          },
          "current_blindspots": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "minimum_viable_instrumentation": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/WebsiteScanEventRecommendation"
            }
          },
          "not_needed_yet": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "event": {
                  "type": "string"
                },
                "reason": {
                  "type": "string"
                },
                "revisit_when": {
                  "type": "string"
                }
              }
            }
          },
          "goal_driven_funnels": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "steps": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "decision": {
                  "type": "string"
                },
                "bottleneck_detection": {
                  "type": "string"
                }
              }
            }
          },
          "after_install_agent_behavior": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "business_events_later": {
            "type": "array",
            "description": "Valuable inferred product, backend, or post-signup events that are not part of the first supplied-page install list.",
            "items": {
              "type": "object",
              "properties": {
                "event": {
                  "type": "string"
                },
                "why": {
                  "type": "string"
                },
                "where_to_instrument": {
                  "type": "string"
                }
              }
            }
          },
          "advanced_tracking_later": {
            "type": "array",
            "description": "Agent Analytics tracker capabilities to consider after the first useful page event is installed.",
            "items": {
              "type": "object",
              "properties": {
                "capability": {
                  "type": "string",
                  "example": "data-aa-impression"
                },
                "why": {
                  "type": "string"
                },
                "implementation_hint": {
                  "type": "string"
                }
              }
            }
          },
          "suggested_ab_tests": {
            "type": "array",
            "description": "Compact experiment ideas tied to the recommended page UI events.",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "hypothesis": {
                  "type": "string"
                },
                "variants": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "success_event": {
                  "type": "string"
                }
              }
            }
          },
          "analytics_detected": {
            "type": "object",
            "description": "Supporting context only; the recommendation does not lead with detected providers."
          }
        }
      },
      "WebsiteScanResponse": {
        "type": "object",
        "properties": {
          "ok": {
            "type": "boolean",
            "example": true
          },
          "analysis_id": {
            "type": "string",
            "example": "scan_..."
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "running",
              "succeeded",
              "failed"
            ],
            "example": "succeeded"
          },
          "mode": {
            "type": "string",
            "example": "anonymous_preview"
          },
          "normalized_url": {
            "type": "string",
            "example": "https://example.com/"
          },
          "hostname": {
            "type": "string",
            "example": "example.com"
          },
          "cached": {
            "type": "boolean"
          },
          "resume_token": {
            "type": "string",
            "description": "Present only when creating a new anonymous preview. Store the token securely; the server stores only its hash.",
            "example": "rst_..."
          },
          "preview": {
            "$ref": "#/components/schemas/WebsiteScanResult"
          },
          "result": {
            "$ref": "#/components/schemas/WebsiteScanResult"
          },
          "agent_handoff": {
            "type": "object",
            "properties": {
              "label": {
                "type": "string",
                "example": "Give your agent analytics judgment"
              },
              "prompt": {
                "type": "string"
              }
            }
          }
        }
      },
      "WebsiteScanBusyError": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Error"
          },
          {
            "type": "object",
            "properties": {
              "retry_after_seconds": {
                "type": "integer",
                "example": 30
              }
            }
          }
        ]
      },
      "LiveSnapshotResponse": {
        "type": "object",
        "properties": {
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "window_seconds": {
            "type": "integer",
            "example": 60
          },
          "timestamp": {
            "type": "number",
            "example": 1708000060000
          },
          "active_visitors": {
            "type": "integer",
            "description": "Unique user_ids in the time window",
            "example": 12
          },
          "active_sessions": {
            "type": "integer",
            "description": "Unique session_ids in the time window",
            "example": 8
          },
          "events_per_minute": {
            "type": "integer",
            "example": 47
          },
          "top_pages": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "path": {
                  "type": "string",
                  "example": "/"
                },
                "visitors": {
                  "type": "integer",
                  "example": 5
                }
              }
            }
          },
          "top_events": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "event": {
                  "type": "string",
                  "example": "page_view"
                },
                "count": {
                  "type": "integer",
                  "example": 32
                }
              }
            }
          },
          "recent_events": {
            "type": "array",
            "description": "Last 10 events, newest first",
            "items": {
              "type": "object",
              "properties": {
                "event": {
                  "type": "string"
                },
                "properties": {
                  "type": [
                    "object",
                    "null"
                  ]
                },
                "user_id": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "timestamp": {
                  "type": "number"
                }
              }
            }
          }
        }
      },
      "AllSitesPeriod": {
        "type": "object",
        "properties": {
          "label": {
            "type": "string",
            "enum": [
              "1d",
              "7d",
              "14d",
              "30d",
              "90d"
            ],
            "example": "7d"
          },
          "from": {
            "type": "string",
            "format": "date",
            "example": "2026-03-03"
          },
          "to": {
            "type": "string",
            "format": "date",
            "example": "2026-03-09"
          },
          "previous_from": {
            "type": "string",
            "format": "date",
            "example": "2026-02-24"
          },
          "previous_to": {
            "type": "string",
            "format": "date",
            "example": "2026-03-02"
          }
        }
      },
      "AllSitesMetricDelta": {
        "type": "object",
        "properties": {
          "current": {
            "type": "integer",
            "example": 120
          },
          "previous": {
            "type": "integer",
            "example": 90
          },
          "change": {
            "type": "integer",
            "example": 30
          },
          "change_pct": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 33
          }
        }
      },
      "AllSitesSummary": {
        "type": "object",
        "properties": {
          "total_projects": {
            "type": "integer",
            "example": 3
          },
          "active_projects": {
            "type": "integer",
            "example": 2
          },
          "total_events": {
            "$ref": "#/components/schemas/AllSitesMetricDelta"
          }
        }
      },
      "AllSitesTimeSeriesPoint": {
        "type": "object",
        "properties": {
          "date": {
            "type": "string",
            "format": "date",
            "example": "2026-03-09"
          },
          "events": {
            "type": "integer",
            "example": 40
          }
        }
      },
      "AllSitesProjectSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "proj_123"
          },
          "name": {
            "type": "string",
            "example": "my-site"
          },
          "events": {
            "type": "integer",
            "example": 80
          },
          "share_pct": {
            "type": "number",
            "example": 66.7
          },
          "last_active_date": {
            "oneOf": [
              {
                "type": "string",
                "format": "date"
              },
              {
                "type": "null"
              }
            ],
            "example": "2026-03-09"
          }
        }
      },
      "AllSitesOverviewResponse": {
        "type": "object",
        "properties": {
          "scope": {
            "type": "string",
            "enum": [
              "account"
            ],
            "example": "account"
          },
          "period": {
            "$ref": "#/components/schemas/AllSitesPeriod"
          },
          "summary": {
            "$ref": "#/components/schemas/AllSitesSummary"
          },
          "time_series": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AllSitesTimeSeriesPoint"
            }
          },
          "projects": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AllSitesProjectSummary"
            }
          },
          "remaining_projects": {
            "type": "integer",
            "example": 1
          }
        }
      },
      "BotTrafficMetricDelta": {
        "type": "object",
        "properties": {
          "current": {
            "type": "integer",
            "example": 5
          },
          "previous": {
            "type": "integer",
            "example": 1
          },
          "change": {
            "type": "integer",
            "example": 4
          },
          "change_pct": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 400
          }
        }
      },
      "BotTrafficTimeSeriesPoint": {
        "type": "object",
        "properties": {
          "date": {
            "type": "string",
            "format": "date",
            "example": "2026-03-13"
          },
          "requests": {
            "type": "integer",
            "example": 5
          },
          "dropped_events": {
            "type": "integer",
            "example": 7
          }
        }
      },
      "BotTrafficCategorySummary": {
        "type": "object",
        "properties": {
          "category": {
            "type": "string",
            "example": "ai_agent"
          },
          "requests": {
            "type": "integer",
            "example": 3
          },
          "dropped_events": {
            "type": "integer",
            "example": 5
          },
          "share_pct": {
            "type": "number",
            "example": 60
          }
        }
      },
      "BotTrafficActorSummary": {
        "type": "object",
        "properties": {
          "actor": {
            "type": "string",
            "example": "ChatGPT-User"
          },
          "category": {
            "type": "string",
            "example": "ai_agent"
          },
          "requests": {
            "type": "integer",
            "example": 3
          },
          "dropped_events": {
            "type": "integer",
            "example": 5
          },
          "last_seen_at": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 1773459600000
          }
        }
      },
      "BotTrafficProjectSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "proj_123"
          },
          "name": {
            "type": "string",
            "example": "my-site"
          },
          "requests": {
            "type": "integer",
            "example": 3
          },
          "dropped_events": {
            "type": "integer",
            "example": 4
          },
          "share_pct": {
            "type": "number",
            "example": 60
          },
          "last_seen_at": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 1773459600000
          }
        }
      },
      "BotTrafficProjectSummaryMetrics": {
        "type": "object",
        "properties": {
          "automated_requests": {
            "$ref": "#/components/schemas/BotTrafficMetricDelta"
          },
          "dropped_events": {
            "$ref": "#/components/schemas/BotTrafficMetricDelta"
          },
          "last_seen_at": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 1773459600000
          }
        }
      },
      "BotTrafficAccountSummary": {
        "type": "object",
        "properties": {
          "automated_requests": {
            "$ref": "#/components/schemas/BotTrafficMetricDelta"
          },
          "dropped_events": {
            "$ref": "#/components/schemas/BotTrafficMetricDelta"
          },
          "active_projects": {
            "type": "integer",
            "example": 1
          },
          "total_projects": {
            "type": "integer",
            "example": 4
          },
          "last_seen_at": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "example": 1773459600000
          }
        }
      },
      "BotTrafficOverviewResponse": {
        "type": "object",
        "properties": {
          "scope": {
            "type": "string",
            "enum": [
              "project"
            ],
            "example": "project"
          },
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "project_context": {
            "$ref": "#/components/schemas/ProjectContext"
          },
          "period": {
            "$ref": "#/components/schemas/AllSitesPeriod"
          },
          "summary": {
            "$ref": "#/components/schemas/BotTrafficProjectSummaryMetrics"
          },
          "categories": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficCategorySummary"
            }
          },
          "actors": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficActorSummary"
            }
          },
          "time_series": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficTimeSeriesPoint"
            }
          }
        }
      },
      "AllSitesBotTrafficOverviewResponse": {
        "type": "object",
        "properties": {
          "scope": {
            "type": "string",
            "enum": [
              "account"
            ],
            "example": "account"
          },
          "period": {
            "$ref": "#/components/schemas/AllSitesPeriod"
          },
          "summary": {
            "$ref": "#/components/schemas/BotTrafficAccountSummary"
          },
          "categories": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficCategorySummary"
            }
          },
          "projects": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficProjectSummary"
            }
          },
          "remaining_projects": {
            "type": "integer",
            "example": 3
          },
          "time_series": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BotTrafficTimeSeriesPoint"
            }
          }
        }
      },
      "AccountResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "email": {
            "type": "string"
          },
          "github_login": {
            "type": [
              "string",
              "null"
            ]
          },
          "tier": {
            "type": "string",
            "enum": [
              "free",
              "pro"
            ]
          },
          "created_at": {
            "type": "string"
          },
          "projects_count": {
            "type": "integer"
          },
          "tier_limits": {
            "type": "object",
            "properties": {
              "max_events_per_month": {
                "type": "integer"
              },
              "max_projects": {
                "type": "integer"
              },
              "max_reads_per_month": {
                "type": "integer"
              },
              "retention_days": {
                "type": "integer"
              },
              "rate_limit_rpm": {
                "type": "integer"
              }
            }
          },
          "monthly_spend_cap_dollars": {
            "type": [
              "number",
              "null"
            ]
          }
        },
        "example": {
          "id": "acc_free123",
          "email": "free@example.com",
          "github_login": "freeuser",
          "tier": "free",
          "created_at": "2026-02-01T12:00:00.000Z",
          "projects_count": 2,
          "tier_limits": {
            "max_events_per_month": 100000,
            "max_projects": 2,
            "max_reads_per_month": 500,
            "retention_days": 90,
            "rate_limit_rpm": 10
          },
          "monthly_spend_cap_dollars": null
        }
      },
      "AgentSessionStartRequest": {
        "type": "object",
        "required": [
          "client_type"
        ],
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "interactive",
              "detached"
            ],
            "default": "interactive"
          },
          "client_type": {
            "type": "string",
            "description": "Runtime type such as `cli`, `mcp`, `paperclip`, or `openclaw`.",
            "example": "cli"
          },
          "client_name": {
            "type": [
              "string",
              "null"
            ],
            "example": "Agent Analytics CLI"
          },
          "client_instance_id": {
            "type": [
              "string",
              "null"
            ],
            "example": "pid:12345"
          },
          "label": {
            "type": [
              "string",
              "null"
            ],
            "example": "Paperclip Workspace"
          },
          "callback_url": {
            "type": [
              "string",
              "null"
            ],
            "description": "Required for interactive mode. Local loopback callback URL.",
            "example": "http://127.0.0.1:43123/callback"
          },
          "project": {
            "type": "string",
            "description": "Optional project name the client is asking the owner to grant.\nWhen omitted, the approval picker preselects nothing. The owner must pick one project or All projects.\n",
            "example": "my-site"
          },
          "level": {
            "type": "string",
            "enum": [
              "read",
              "manage",
              "admin"
            ],
            "description": "Optional requested level. When omitted, the default is `read`. The owner may grant a lower or higher level.\n`read` expands to `account:read`, `projects:read`, `analytics:read`, `experiments:read`, `live:read`, `replays:read`.\n`manage` is `read` plus `projects:write`, `experiments:write`, `feedback:write`, `replays:write`, `erasures:write`.\n`admin` is `manage` plus account-level management sessions already have, such as creating projects.\nAgent sessions still cannot create, rotate, or reveal API keys, and cannot touch billing checkout.\nCreating a project needs `admin` and All projects.\n"
          },
          "scopes": {
            "type": "array",
            "description": "Requested agent-session scopes. Still accepted. The server maps them to the smallest level that covers them.\n`erasures:write` maps to `manage` and is absent from `read`.\n`analytics:read` and `projects:write` do not grant erasure.\n",
            "items": {
              "type": "string",
              "enum": [
                "account:read",
                "projects:read",
                "projects:write",
                "analytics:read",
                "experiments:read",
                "experiments:write",
                "feedback:write",
                "live:read",
                "replays:read",
                "replays:write",
                "erasures:write"
              ]
            }
          },
          "code_challenge": {
            "type": [
              "string",
              "null"
            ],
            "description": "Optional PKCE-style challenge for interactive runtimes."
          },
          "metadata": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          }
        }
      },
      "AgentSessionStartResponse": {
        "type": "object",
        "properties": {
          "ok": {
            "type": "boolean",
            "example": true
          },
          "auth_request_id": {
            "type": "string",
            "example": "req_agent123"
          },
          "authorize_url": {
            "type": "string",
            "example": "https://api.agentanalytics.sh/agent-sessions/authorize/req_agent123"
          },
          "poll_token": {
            "type": "string",
            "example": "aap_polltoken"
          },
          "mode": {
            "type": "string",
            "enum": [
              "interactive",
              "detached"
            ]
          },
          "expires_at": {
            "type": "integer",
            "example": 1775079600000
          },
          "scopes": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        }
      },
      "AgentSessionPollRequest": {
        "type": "object",
        "required": [
          "auth_request_id",
          "poll_token"
        ],
        "properties": {
          "auth_request_id": {
            "type": "string"
          },
          "poll_token": {
            "type": "string"
          }
        }
      },
      "AgentSessionPollResponse": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "approved",
              "exchanged",
              "revoked",
              "expired"
            ]
          },
          "exchange_code": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "account_id": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "approved_email": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "AgentSessionExchangeRequest": {
        "type": "object",
        "required": [
          "auth_request_id",
          "exchange_code"
        ],
        "properties": {
          "auth_request_id": {
            "type": "string"
          },
          "exchange_code": {
            "type": "string"
          },
          "code_verifier": {
            "type": [
              "string",
              "null"
            ],
            "description": "Required when the auth request was started with a code challenge."
          }
        }
      },
      "AgentSessionIssued": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "access_token": {
            "type": "string",
            "example": "aas_123"
          },
          "refresh_token": {
            "type": "string",
            "example": "aar_123"
          },
          "access_expires_at": {
            "type": "integer"
          },
          "refresh_expires_at": {
            "type": "integer"
          },
          "level": {
            "type": "string",
            "enum": [
              "read",
              "manage",
              "admin",
              "legacy"
            ],
            "description": "Granted level. `legacy` is a session created before levels. It keeps its stored scopes and all-projects access.\n",
            "example": "read"
          },
          "project": {
            "type": [
              "string",
              "null"
            ],
            "description": "Granted project name. Null means All projects. A legacy session reports null and still has all-projects access.",
            "example": "my-site"
          },
          "scopes": {
            "type": "array",
            "description": "Expanded scopes for the granted level. A legacy session returns its stored scopes.",
            "items": {
              "type": "string"
            }
          }
        }
      },
      "AgentSessionExchangeResponse": {
        "type": "object",
        "properties": {
          "ok": {
            "type": "boolean",
            "example": true
          },
          "agent_session": {
            "$ref": "#/components/schemas/AgentSessionIssued"
          },
          "account": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              },
              "email": {
                "type": "string"
              },
              "github_login": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "google_name": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "tier": {
                "type": "string",
                "enum": [
                  "free",
                  "pro"
                ]
              }
            }
          }
        }
      },
      "AgentSessionRefreshRequest": {
        "type": "object",
        "required": [
          "refresh_token"
        ],
        "properties": {
          "refresh_token": {
            "type": "string"
          }
        }
      },
      "AgentSessionRefreshResponse": {
        "type": "object",
        "properties": {
          "ok": {
            "type": "boolean",
            "example": true
          },
          "agent_session": {
            "type": "object",
            "properties": {
              "session_id": {
                "type": "string"
              },
              "access_token": {
                "type": "string"
              },
              "refresh_token": {
                "type": "string"
              },
              "access_expires_at": {
                "type": "integer"
              },
              "refresh_expires_at": {
                "type": "integer"
              },
              "account": {
                "type": "object",
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "email": {
                    "type": "string"
                  },
                  "github_login": {
                    "oneOf": [
                      {
                        "type": "string"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "google_name": {
                    "oneOf": [
                      {
                        "type": "string"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "tier": {
                    "type": "string",
                    "enum": [
                      "free",
                      "pro"
                    ]
                  }
                }
              },
              "level": {
                "type": "string",
                "enum": [
                  "read",
                  "manage",
                  "admin",
                  "legacy"
                ],
                "description": "Granted level. Refresh keeps this value. `legacy` keeps stored scopes and all-projects access."
              },
              "project": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Granted project name. Null means All projects. Refresh keeps this value."
              },
              "scopes": {
                "type": "array",
                "description": "Expanded scopes for the granted level. A legacy session returns its stored scopes.",
                "items": {
                  "type": "string"
                }
              }
            }
          }
        }
      },
      "AgentSessionSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "client_type": {
            "type": "string"
          },
          "client_name": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "client_instance_id": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "label": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "level": {
            "type": "string",
            "enum": [
              "read",
              "manage",
              "admin",
              "legacy"
            ],
            "description": "Granted level. `legacy` means the session predates levels and keeps its stored scopes and all-projects access.\n"
          },
          "project": {
            "type": [
              "string",
              "null"
            ],
            "description": "Granted project name. Null means All projects."
          },
          "scopes": {
            "type": "array",
            "description": "Expanded scopes for the granted level. A legacy session returns its stored scopes.",
            "items": {
              "type": "string"
            }
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "revoked"
            ]
          },
          "created_at": {
            "type": "integer"
          },
          "last_used_at": {
            "type": "integer"
          },
          "access_expires_at": {
            "type": "integer"
          },
          "refresh_expires_at": {
            "type": "integer"
          },
          "revoked_at": {
            "oneOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "FeedbackRequest": {
        "type": "object",
        "required": [
          "message"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Sanitized summary of the friction, missing capability, or workflow problem.",
            "example": "The agent had to calculate funnel drop-off manually instead of using a built-in report."
          },
          "project": {
            "type": "string",
            "description": "Optional project name for context.",
            "example": "my-site"
          },
          "command": {
            "type": "string",
            "description": "Optional CLI command or workflow step that led to the issue.",
            "example": "agent-analytics funnel my-site --steps \"page_view,signup,purchase\""
          },
          "context": {
            "type": "string",
            "description": "Optional sanitized context. Do not include private owner details, secrets, or raw customer data.",
            "example": "The agent understood the goal but had to compute the percentages manually."
          }
        }
      },
      "Experiment": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "exp_a1b2c3d4e5f6g7h8"
          },
          "project_id": {
            "type": "string"
          },
          "account_id": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "example": "signup_cta"
          },
          "variants": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "key": {
                  "type": "string",
                  "example": "control"
                },
                "weight": {
                  "type": "integer",
                  "example": 50
                }
              }
            }
          },
          "goal_event": {
            "type": "string",
            "example": "signup"
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "paused",
              "completed"
            ],
            "example": "active"
          },
          "winner": {
            "type": [
              "string",
              "null"
            ],
            "description": "Variant key, set when status is completed"
          },
          "created_at": {
            "type": "string"
          },
          "updated_at": {
            "type": "string"
          },
          "completed_at": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "ExperimentResults": {
        "type": "object",
        "properties": {
          "variants": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "key": {
                  "type": "string",
                  "example": "control"
                },
                "exposures": {
                  "type": "integer",
                  "example": 520
                },
                "unique_users": {
                  "type": "integer",
                  "example": 480
                },
                "conversions": {
                  "type": "integer",
                  "example": 48
                },
                "conversion_rate": {
                  "type": "number",
                  "example": 0.1
                }
              }
            }
          },
          "probability_best": {
            "type": "object",
            "additionalProperties": {
              "type": "number"
            },
            "example": {
              "control": 0.06,
              "new_cta": 0.94
            }
          },
          "lift": {
            "type": "object",
            "additionalProperties": {
              "type": "number"
            },
            "example": {
              "control": -0.32,
              "new_cta": 0.47
            }
          },
          "sufficient_data": {
            "type": "boolean",
            "example": true
          },
          "recommendation": {
            "type": "string",
            "example": "'new_cta' is the winner with 94% probability (47% lift over baseline)"
          }
        }
      },
      "ErasureCounts": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "events",
          "sessions",
          "identity_rows",
          "profiles",
          "email_lookups",
          "replay_sessions",
          "replay_objects"
        ],
        "properties": {
          "events": {
            "type": "integer",
            "minimum": 0
          },
          "sessions": {
            "type": "integer",
            "minimum": 0
          },
          "identity_rows": {
            "type": "integer",
            "minimum": 0
          },
          "profiles": {
            "type": "integer",
            "minimum": 0
          },
          "email_lookups": {
            "type": "integer",
            "minimum": 0
          },
          "replay_sessions": {
            "type": "integer",
            "minimum": 0
          },
          "replay_objects": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "ErasureReceipt": {
        "type": "object",
        "additionalProperties": false,
        "description": "Pollable receipt. It echoes `subject_type` and counts.\nIt omits the subject value, event payloads, property JSON, and the raw email.\n",
        "required": [
          "id",
          "status",
          "project",
          "subject_type",
          "counts",
          "replay_included"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "Erasure id (`era_...`).",
            "example": "era_01HZX"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "running",
              "completed",
              "failed"
            ]
          },
          "project": {
            "type": "string",
            "example": "my-site"
          },
          "subject_type": {
            "type": "string",
            "enum": [
              "user_id",
              "session_id",
              "email"
            ]
          },
          "counts": {
            "$ref": "#/components/schemas/ErasureCounts"
          },
          "replay_included": {
            "type": "boolean"
          },
          "completed_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "Set when `status` is `completed` or `failed`."
          },
          "error": {
            "type": [
              "string",
              "null"
            ],
            "description": "Set when `status` is `failed`."
          }
        }
      },
      "ErasureCreateRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "idempotency_key",
          "confirm"
        ],
        "properties": {
          "project": {
            "type": "string",
            "description": "Project name. Event and session deletes use this name. Email lookup deletes use `scope_id = project:<uuid>` for this project.",
            "example": "my-site"
          },
          "idempotency_key": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256,
            "description": "Required. Unique per account. The same key and the same body return the original job. A retry of a failed job continues. The same key with a different body is `409` `IDEMPOTENCY_CONFLICT`.",
            "example": "erase-user-123-2026-11-13"
          },
          "confirm": {
            "type": "string",
            "const": "erase",
            "description": "Must be the string `erase`."
          },
          "user_id": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256,
            "description": "Exact user id. One subject per request. Walks `identity_map` and `identity_aliases` once, then deletes this project's events, sessions, identity rows, profiles, and email lookup rows.",
            "example": "user_123"
          },
          "session_id": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256,
            "description": "Exact session id. Deletes events, sessions, and replay for that session, with no identity graph walk.",
            "example": "sess_123"
          },
          "email": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256,
            "description": "Normalized and HMAC'd the same way project email lookup is built, then the user id path runs. The raw email is not stored on the job and is not returned.",
            "example": "visitor@example.com"
          },
          "include_replays": {
            "type": "boolean",
            "default": true,
            "description": "Delete replay sessions and objects for the subject's sessions. Default true."
          },
          "portfolio": {
            "type": "boolean",
            "default": false,
            "description": "Email only. Default false keeps the erasure inside this project. `true` uses the portfolio HMAC and loops member projects."
          },
          "confirm_large": {
            "type": "boolean",
            "description": "Required true when the subject matches more than 100,000 events. Otherwise `400` `CONFIRM_LARGE_REQUIRED`."
          }
        }
      },
      "ErasureList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "project",
          "erasures"
        ],
        "properties": {
          "project": {
            "type": "string"
          },
          "erasures": {
            "type": "array",
            "maxItems": 100,
            "description": "Newest first, at most 100 receipts. No subject values and no raw email.",
            "items": {
              "$ref": "#/components/schemas/ErasureReceipt"
            }
          }
        }
      }
    },
    "parameters": {
      "ProjectParam": {
        "name": "project",
        "in": "query",
        "required": true,
        "description": "Project name",
        "schema": {
          "type": "string"
        },
        "example": "my-site"
      },
      "SinceParam": {
        "name": "since",
        "in": "query",
        "required": false,
        "description": "Start date. Accepts ISO 8601 (`2025-01-01`) or shorthand (`7d`, `30d`). Defaults to 7 days ago.",
        "schema": {
          "type": "string"
        },
        "example": "7d"
      },
      "LimitParam": {
        "name": "limit",
        "in": "query",
        "required": false,
        "description": "Max results to return (1-1000, default 100)",
        "schema": {
          "type": "integer",
          "default": 100,
          "minimum": 1,
          "maximum": 1000
        }
      },
      "ApiVersion": {
        "name": "AA-Version",
        "in": "header",
        "required": false,
        "description": "Optional API version. The only current value is `1`. Omitting the header, or sending a blank value, selects version `1`. Read and management routes return `400` `UNKNOWN_API_VERSION` for any other value. Ingest, tracker, beacon, collect, and replay-recording routes ignore the header. Every response includes `AA-Version: 1`. Policy: https://docs.agentanalytics.sh/reference/api-versioning/\n",
        "schema": {
          "type": "string",
          "enum": [
            "1"
          ],
          "default": "1"
        },
        "example": "1"
      },
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": false,
        "description": "Optional retry key for this write. The hosted API stores the completed response for 24 hours and replays it when the same authenticated grant, method, path, and key are sent again with the same body. A replay includes the response header `Idempotent-Replayed: true`.\n\nThe key is 1 to 255 printable ASCII characters and must not contain spaces. The same key with a different body returns `422` `IDEMPOTENCY_MISMATCH`. A second request while the first is still running returns `409` `IDEMPOTENCY_IN_PROGRESS` and `Retry-After`. A key outside that format returns `400` `VALIDATION_ERROR`. Sending the header without an authenticated grant returns `401` `AUTH_REQUIRED`. On ingestion routes the project token in the body counts as that grant.\n\nRoutes that do not list this parameter ignore the header. That includes auth, billing, erasure, credential issuance, and read-style POSTs such as `/query`, `/sql`, `/funnel`, and `/paths`. Erasure keeps its own body field `idempotency_key`.\n",
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 255,
          "pattern": "^[!-~]{1,255}$"
        },
        "example": "8f14e45fceea4f6e9c3a6d5b1a2c9e70"
      }
    },
    "headers": {
      "IdempotentReplayed": {
        "description": "Set to true when this response is a stored replay of an earlier request with the same Idempotency-Key.",
        "schema": {
          "type": "string",
          "enum": [
            "true"
          ]
        },
        "example": "true"
      },
      "RetryAfter": {
        "description": "Seconds to wait before retrying a request that returned 409 IDEMPOTENCY_IN_PROGRESS.",
        "schema": {
          "type": "integer",
          "minimum": 0
        },
        "example": 2
      },
      "RetryAfterLimit": {
        "description": "Seconds to wait before retrying. Every `429` includes `Retry-After`. A per-minute window sends the seconds left in that window. Stream concurrency sends `1800`.\n",
        "schema": {
          "type": "integer",
          "minimum": 0
        },
        "example": 60
      },
      "RateLimit": {
        "description": "Remaining quota on this response, as an IETF structured-field list. `r` is the remaining requests. `t` is the seconds until the window resets. The default pair is the free and pro request rates. A route-specific policy replaces that pair. Captured from a read route: `\"free\";r=10;t=60, \"pro\";r=1000;t=60`.\n",
        "schema": {
          "type": "string"
        },
        "example": "\"free\";r=10;t=60, \"pro\";r=1000;t=60"
      },
      "RateLimitPolicy": {
        "description": "Quota and window for this response. `q` is the quota. `w` is the window in seconds. The default is `\"free\";q=10;w=60, \"pro\";q=1000;w=60`. A route-specific policy replaces that pair. `POST /demo/session` sends `\"demo-session\";q=30;w=60`.\n",
        "schema": {
          "type": "string"
        },
        "example": "\"free\";q=10;w=60, \"pro\";q=1000;w=60"
      }
    },
    "responses": {
      "IdempotencyMismatch": {
        "description": "This Idempotency-Key was already used with a different request body.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "IDEMPOTENCY_MISMATCH",
              "message": "Idempotency-Key was already used with a different request body"
            }
          }
        }
      },
      "IdempotencyInProgress": {
        "description": "This Idempotency-Key is already in progress. Wait for Retry-After, then send the same request again.",
        "headers": {
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "IDEMPOTENCY_IN_PROGRESS",
              "message": "Idempotency-Key is already in progress"
            }
          }
        }
      }
    }
  },
  "paths": {
    "/agent-sessions/start": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "startAgentSession",
        "summary": "Start an agent-session signup/login flow",
        "description": "Creates a pending auth request for a CLI, MCP client, or managed runtime.\n\nOptional `project` (name) and `level` (`read`, `manage`, or `admin`) are the client's request. `scopes` still work and map to the smallest level that covers them. With neither project nor level, the level is `read` and the project picker preselects nothing.\nThe OAuth and MCP start path passes `project` and `level` only when the client supplies them.\n\nUse `mode=interactive` when the runtime can receive a localhost/browser callback.\nUse `mode=detached` when the runtime must wait for approval by polling or manual exchange.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgentSessionStartRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Auth request created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgentSessionStartResponse"
                },
                "example": {
                  "ok": true,
                  "auth_request_id": "req_agent123",
                  "authorize_url": "https://api.agentanalytics.sh/agent-sessions/authorize/req_agent123",
                  "poll_token": "aap_polltoken",
                  "mode": "interactive",
                  "expires_at": 1775079600000
                }
              }
            }
          },
          "400": {
            "description": "Invalid request payload",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/agent-sessions/authorize/{id}": {
      "get": {
        "operationId": "authorizeAgentSession",
        "summary": "Browser approval page for an auth request",
        "description": "Human-facing browser entry for agent signup/login approval.\n\nThe owner sees the client name, picks one project or All projects, and picks a level (`read`, `manage`, or `admin`). Each level has one short explanation. `manage` and `admin` say they can permanently erase user data. The owner may grant less or more than requested. The server checks that the project belongs to the account.\n\nThe response is HTML and lets the user continue with Google or GitHub OAuth. This endpoint is usually opened from the `authorize_url` returned by `POST /agent-sessions/start`.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "HTML approval page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Auth request not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Auth request expired",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/agent-sessions/poll": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "pollAgentSession",
        "summary": "Poll detached auth status",
        "description": "Checks whether a detached auth request has been approved, exchanged, revoked, or expired.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgentSessionPollRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Auth request status",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgentSessionPollResponse"
                },
                "example": {
                  "status": "pending"
                }
              }
            }
          },
          "401": {
            "description": "Invalid poll token or auth request",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Auth request revoked or expired",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgentSessionPollResponse"
                }
              }
            }
          }
        }
      }
    },
    "/agent-sessions/exchange": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "exchangeAgentSession",
        "summary": "Exchange an approved auth request for an agent session",
        "description": "Redeems an approved auth request into a renewable agent session.\n\nThe response returns `level`, `project` (name or null), and the expanded `scopes`.\n\nInteractive runtimes should send the matching `code_verifier` when the start request included a `code_challenge`.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgentSessionExchangeRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Agent session issued",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgentSessionExchangeResponse"
                },
                "example": {
                  "ok": true,
                  "agent_session": {
                    "access_token": "aas_123",
                    "refresh_token": "aar_123",
                    "level": "read",
                    "project": "my-site"
                  },
                  "account": {
                    "tier": "free"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Auth request is not ready",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Invalid exchange code or code verifier",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Auth request has already been exchanged",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Auth request expired",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/agent-sessions/refresh": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "refreshAgentSession",
        "summary": "Refresh an agent session access token",
        "description": "Exchanges a valid refresh token for a new access token while keeping the same logical agent session, the same project, and the same level.\nAccess tokens last 1 hour. Refresh tokens last 30 days.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgentSessionRefreshRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Session refreshed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgentSessionRefreshResponse"
                },
                "example": {
                  "ok": true,
                  "agent_session": {
                    "account": {
                      "tier": "free"
                    },
                    "level": "read"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Missing refresh token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Invalid or expired refresh token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/agent-sessions/revoke": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "revokeAgentSession",
        "summary": "Revoke an agent session",
        "description": "Revokes one active agent session owned by the authenticated account.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "session_id"
                ],
                "properties": {
                  "session_id": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Session revoked",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "session_id": {
                      "type": "string"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Session not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/demo/session": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "createDemoSession",
        "summary": "Mint a short-lived read-only sandbox session",
        "description": "Public sandbox entry point for the seeded project `agentanalytics-demo`. No account and no API key. POST an empty JSON body.\n\nThe access token is an `aas_*` session that lasts 15 minutes. Its scopes are `account:read`, `projects:read`, `analytics:read`, and `experiments:read`. Reads stay on `agentanalytics-demo`. Writes with this session return `403` `DEMO_READ_ONLY`.\n\nThis route ignores `Idempotency-Key`. Auth, billing, erasure, credential, and read-style POST routes ignore it as well.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "Read-only demo session for agentanalytics-demo",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "ok",
                    "mode",
                    "agent_session",
                    "projects"
                  ],
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "const": true
                    },
                    "mode": {
                      "type": "string",
                      "const": "demo"
                    },
                    "agent_session": {
                      "type": "object",
                      "required": [
                        "access_token",
                        "access_expires_at",
                        "scopes"
                      ],
                      "properties": {
                        "access_token": {
                          "type": "string",
                          "description": "Short-lived `aas_*` access token.",
                          "example": "aas_example"
                        },
                        "access_expires_at": {
                          "type": "integer",
                          "description": "Unix time in milliseconds when the access token expires.",
                          "example": 1796371500000
                        },
                        "scopes": {
                          "type": "array",
                          "items": {
                            "type": "string"
                          },
                          "example": [
                            "account:read",
                            "projects:read",
                            "analytics:read",
                            "experiments:read"
                          ]
                        }
                      }
                    },
                    "projects": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "name"
                        ],
                        "properties": {
                          "name": {
                            "type": "string",
                            "const": "agentanalytics-demo"
                          }
                        }
                      }
                    },
                    "commands": {
                      "type": "array",
                      "description": "Sample read commands against the demo project.",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "mode": "demo",
                  "agent_session": {
                    "access_token": "aas_example",
                    "access_expires_at": 1796371500000,
                    "scopes": [
                      "account:read",
                      "projects:read",
                      "analytics:read",
                      "experiments:read"
                    ]
                  },
                  "projects": [
                    {
                      "name": "agentanalytics-demo"
                    }
                  ]
                }
              }
            }
          },
          "429": {
            "description": "Too many demo sessions from this client",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "description": "Seconds to wait before requesting another demo session.",
                "schema": {
                  "type": "integer",
                  "minimum": 0
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "RATE_LIMITED",
                  "message": "rate limit exceeded"
                }
              }
            }
          },
          "503": {
            "description": "Public demo is not configured",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "DEMO_NOT_CONFIGURED",
                  "message": "public demo is not configured"
                }
              }
            }
          }
        }
      }
    },
    "/track": {
      "post": {
        "operationId": "trackEvent",
        "summary": "Track a single event",
        "description": "Record an event. Called automatically by the `tracker.js` script running in your visitors' browsers — you don't need to call this directly.\n\nAdd the tracker to your site and it handles everything:\n```html\n<script defer src=\"https://api.agentanalytics.sh/tracker.js\"\n        data-project=\"my-site\" data-token=\"aat_...\"\n        data-track-vitals=\"true\"></script>\n```\n\nThe response is `202 Accepted` — events are queued and written asynchronously.\n\nAutomated traffic that reaches this endpoint is filtered out of normal analytics and reported separately via `/bot-traffic` and `/account/bot-traffic`.\n",
        "tags": [
          "Ingestion"
        ],
        "security": [],
        "x-codeSamples": [
          {
            "lang": "html",
            "label": "Tracker Snippet",
            "source": "<script defer src=\"https://api.agentanalytics.sh/tracker.js\"\n        data-project=\"my-site\"\n        data-token=\"aat_...\"\n        data-track-vitals=\"true\"></script>\n"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TrackRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "202": {
            "description": "Event queued",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "queued": {
                      "type": "boolean",
                      "example": true
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "queued": true
                }
              }
            }
          },
          "400": {
            "description": "Validation error (missing fields, invalid event name, properties too large)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Invalid or missing token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "429": {
            "description": "Rate limited",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Error"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "reason": {
                          "type": "string",
                          "enum": [
                            "rate_limit",
                            "lifetime_event_limit",
                            "monthly_spend_cap"
                          ]
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/track/batch": {
      "post": {
        "operationId": "trackBatch",
        "summary": "Track multiple events",
        "description": "Record up to 100 events in a single request. All events must use the same project token.\nIf a client buffers more than 100 events, such as while waiting for tracking consent, split the buffer into multiple `/track/batch` requests.\n\nLike `/track`, this is called by the browser tracker — not by agents or CLI.\n\nAutomated traffic that reaches this endpoint is filtered out of normal analytics and reported separately via `/bot-traffic` and `/account/bot-traffic`.\n",
        "tags": [
          "Ingestion"
        ],
        "security": [],
        "x-codeSamples": [
          {
            "lang": "html",
            "label": "Tracker Snippet",
            "source": "<!-- The tracker batches events automatically -->\n<script defer src=\"https://api.agentanalytics.sh/tracker.js\"\n        data-project=\"my-site\"\n        data-token=\"aat_...\"\n        data-track-vitals=\"true\"></script>\n"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TrackBatchRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "202": {
            "description": "Events queued",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "queued": {
                      "type": "boolean",
                      "example": true
                    },
                    "count": {
                      "type": "integer",
                      "example": 5
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "queued": true,
                  "count": 5
                }
              }
            }
          },
          "400": {
            "description": "Validation error (empty array, exceeds 100 events, invalid event)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "batchTooLarge": {
                    "summary": "Batch contains more than 100 events",
                    "value": {
                      "error": "BATCH_TOO_LARGE",
                      "message": "max 100 events per batch; split larger buffers into multiple requests"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Invalid or missing token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "429": {
            "description": "Rate limited",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/identify": {
      "post": {
        "operationId": "identify",
        "summary": "Link anonymous user to authenticated identity",
        "description": "Maps `previous_id` (typically an anonymous tracker ID like `anon_xxx`) to `user_id` (the authenticated identity).\nAll historical events and sessions with `previous_id` are backfilled to use `user_id`.\n\nCalled automatically by the tracker's `aa.identify(\"user_123\", { email: \"alice@example.com\" })` method.\nCan also be called server-side after authentication to stitch identities.\nUse a stable application user ID for `user_id`; do not identify users by email address.\nIf `traits.email` is present, raw email is transmitted over HTTPS only for identify-time lookup indexing. Agent Analytics stores a scoped HMAC lookup index and strips raw email from event rows and profile traits by default.\n\n- **Idempotent**: sending the same mapping twice is a no-op\n- **Re-identify**: updating the mapping triggers a new backfill\n- **Project-scoped**: only affects events/sessions in the specified project\n",
        "tags": [
          "Ingestion"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "token",
                  "previous_id",
                  "user_id"
                ],
                "properties": {
                  "token": {
                    "type": "string",
                    "description": "Project token (`aat_*`)",
                    "example": "aat_abc123"
                  },
                  "previous_id": {
                    "type": "string",
                    "maxLength": 256,
                    "description": "The anonymous or previous user ID to replace",
                    "example": "anon_k7x9m2abc"
                  },
                  "user_id": {
                    "type": "string",
                    "maxLength": 256,
                    "description": "The authenticated stable application user ID to assign. Do not use an email address as the user ID.",
                    "example": "user_12345"
                  },
                  "traits": {
                    "type": "object",
                    "additionalProperties": true,
                    "description": "Optional safe profile traits. `traits.email` may be sent for server-side HMAC lookup indexing; raw email is not stored in event rows or profile traits by default.",
                    "example": {
                      "email": "alice@example.com",
                      "plan": "pro",
                      "role": "admin",
                      "team": "acme"
                    }
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "202": {
            "description": "Identity mapping queued for processing",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "queued": {
                      "type": "boolean",
                      "example": true
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "queued": true
                }
              }
            }
          },
          "400": {
            "description": "Validation error (missing fields, same IDs, exceeds length)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Invalid or missing token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "429": {
            "description": "Rate limited",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/stats": {
      "get": {
        "operationId": "getStats",
        "summary": "Aggregated stats overview",
        "description": "Returns an overview of a project's analytics: time series, top events, session metrics, and totals.\n\nBounce metrics are computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 stats my-site --since 7d`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "name": "groupBy",
            "in": "query",
            "required": false,
            "description": "Time series granularity",
            "schema": {
              "type": "string",
              "enum": [
                "hour",
                "day",
                "week",
                "month"
              ],
              "default": "day"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Stats overview",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StatsResponse"
                },
                "example": {
                  "project": "my-site",
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "period": {
                    "from": "2025-01-01",
                    "to": "2025-01-07",
                    "groupBy": "day"
                  },
                  "totals": {
                    "unique_users": 142,
                    "total_events": 1247
                  },
                  "timeSeries": [
                    {
                      "bucket": "2025-01-01"
                    }
                  ],
                  "events": [
                    {
                      "event": "page_view"
                    }
                  ],
                  "countries": [
                    {
                      "country": "NL",
                      "count": 80,
                      "unique_users": 1
                    }
                  ],
                  "sessions": {
                    "bounce_rate": 0.45
                  }
                }
              }
            }
          },
          "400": {
            "description": "Missing project parameter",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/events": {
      "get": {
        "operationId": "getEvents",
        "summary": "Raw event log",
        "description": "Returns individual events, newest first. Filter by event name and/or session ID.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 events my-site --event page_view --since 7d --limit 50`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "event",
            "in": "query",
            "required": false,
            "description": "Filter by event name",
            "schema": {
              "type": "string"
            },
            "example": "page_view"
          },
          {
            "name": "session_id",
            "in": "query",
            "required": false,
            "description": "Filter by session ID",
            "schema": {
              "type": "string"
            }
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "$ref": "#/components/parameters/LimitParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Event list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "project": {
                      "type": "string"
                    },
                    "events": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/EventRow"
                      }
                    }
                  }
                },
                "example": {
                  "events": [
                    {
                      "country": "US"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "lookupEvents",
        "summary": "Raw event log by user ID or email lookup",
        "description": "Authenticated lookup variant for one customer's rows. Use `user_id` for stable IDs, or send raw `email` in the HTTPS POST body for server-side scoped HMAC lookup.\n`email_hash` is no longer accepted. Agent Analytics does not store raw lookup email in event rows or profile traits.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IdentityLookupRequest"
              },
              "examples": {
                "byEmail": {
                  "value": {
                    "project": "my-site",
                    "email": "alice@example.com",
                    "since": "30d",
                    "limit": 50
                  }
                },
                "byUserId": {
                  "value": {
                    "project": "my-site",
                    "user_id": "user_12345",
                    "since": "30d"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Event list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "project": {
                      "type": "string"
                    },
                    "events": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/EventRow"
                      }
                    }
                  }
                },
                "example": {
                  "events": [
                    {
                      "country": "US"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/journey": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "lookupJourney",
        "summary": "Customer journey by user ID or email lookup",
        "description": "Returns chronological events and matching profiles for a single known identity. Use a stable `user_id` when available.\nFor support lookup by email, send raw `email` in the HTTPS POST body; the API normalizes it, computes scoped HMAC lookup indexes server-side, and does not store raw email in event rows or profile traits.\n`email_hash` is no longer accepted.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IdentityLookupRequest"
              },
              "examples": {
                "byEmail": {
                  "value": {
                    "project": "my-site",
                    "email": "alice@example.com",
                    "since": "30d",
                    "limit": 100
                  }
                },
                "byUserId": {
                  "value": {
                    "project": "my-site",
                    "user_id": "user_12345",
                    "since": "30d"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Chronological journey",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JourneyResponse"
                },
                "example": {
                  "events": [
                    {
                      "country": "US"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/query": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "query",
        "summary": "Flexible analytics query",
        "description": "Run custom analytics queries with metrics, grouping, filtering, and ordering.\nThis is the most powerful endpoint for building custom reports.\n\n**Metrics:** `event_count`, `unique_users`, `session_count`, `bounce_rate`, `avg_duration`, `sum`, `avg`, `p50`, `p75`, `p95`\n\n**Numeric property metrics:** `sum`, `avg`, `p50`, `p75`, and `p95` aggregate one event property. Send `property` with the key (`cwv_lcp`, `revenue`), not `properties.<key>`. The key matches `^[A-Za-z0-9_]+$` and is at most 128 characters. The same `property` applies to every numeric metric in the request. They work with `group_by` (including one `properties.<key>`), `filters`, the date range, and the event filter. There is no `GET /query`.\n\nMissing `property` is `400` `MISSING_FIELDS`. An invalid key is `400` `INVALID_PROPERTY_KEY`.\n\nOnly JSON numbers are aggregated. Numeric strings, booleans, nulls, and missing keys are skipped. Each row returns `n` (numeric values used) and `skipped` (the other rows in the group) whenever any aggregation metric is requested. `avg` is rounded to 6 decimal places. `sum` and `avg` are streaming aggregates.\n\nPercentiles are nearest-rank on D1 and on self-hosted SQLite, which have no percentile function. Sort ascending, break ties by event id, and take rank `ceil(p/100 * n)` (p is 50, 75, or 95). Rank 1 is the smallest value. The result is an observed input, not an interpolation. The response field `percentile_method` is `nearest_rank` when a percentile is requested and `null` when the aggregation metrics are only `sum` and/or `avg`. A percentile query whose filtered set is larger than 200,000 events is `400`. The guard applies to `p50`, `p75`, and `p95`.\n\nHosted stores `cwv_lcp`, `cwv_inp`, `cwv_cls`, `cwv_fcp`, and `cwv_ttfb` on `page_view` when `data-track-vitals` is on. Self-hosted core stores the same keys on `$web_vitals`. Hosted does not store `$web_vitals`. If `n` is 0, the filter event does not carry the key.\n\n**Group by:** `event`, `date`, `user_id`, `session_id`, `country`, and at most one `properties.<key>`.\n\n`<key>` is 1 to 128 characters matching `[A-Za-z0-9_]`, the same rule as a `properties.<key>` filter. The result row carries the value under the key exactly `properties.<key>`. A null or missing property groups as null. Two `properties.*` entries are `400` `INVALID_GROUP_BY`. A key that fails the filter rule is `400` `INVALID_PROPERTY_KEY`. `limit` stays capped at 1,000. Numeric metrics work with this group column. The route stays Pro.\n\nUse `POST /query` before `POST /sql`. SQL is the escape hatch when this DSL cannot say the question.\n\n**Filter operators:** `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, `contains`\n\n**Filterable fields:** `event`, `user_id`, `date`, `country`, `session_id`, `timestamp`, and any `properties.*` field (e.g. `properties.path`, `properties.browser`, `properties.first_utm_source`)\n\nBuilt-in fields are a closed list. Common analytics properties such as `referrer`, `utm_source`, `path`, `browser`, and `hostname` must be queried as `properties.referrer`, `properties.utm_source`, `properties.path`, `properties.browser`, and `properties.hostname`.\n\nInvalid filter fields fail the query with `400` and include `/properties`-style discovery guidance instead of being silently ignored.\n\n**Count modes:** `session_then_user` (default for `event_count`) or `raw`\n\n**Plan:** `POST /query` stays paid-only. A free account receives `403` `PRO_REQUIRED` and the read is not metered. The free before/after read is `POST /compare`.\n\n`/events` remains lossless and returns every ingested row. `/query` uses `session_then_user` as the default for `event_count`: session-backed rows count by session, no-session rows fall back to `user_id` only when that user has no session-backed row in the same filtered/grouped result set, and fully anonymous rows fall back to event `id`. `count_mode` is ignored for queries without `event_count`. Use `count_mode: raw` when the question is about ingestion volume or debugging raw writes.\n\nFor support lookup by email, send raw `email` in the HTTPS POST body. The API computes scoped HMAC lookup indexes server-side and does not store raw email in event rows or profile traits. `email_hash` is no longer accepted.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 query my-site --metrics event_count --group-by event --filter '[{\"field\":\"country\",\"op\":\"eq\",\"value\":\"US\"}]'`\n\n**CLI numeric metric:** `npx --yes @agent-analytics/cli@0.5.41 query my-site --metrics p75 --property cwv_lcp --filter '[{\"field\":\"event\",\"op\":\"eq\",\"value\":\"page_view\"}]'`\n\n**CLI property group:** `npx --yes @agent-analytics/cli@0.5.41 query my-site --metrics event_count --group-by properties.path --filter '[{\"field\":\"event\",\"op\":\"eq\",\"value\":\"signup\"}]'`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/QueryRequest"
              },
              "examples": {
                "pageViewsByDay": {
                  "summary": "Page views by day",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count",
                      "unique_users"
                    ],
                    "group_by": [
                      "date"
                    ],
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "page_view"
                      }
                    ],
                    "date_from": "2025-01-01"
                  }
                },
                "topPages": {
                  "summary": "Top pages by event count",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count"
                    ],
                    "group_by": [
                      "event"
                    ],
                    "filters": [
                      {
                        "field": "properties.path",
                        "op": "eq",
                        "value": "/pricing"
                      }
                    ],
                    "limit": 10
                  }
                },
                "rawIngestionCount": {
                  "summary": "Raw ingested rows for debugging",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count"
                    ],
                    "count_mode": "raw",
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "project_created"
                      }
                    ],
                    "date_from": "7d"
                  }
                },
                "signupsFromGermany": {
                  "summary": "Signups from Germany this week",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count",
                      "unique_users"
                    ],
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "signup"
                      },
                      {
                        "field": "country",
                        "op": "eq",
                        "value": "DE"
                      }
                    ],
                    "date_from": "7d"
                  }
                },
                "eventsPerCountry": {
                  "summary": "Events grouped by country",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count",
                      "unique_users"
                    ],
                    "group_by": [
                      "country"
                    ],
                    "order_by": "event_count",
                    "limit": 20
                  }
                },
                "containsFilter": {
                  "summary": "Events with \"blog\" in the path",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count"
                    ],
                    "filters": [
                      {
                        "field": "properties.path",
                        "op": "contains",
                        "value": "blog"
                      }
                    ],
                    "group_by": [
                      "event"
                    ]
                  }
                },
                "p75Lcp": {
                  "summary": "p75 of cwv_lcp on page_view",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "p50",
                      "p75",
                      "p95",
                      "sum",
                      "avg"
                    ],
                    "property": "cwv_lcp",
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "page_view"
                      }
                    ],
                    "date_from": "2026-11-01",
                    "date_to": "2026-11-12",
                    "group_by": [
                      "country"
                    ],
                    "order_by": "p75",
                    "order": "desc",
                    "limit": 50
                  }
                },
                "sumRevenue": {
                  "summary": "Sum of purchase revenue by day",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "sum",
                      "avg"
                    ],
                    "property": "revenue",
                    "group_by": [
                      "date"
                    ],
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "purchase"
                      }
                    ],
                    "date_from": "30d"
                  }
                },
                "signupsByPathAndDay": {
                  "summary": "Signups by day and properties.path",
                  "value": {
                    "project": "my-site",
                    "metrics": [
                      "event_count",
                      "unique_users"
                    ],
                    "group_by": [
                      "date",
                      "properties.path"
                    ],
                    "filters": [
                      {
                        "field": "event",
                        "op": "eq",
                        "value": "signup"
                      }
                    ],
                    "date_from": "7d"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Query results",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QueryResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "property": "cwv_lcp",
                  "percentile_method": "nearest_rank"
                }
              }
            }
          },
          "400": {
            "description": "Invalid query.\nMissing `property` when an aggregation metric is present is `MISSING_FIELDS`.\nAn invalid property key is `INVALID_PROPERTY_KEY`.\nTwo `properties.*` group entries, or a group entry that is not a built-in field or `properties.<key>`, is `INVALID_GROUP_BY`.\nA percentile query whose filtered set is larger than 200,000 events is `400`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missingProperty": {
                    "summary": "Aggregation metric without property",
                    "value": {
                      "error": "MISSING_FIELDS",
                      "message": "property is required for sum, avg, p50, p75, or p95"
                    }
                  },
                  "invalidProperty": {
                    "summary": "Property key outside the allowlist",
                    "value": {
                      "error": "INVALID_PROPERTY_KEY",
                      "message": "Invalid property key"
                    }
                  },
                  "twoPropertyGroups": {
                    "summary": "Two properties.* group_by entries",
                    "value": {
                      "error": "INVALID_GROUP_BY",
                      "message": "group_by accepts at most one properties.<key>"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account. `PRO_REQUIRED`. The body is `error`, `message`, and `payment` when the caller can see billing. The read is not metered.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PRO_REQUIRED",
                  "message": "Pro plan required"
                }
              }
            }
          }
        }
      }
    },
    "/sql": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "runSql",
        "summary": "Read-only SQL for one project",
        "description": "Pro escape hatch for one `SELECT` the `POST /query` DSL cannot say. Use `POST /query` or `GET /breakdown` first. A funnel stays `POST /funnel`.\n\n**Plan:** Pro only. A free account receives `403` `PRO_REQUIRED`. That response is not metered. One accepted call counts as one metered read. Agent session scope is `analytics:read`. Self-hosted OSS auth is the read API key.\n\nEach account database runs one query at a time, so heavy SQL would delay incoming events.\n\n**Body:** `project` (project name) and `sql` (one statement, at most 20,480 bytes). Optional `days` (default 7, maximum 90) or `date_from` and `date_to` (`YYYY-MM-DD`, span at most 90 days). Date parsing matches `POST /query`. Send `days`, or send the date pair. A window outside those rules is `400` `INVALID_WINDOW`.\n\n**Window:** the server always applies the window on the `date` column of both `events` and `sessions`: `date >= ? AND date <= ?`, inclusive UTC days. That uses `idx_events_project_date` and `idx_sessions_project_date`. The response `window` is `{date_from, date_to}`.\n\n**Response:** `columns`, `rows`, `count`, `truncated`, `window`, `statistics.elapsed_ms`, `statistics.rows_read`, `statistics.expensive`. Each row is an object. Hosted and OSS both return row objects. `columns` is the keys of the first row, and `columns` is `[]` when `rows` is empty. `count` is the number of returned rows. Hosted sets `rows_read` from D1 `meta.rows_read`. `expensive` is true when `rows_read` is over 1,000,000. The rows are still returned.\n\n**Row cap:** if the statement has no `LIMIT`, the server appends `LIMIT 1001`, returns at most 1,000 rows, and sets `truncated` true when the extra row existed. A user `LIMIT` must be a plain integer. `LIMIT 1000+500` is `400` `INVALID_SQL`. A user `LIMIT` above 1,000 is capped to 1,000.\n\n**Join limit:** each of `events` and `sessions` may be referenced at most once. One join of `events` to `sessions` is allowed. A self join is not. A recursive CTE is rejected. Either case is `400` `INVALID_SQL`, and the message says why.\n\n**Table position:** after `FROM`, `JOIN`, or `IN`, only `events`, `sessions`, a CTE name, or a parenthesized subquery or list is allowed. `randomblob` and `zeroblob` are rejected. A SQL error from the database is `400` `INVALID_SQL`, not `500`.\n\n**Rate and budget:** 10 `/sql` calls per account per minute, inside the Pro 1,000 requests per minute cap. The next call in that minute is `429` `RATE_LIMITED` with `reason` `sql_rate_limit`. One running `/sql` per account. The lease expires after 15 seconds. If one is already running, the call is `429` `SQL_BUSY` with `Retry-After`. When `rows_read` exceeds 5,000,000, that account's `/sql` is blocked for 60 seconds (`429` `SQL_COOLDOWN` with `Retry-After`). The monthly budget stays 100,000,000 rows read per account on `/sql`, then `429` `SQL_BUDGET`. The HTTP call times out after 10 seconds (`504` `SQL_TIMEOUT`). The query may still finish inside the database.\n\n**Hosted execution:** a separate Cloudflare API token, `CF_D1_READ_TOKEN`, with D1 Read only. `/sql` never uses the edit token. Until that secret is configured, the route returns `503` `SQL_UNAVAILABLE`. The worker chooses the account D1 id from the authenticated account. The client does not send a database id. The project name is a bound parameter.\n\n**Statement rules:** exactly one `SELECT`. A statement that starts with `WITH` is rejected. A nested `WITH` is allowed only when every table it names is `events` or `sessions`. A recursive CTE is rejected. Each of `events` and `sessions` may be referenced at most once. One join of `events` to `sessions` is allowed. A self join is not. After `FROM`, `JOIN`, or `IN`, only `events`, `sessions`, a CTE name, or a parenthesized subquery or list is allowed. A `LIMIT` must be a plain integer. Reject `randomblob` and `zeroblob`. A subquery inside the `SELECT` is allowed. Reject multiple statements. Reject bind parameters. Reject these keywords outside string literals: `INSERT`, `UPDATE`, `DELETE`, `REPLACE`, `ALTER`, `DROP`, `CREATE`, `ATTACH`, `DETACH`, `PRAGMA`, `VACUUM`, `REINDEX`. The same word inside a string literal is allowed. Reject schema-qualified names (`main.events`, `temp.sessions`). Reject `sqlite_master`, `sqlite_schema`, `sqlite_temp_master`, and `sqlite_temp_schema`. Reject table-valued functions. Reject non-ASCII characters outside string literals. Reject any table other than `events` and `sessions`.\n\n**Public columns.** Adding a column later is allowed. Removing or renaming one is a breaking change. `resolved_user_id` is not exposed. There is no `GET /sql/schema`.\n\n`events`: `id`, `event`, `properties`, `user_id`, `session_id`, `timestamp`, `date`, `country`. `properties` is a JSON string. Use `json_extract` in the statement. `project_id` is not a column of this table. See `SqlEventsRow`.\n\n`sessions`: `session_id`, `user_id`, `project_id`, `start_time`, `end_time`, `duration`, `entry_page`, `exit_page`, `event_count`, `is_bounce`, `date`. `project_id` is the project name. See `SqlSessionsRow`.\n\nThe server wraps the statement so each table shows only that project's rows.\n\n**Self-hosted:** same route, same columns, same parser. OSS returns `rows` as objects, the same as hosted. OSS applies the time window, the join limit, and the 10 second timeout only. It does not apply `SQL_BUSY`, the 10 calls per minute cap, `SQL_COOLDOWN`, `SQL_UPSTREAM_RATE_LIMITED`, or the monthly rows read budget. Node and SQLite open a read-only connection. Cloudflare Workers OSS uses the parser only and then the writable D1 binding. That Workers path is weaker.\n\n**MCP:** `run_sql`, `readOnlyHint` true. The description lists these two tables and columns and says to use `query` or `analytics_breakdown` first. Not registered on the demo MCP.\n\n**CLI:** `aa sql <project> --sql '...'` and `aa sql <project> -f file.sql`. Pass SQL with `--sql` or `-f`. Do not build the statement by concatenating untrusted shell input.\n\n**Guide:** https://docs.agentanalytics.sh/guides/sql/\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SqlRequest"
              },
              "examples": {
                "countsByEvent": {
                  "summary": "Event counts",
                  "value": {
                    "project": "my-site",
                    "sql": "SELECT event, COUNT(*) AS n FROM events GROUP BY event"
                  }
                },
                "pathFromJson": {
                  "summary": "json_extract on properties",
                  "value": {
                    "project": "my-site",
                    "sql": "SELECT json_extract(properties, '$.path') AS path, COUNT(*) AS n FROM events GROUP BY path"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Rows from the SELECT, capped at 1,000.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SqlResponse"
                },
                "example": {
                  "columns": [
                    "event",
                    "n"
                  ],
                  "rows": [
                    {
                      "event": "page_view",
                      "n": 12
                    }
                  ],
                  "count": 1,
                  "truncated": false,
                  "window": {
                    "date_from": "2026-11-07",
                    "date_to": "2026-11-13"
                  },
                  "statistics": {
                    "elapsed_ms": 18,
                    "rows_read": 1200,
                    "expensive": false
                  }
                }
              }
            }
          },
          "400": {
            "description": "`INVALID_SQL` when the statement is rejected: more than one statement, a leading `WITH`, a recursive CTE, a second reference to `events` or to `sessions`, a name after `FROM`, `JOIN`, or `IN` that is not `events`, `sessions`, a CTE name, or a parenthesized subquery or list, a `LIMIT` that is not a plain integer, `randomblob` or `zeroblob`, SQL over 20,480 bytes, a bind parameter, a write or DDL keyword outside a string literal, a schema-qualified name, `sqlite_master`, `sqlite_schema`, `sqlite_temp_master`, `sqlite_temp_schema`, a table-valued function, a non-ASCII character outside a string literal, or a table other than `events` and `sessions`. A SQL error from the database is also `400` `INVALID_SQL`, not `500`. The message says why. A nested `WITH` is allowed only over `events` and `sessions`. A bad time window is `INVALID_WINDOW`. Missing `project` or `sql` is `MISSING_FIELDS`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "notSelect": {
                    "summary": "Statement is not one SELECT",
                    "value": {
                      "error": "INVALID_SQL",
                      "message": "Only a single SELECT statement is accepted"
                    }
                  },
                  "writeKeyword": {
                    "summary": "Write keyword outside a string literal",
                    "value": {
                      "error": "INVALID_SQL",
                      "message": "SQL contains a write or DDL keyword"
                    }
                  },
                  "tooManyTables": {
                    "summary": "More than two events or sessions references",
                    "value": {
                      "error": "INVALID_SQL",
                      "message": "Each of events and sessions may be referenced at most once"
                    }
                  },
                  "badWindow": {
                    "summary": "Time window is outside the allowed rules",
                    "value": {
                      "error": "INVALID_WINDOW",
                      "message": "Invalid SQL time window"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account. `PRO_REQUIRED`. The body is `error`, `message`, and `payment` when the caller can see billing. The attempt is not metered.\nAn agent session without `analytics:read` is `FORBIDDEN`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "proRequired": {
                    "summary": "Free account",
                    "value": {
                      "error": "PRO_REQUIRED",
                      "message": "Pro plan required"
                    }
                  },
                  "missingScope": {
                    "summary": "Agent session missing analytics:read",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: analytics:read"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "`RATE_LIMITED` after 10 `/sql` calls for this account in a minute. The body includes `reason: sql_rate_limit`.\n`SQL_BUSY` when a `/sql` query is already running for this account. The lease expires after 15 seconds. `Retry-After` is set.\n`SQL_COOLDOWN` for 60 seconds after a query whose `rows_read` exceeds 5,000,000. `Retry-After` is set.\n`SQL_BUDGET` after 100,000,000 rows read on `/sql` for this account in the month. That monthly budget is unchanged.\n`SQL_UPSTREAM_RATE_LIMITED` when the Cloudflare D1 API returns 429. Hosted only. The call is not retried. `Retry-After` is Cloudflare's value, or 60 when Cloudflare does not send one. The body `retry_after` is that number of seconds.\n",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "schema": {
                  "type": "integer"
                },
                "description": "Seconds to wait. Every 429 includes Retry-After."
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "minuteCap": {
                    "summary": "10 SQL calls in a minute",
                    "value": {
                      "error": "RATE_LIMITED",
                      "message": "SQL rate limit exceeded (10 requests per minute)",
                      "reason": "sql_rate_limit",
                      "limit": 10,
                      "used": 11
                    }
                  },
                  "alreadyRunning": {
                    "summary": "Another SQL query is running",
                    "value": {
                      "error": "SQL_BUSY",
                      "message": "A SQL query is already running for this account"
                    }
                  },
                  "cooldown": {
                    "summary": "Large read blocks SQL for 60 seconds",
                    "value": {
                      "error": "SQL_COOLDOWN",
                      "message": "SQL is cooling down after a large read"
                    }
                  },
                  "monthlyBudget": {
                    "summary": "Monthly rows read budget",
                    "value": {
                      "error": "SQL_BUDGET",
                      "message": "Monthly SQL rows read budget exceeded"
                    }
                  },
                  "upstreamRateLimit": {
                    "summary": "Cloudflare D1 returned 429",
                    "value": {
                      "error": "SQL_UPSTREAM_RATE_LIMITED",
                      "message": "Cloudflare API rate limit reached",
                      "retry_after": 60
                    }
                  }
                }
              }
            }
          },
          "503": {
            "description": "Hosted `CF_D1_READ_TOKEN` is not configured. `SQL_UNAVAILABLE`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "SQL_UNAVAILABLE",
                  "message": "Read-only SQL is not configured"
                }
              }
            }
          },
          "504": {
            "description": "The HTTP call times out after 10 seconds. `SQL_TIMEOUT`. The query may still finish inside the database.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "SQL_TIMEOUT",
                  "message": "SQL query timed out"
                }
              }
            }
          }
        }
      }
    },
    "/vitals": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "postVitals",
        "summary": "Web Vitals p75 on page_view",
        "description": "Pro read of LCP, INP, CLS, FCP, and TTFB stored on hosted `page_view`. The event is fixed to `page_view`. There is no event parameter. p75 is the headline. The method is nearest-rank.\n\nHosted stores `cwv_lcp`, `cwv_inp`, `cwv_cls`, `cwv_fcp`, and `cwv_ttfb` on `page_view` when `data-track-vitals` is on. Self-hosted core stores the same keys on `$web_vitals`. Hosted does not store `$web_vitals`. This endpoint is the hosted read.\n\n**Plan:** paid-only, the same gate as `POST /query` and `GET /errors`. A free account receives `403` `PRO_REQUIRED`. The body is `error`, `message`, and `payment` when the caller can see billing. That `403` is not metered. One successful `200` counts as one monthly agent/API read. A `4xx` or `5xx` does not.\n\n**Request:** `project` is required. Optional `days`, or `date_from` and `date_to` (`YYYY-MM-DD`). Optional `group_by` is `device` or `path`. Optional `limit` defaults to 10 and the maximum is 20. `GET /vitals` accepts the same fields as query parameters.\n\n**Rating:** a value is `good` when it is <= `good_max`, `poor` when it is > `poor_min`, and `needs-improvement` otherwise. The p75 rating uses that rule on the p75. `share` uses the same rule on each page load. Share fractions are 0 to 1 with 3 decimal places. The share key is `needs_improvement`. The rating string is `needs-improvement`.\n\n**Thresholds:** LCP 2500/4000 ms, INP 200/500 ms, CLS 0.1/0.25 unitless, FCP 1800/3000 ms, TTFB 800/1800 ms. The response echoes them.\n\n**`cwv_pass`:** true when the LCP, INP, and CLS p75 values are all good. When INP `n` is 0, the decision uses LCP and CLS only. Null when LCP `n` is 0 or CLS `n` is 0. FCP and TTFB are not part of `cwv_pass`.\n\n**`n` and `skipped`:** `n` is page views in the group that included the metric. `skipped` is page views in the group that did not. A missing key is skipped, not zero. CLS and INP are Chromium only and are absent elsewhere.\n\n**Targets:** `top_poor_targets` is at most 5 `{ target, count }` entries for loads rated poor. `target` is a CSS selector only (no text content, no URL), max 200 characters. FCP and TTFB return `[]`.\n\n**Grouping:** omit `group_by` for one row with `group` null. `device` returns `mobile`, `tablet`, and `desktop`. `path` returns the top `limit` paths by `n`, sorted by worst LCP p75.\n\n**Cap:** nearest-rank, same rank rule as `POST /query`. The sample is capped at 200,000 events. When the cap is hit, `approximate` is true and `caps` is present. Otherwise `approximate` is false and `caps` is omitted. The response is still `200`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 vitals my-site --days 7`\n\n**MCP:** tool `web_vitals`. Arguments match this body. The text result prints, per metric, p75 with unit, rating, good / needs-improvement / poor share, and `n`.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/VitalsRequest"
              },
              "examples": {
                "site": {
                  "summary": "Site-wide p75",
                  "value": {
                    "project": "my-site",
                    "days": 7
                  }
                },
                "byPath": {
                  "summary": "Worst paths by LCP p75",
                  "value": {
                    "project": "my-site",
                    "date_from": "2026-11-06",
                    "date_to": "2026-11-12",
                    "group_by": "path",
                    "limit": 10
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "p75 Web Vitals for page_view. This example omits group_by, so group is null and cwv_pass is true.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VitalsResponse"
                },
                "example": {
                  "project": "my-site",
                  "date_from": "2026-11-06",
                  "date_to": "2026-11-12",
                  "event": "page_view",
                  "group_by": null,
                  "percentile": "p75",
                  "percentile_method": "nearest_rank",
                  "approximate": false,
                  "thresholds": {
                    "lcp": {
                      "unit": "ms",
                      "good_max": 2500,
                      "poor_min": 4000
                    },
                    "inp": {
                      "unit": "ms",
                      "good_max": 200,
                      "poor_min": 500
                    },
                    "cls": {
                      "unit": "unitless",
                      "good_max": 0.1,
                      "poor_min": 0.25
                    },
                    "fcp": {
                      "unit": "ms",
                      "good_max": 1800,
                      "poor_min": 3000
                    },
                    "ttfb": {
                      "unit": "ms",
                      "good_max": 800,
                      "poor_min": 1800
                    }
                  },
                  "rows": [
                    {
                      "group": null,
                      "cwv_pass": true,
                      "metrics": {
                        "lcp": {
                          "p75": 2100,
                          "rating": "good",
                          "n": 400,
                          "skipped": 20,
                          "share": {
                            "good": 0.8,
                            "needs_improvement": 0.15,
                            "poor": 0.05
                          },
                          "top_poor_targets": [
                            {
                              "target": "img.hero",
                              "count": 4
                            }
                          ]
                        },
                        "inp": {
                          "p75": 180,
                          "rating": "good",
                          "n": 360,
                          "skipped": 60,
                          "share": {
                            "good": 0.75,
                            "needs_improvement": 0.2,
                            "poor": 0.05
                          },
                          "top_poor_targets": [
                            {
                              "target": "button.buy",
                              "count": 3
                            }
                          ]
                        },
                        "cls": {
                          "p75": 0.08,
                          "rating": "good",
                          "n": 390,
                          "skipped": 30,
                          "share": {
                            "good": 0.82,
                            "needs_improvement": 0.12,
                            "poor": 0.06
                          },
                          "top_poor_targets": [
                            {
                              "target": "#main > .banner",
                              "count": 2
                            }
                          ]
                        },
                        "fcp": {
                          "p75": 1600,
                          "rating": "good",
                          "n": 400,
                          "skipped": 20,
                          "share": {
                            "good": 0.84,
                            "needs_improvement": 0.12,
                            "poor": 0.04
                          },
                          "top_poor_targets": []
                        },
                        "ttfb": {
                          "p75": 700,
                          "rating": "good",
                          "n": 400,
                          "skipped": 20,
                          "share": {
                            "good": 0.78,
                            "needs_improvement": 0.16,
                            "poor": 0.06
                          },
                          "top_poor_targets": []
                        }
                      }
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account. `PRO_REQUIRED`. The read is not metered.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PRO_REQUIRED",
                  "message": "Pro plan required"
                }
              }
            }
          }
        }
      },
      "get": {
        "operationId": "getVitals",
        "summary": "Web Vitals p75 on page_view",
        "description": "Same read as `POST /vitals`. Pass `project`, `days`, `date_from`, `date_to`, `group_by`, and `limit` as query parameters. The event is fixed to `page_view`. p75 is the headline. Pro only. A free account receives `403` `PRO_REQUIRED`, and that response is not metered. One successful `200` counts as one metered read.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 vitals my-site --days 7 --by device`\n\n**MCP:** tool `web_vitals`.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "days",
            "in": "query",
            "required": false,
            "description": "Optional day window.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "date_from",
            "in": "query",
            "required": false,
            "description": "Inclusive start, `YYYY-MM-DD`.",
            "schema": {
              "type": "string",
              "format": "date"
            }
          },
          {
            "name": "date_to",
            "in": "query",
            "required": false,
            "description": "Inclusive end, `YYYY-MM-DD`.",
            "schema": {
              "type": "string",
              "format": "date"
            }
          },
          {
            "name": "group_by",
            "in": "query",
            "required": false,
            "description": "`device` or `path`. Omit for one row.",
            "schema": {
              "type": "string",
              "enum": [
                "device",
                "path"
              ]
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Used when `group_by` is `path`. Default 10. Maximum 20.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 20,
              "default": 10
            }
          }
        ],
        "responses": {
          "200": {
            "description": "p75 Web Vitals for page_view",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VitalsResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account. `PRO_REQUIRED`. The read is not metered.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PRO_REQUIRED",
                  "message": "Pro plan required"
                }
              }
            }
          }
        }
      }
    },
    "/compare": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "compareWindows",
        "summary": "Before/after keep, revert, or extend",
        "description": "Compare the same weekdays before and after a ship. The ship day is in neither window.\nThe verdict is `keep`, `revert`, or `extend`. It is deterministic.\nAnnotations and traffic mix do not change the verdict. A window that includes today UTC overrides every other reason with `extend` / `incomplete_current_day`.\n\n**Plan:** free on every plan (`paidOnly: false`). `POST /query` stays paid-only. Free accounts can call `/compare` and still receive `PRO_REQUIRED` from `POST /query`.\n\n**Metering:** one successful `200` counts as one monthly agent/API read, regardless of the internal queries. A `4xx` or `5xx` does not increment the counter. Agent session scope is `analytics:read`. Account setup is required, the same as other analytics reads.\n\n**Rate limit:** a free account is limited to 10 requests per minute. The 11th compare in that minute is `429` `RATE_LIMITED` with `reason: \"rate_limit\"` and `limit: 10`. The free monthly read cap remains 500. The next compare after 500 successful reads is `429` `RATE_LIMITED` with `reason: \"monthly_read_limit\"`. Pro uses the Pro request rate.\n\n**Windows:** pass `ship_date` (`YYYY-MM-DD`, UTC) or both `baseline` and `compare`. Not both, and not `window_days` with explicit windows. `window_days` defaults to 7, must be an integer from 1 to 90, and must be a multiple of 7. The baseline is the N calendar days before the ship date (`ship-N` through `ship-1`). The compare window is the N calendar days after (`ship+1` through `ship+N`). The longest ship window is 84 days. Explicit windows are inclusive and each at most 90 days. A window whose `date_to` is after today UTC is `400`. A window that includes today UTC returns `200` with verdict `extend` and reason `incomplete_current_day`. Read on ship day + 8 or later so both windows are complete.\n\n**Metric:** `count_mode` is `unique_users`. A user who fires the goal three times counts once. `rate = goal_converters / denominator_unique_users`, and `goal_converters = min(goal_unique_users, denominator_unique_users)`. Optional `denominator_filters` (at most 10, same shape as `filters`) apply only to that denominator count. Omit them or send `[]` and the denominator is unchanged. The response echoes `denominator_filters` next to `filters`. Relative `lift = (compare_rate - baseline_rate) / baseline_rate`, rounded to 6 decimal places. Thresholds are fractions (`0.15` means +15%). An absolute value above 5 is `400`. This paragraph is the conversion-rate compare, used when `metric` is omitted.\n\n**Property metric:** optional `metric` is `sum(<key>)`, `avg(<key>)`, `p50(<key>)`, `p75(<key>)`, or `p95(<key>)`. It stays free, with the same metering as any other compare. `metric_event` is the event whose property is measured. It defaults to `goal_event`. On hosted, Web Vitals properties are on `page_view`. Self-hosted core stores them on `$web_vitals`. Set it when the measured event is not the goal, for example goal `signup` and metric event `page_view`. `filters` apply to the metric event. `denominator_filters` still apply only to the denominator user count. The `sum` numerator ignores `denominator_filters`: every numeric value on `metric_event` in the window is added, then that sum is divided by denominator unique users. `better` is `higher` (default) or `lower` and is not inferred from the property name. Set `better` to `lower` for `cwv_lcp` and the other vitals.\n\nOnly JSON numbers are aggregated. Percentiles are nearest-rank, the same rank rule as `POST /query` (`percentile_method: nearest_rank`). `sum` sets `per_user` to `true`. `avg` and percentiles compare the aggregate itself (`per_user: false`). Each window still includes the conversion `rate` and user counts, plus `value`, `n`, and `skipped`.\n\n`raw_lift` is `(compare_value - baseline_value) / baseline_value`. `lift` is `raw_lift`, negated when `better` is `lower`, so the existing thresholds keep their meaning. `interval` is `null` and `interval_method` is `none`. There is no confidence interval for a metric compare in v1.\n\n**Property-metric verdict:** the existing compare order still applies. `min_denominator` is still unique denominator users per window. `min_goal_events` is `n` on `metric_event` across both windows, not unique converters. A metric compare does not return `keep` or `revert` in v1.\n1. `extend` / `incomplete_current_day` when either window includes today UTC.\n2. `extend` / `below_min_sample` when `n` across both windows is under `min_goal_events` (default 20), or either window is under `min_denominator` (default 200).\n3. `extend` / `zero_denominator` when a denominator is still 0.\n4. `extend` / `zero_baseline` when the compare `value` is missing, or the baseline `value` is 0 or null. `lift` is null.\n5. `extend` / `no_interval_for_metric` when `lift` meets `keep_threshold` or `revert_threshold`. `lift` is still reported. A metric compare returns `extend` instead of `keep` or `revert` in v1. Example `reason_detail`: \"Relative lift 0.5 meets the keep threshold 0.15, but metric compare does not compute an interval in v1, so the verdict is extend.\"\n6. `extend` / `no_evidence_of_gain` when `lift` is between the thresholds.\n\nA conversion-rate response is unchanged when `metric` is omitted.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 compare my-site --goal signup --metric 'p75(cwv_lcp)' --metric-event page_view --better lower --ship-date 2026-11-05`\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 compare my-site --goal purchase --metric 'sum(revenue)' --ship-date 2026-11-04`\n\n**Verdict order (metric omitted):**\n1. `extend` / `incomplete_current_day` when either window includes today UTC. This overrides every later reason.\n2. `extend` / `below_min_sample` when either window is under `min_denominator`, or the two windows together have fewer unique converters than `min_goal_events`.\n3. `extend` / `zero_denominator` only if a denominator is still 0 (reachable only when `min_denominator` is 0).\n4. `extend` / `zero_baseline` when the baseline rate is 0. `lift` is null.\n5. `revert` / `revert_threshold_met` only when lift is at or below `revert_threshold` and the 90% interval lies entirely below zero.\n6. `extend` / `inconclusive` when that drop is inside the noise (lift is at or below `revert_threshold`, but the interval is not entirely below zero).\n7. `keep` / `keep_threshold_met` when lift is at or above `keep_threshold` and `interval.low > 0`.\n8. `extend` / `interval_includes_zero` when lift clears the keep threshold but the interval includes zero.\n9. `extend` / `no_evidence_of_gain` otherwise.\n\n`interval` is null on `below_min_sample` and `zero_denominator`. `lift` is null when the baseline rate is 0 or a rate cannot be formed. `ship_date` and `window_days` are omitted when the caller passed explicit windows.\n\nThe interval estimate is `rate_difference` (compare rate minus baseline rate), not the relative lift. The method is `newcombe_wilson_90`.\n\nInvalid filters are a plain `400` with `{ error, message }` only. They do not include `available_properties` or any other `/properties` payload, and they do not run the count queries.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompareRequest"
              },
              "examples": {
                "shipDate": {
                  "summary": "Seven days before and after a ship date",
                  "value": {
                    "project": "my-site",
                    "goal_event": "signup",
                    "denominator_event": "page_view",
                    "filters": [
                      {
                        "field": "country",
                        "op": "eq",
                        "value": "US"
                      }
                    ],
                    "ship_date": "2020-06-10",
                    "window_days": 7,
                    "denominator_filters": [
                      {
                        "field": "properties.title",
                        "op": "neq",
                        "value": "Page not found | grokbotpages.com"
                      }
                    ],
                    "rule": {
                      "keep_threshold": 0.15,
                      "revert_threshold": -0.1,
                      "min_denominator": 200,
                      "min_goal_events": 20
                    }
                  }
                },
                "explicitWindows": {
                  "summary": "Explicit baseline and compare dates",
                  "value": {
                    "project": "my-site",
                    "goal_event": "signup",
                    "baseline": {
                      "date_from": "2020-06-01",
                      "date_to": "2020-06-07"
                    },
                    "compare": {
                      "date_from": "2020-06-08",
                      "date_to": "2020-06-14"
                    }
                  }
                },
                "webVitals": {
                  "summary": "p75 of cwv_lcp, lower is better, signup remains the goal",
                  "value": {
                    "project": "my-site",
                    "goal_event": "signup",
                    "metric": "p75(cwv_lcp)",
                    "metric_event": "page_view",
                    "better": "lower",
                    "ship_date": "2026-11-05"
                  }
                },
                "revenuePerUser": {
                  "summary": "Sum of revenue per denominator user",
                  "value": {
                    "project": "my-site",
                    "goal_event": "purchase",
                    "metric": "sum(revenue)",
                    "ship_date": "2026-11-04",
                    "window_days": 7
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Verdict for the two windows. This example is 2000 denominator users and 200 vs 400 unique converters, none of them outside the denominator, ship date 2020-06-10, window length 7, and the example rule. The request omitted `denominator_filters`, so the echo is `[]`. Neither window includes today, so the verdict can be keep.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompareResponse"
                },
                "example": {
                  "project": "my-site",
                  "project_id": "proj_123",
                  "verdict": "keep",
                  "reason": "keep_threshold_met",
                  "reason_detail": "Relative lift 1 is at or above the keep threshold 0.15, and the 90% interval for the rate difference lies entirely above zero.",
                  "goal_event": "signup",
                  "denominator_event": "page_view",
                  "count_mode": "unique_users",
                  "filters": [],
                  "denominator_filters": [],
                  "window_source": "ship_date",
                  "ship_date": "2020-06-10",
                  "window_days": 7,
                  "weekday_aligned": true,
                  "windows": {
                    "baseline": {
                      "date_from": "2020-06-03",
                      "date_to": "2020-06-09",
                      "day_count": 7,
                      "denominator_unique_users": 2000,
                      "goal_unique_users": 200,
                      "goal_converters": 200,
                      "goal_users_outside_denominator": 0,
                      "count_mode": "unique_users",
                      "rate": 0.1
                    },
                    "compare": {
                      "date_from": "2020-06-11",
                      "date_to": "2020-06-17",
                      "day_count": 7,
                      "denominator_unique_users": 2000,
                      "goal_unique_users": 400,
                      "goal_converters": 400,
                      "goal_users_outside_denominator": 0,
                      "count_mode": "unique_users",
                      "rate": 0.2
                    }
                  },
                  "lift": 1,
                  "interval": {
                    "level": 0.9,
                    "method": "newcombe_wilson_90",
                    "estimate": "rate_difference",
                    "low": 0.081597,
                    "high": 0.118402,
                    "excludes_zero": true,
                    "note": "90% interval for compare_rate - baseline_rate. Rates are unique goal converters divided by denominator unique_users. Each converter counts once. The Newcombe/Wilson interval treats the rate as a binomial proportion. keep requires the interval to lie entirely above zero. revert requires the interval to lie entirely below zero."
                  },
                  "rule": {
                    "keep_threshold": 0.15,
                    "revert_threshold": -0.1,
                    "min_denominator": 200,
                    "min_goal_events": 20,
                    "defaults_applied": []
                  },
                  "guardrails": {
                    "confounded": false,
                    "annotations": [],
                    "traffic_mix": {
                      "basis": "denominator_event",
                      "shift_threshold": 0.2,
                      "shifted": false,
                      "filters_applied": false,
                      "properties": {
                        "utm_source": {
                          "coverage": {
                            "baseline": 0,
                            "compare": 0
                          },
                          "baseline": [],
                          "compare": [],
                          "shifts": []
                        },
                        "referrer": {
                          "coverage": {
                            "baseline": 0,
                            "compare": 0
                          },
                          "baseline": [],
                          "compare": [],
                          "shifts": []
                        }
                      }
                    },
                    "incomplete_current_day": false,
                    "caveat": "Before/after is not causal. A keep or revert verdict is a deterministic reading of this rule on these two windows, not proof that the change caused the difference."
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error. The body is `{ error, message }` only.\nFuture windows, unknown fields, a `window_days` that is not a multiple of 7, and invalid filters use this status.\nFilter errors do not include `available_properties`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "futureWindow": {
                    "summary": "ship_date 2099-01-06 with window_days 7, when today UTC is 2020-06-01",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "compare windows must end on or before today (2020-06-01 UTC); baseline ends 2099-01-05; compare ends 2099-01-13"
                    }
                  },
                  "windowDays": {
                    "summary": "ship_date window is not a multiple of 7",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "window_days must be a multiple of 7 when using ship_date so the before and after windows cover the same weekdays; got 10. Pass baseline and compare dates to use another length."
                    }
                  },
                  "invalidFilterField": {
                    "summary": "Unknown filter field, with no property catalog",
                    "value": {
                      "error": "INVALID_FILTER_FIELD",
                      "message": "invalid filter field: x. Built-in fields are event, user_id, date, country, session_id, timestamp. Event properties must use properties.<key>, for example properties.x"
                    }
                  },
                  "invalidPropertyKey": {
                    "summary": "Property key rejected before any count query",
                    "value": {
                      "error": "INVALID_PROPERTY_KEY",
                      "message": "Invalid property filter key"
                    }
                  },
                  "eventFilter": {
                    "summary": "Filter tried to set the event name",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "filters cannot set event; pass goal_event and denominator_event"
                    }
                  },
                  "thresholdFraction": {
                    "summary": "keep_threshold 15 is above the fraction cap",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "rule.keep_threshold is 15. Thresholds are fractions (0.15 = +15%), and the absolute value must be 5 or less."
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Agent session is missing `analytics:read`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "FORBIDDEN",
                  "message": "agent session missing required scope: analytics:read"
                }
              }
            }
          },
          "404": {
            "description": "Project is not owned by the account. Does not query analytics and does not count as a read.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found or unauthorized"
                }
              }
            }
          },
          "429": {
            "description": "Free-account request rate (10 per minute, `reason: \"rate_limit\"`, `limit: 10`) or the free monthly read cap (`reason: \"monthly_read_limit\"`, limit 500).\nThe monthly cap applies when this successful call would pass 500 reads. A rate-limited request is not a successful read.\n",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Error"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "reason": {
                          "type": "string",
                          "enum": [
                            "rate_limit",
                            "monthly_read_limit"
                          ]
                        },
                        "limit": {
                          "type": "integer"
                        },
                        "used": {
                          "type": "integer"
                        },
                        "remaining": {
                          "type": "integer"
                        },
                        "attempted": {
                          "type": "integer"
                        }
                      }
                    }
                  ]
                },
                "examples": {
                  "perMinute": {
                    "summary": "11th compare in a minute on a free account",
                    "value": {
                      "error": "RATE_LIMITED",
                      "message": "rate limit exceeded (10 req/min on free tier)",
                      "reason": "rate_limit",
                      "limit": 10,
                      "used": 11,
                      "remaining": 0
                    }
                  },
                  "monthlyReads": {
                    "summary": "Free monthly read cap already used",
                    "value": {
                      "error": "RATE_LIMITED",
                      "message": "free plan includes 500 agent/API read actions per month. Upgrade for more reads: https://app.agentanalytics.sh/account/billing",
                      "reason": "monthly_read_limit",
                      "limit": 500,
                      "used": 500,
                      "remaining": 0,
                      "attempted": 1
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Unexpected failure while comparing windows. An AnalyticsError is returned with its own code and message. Not metered.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "QUERY_FAILED",
                  "message": "failed to compare windows"
                }
              }
            }
          }
        }
      }
    },
    "/errors": {
      "get": {
        "operationId": "getErrors",
        "summary": "Grouped $error events",
        "description": "Groups ingested `$error` events for one project. Pro only. A free account receives `403` `PRO_REQUIRED`, the same status and code as `POST /query`. The body is `error`, `message`, and `payment` when the caller can see billing. That `403` does not consume read quota. One successful `200` counts as one monthly agent/API read. A `4xx` or `5xx` does not. Agent session scope is `analytics:read`.\n\nThe tracker opt-in is `data-track-errors=\"true\"`. Each `$error` stores `message` (sanitized, max 500), `source` (sanitized script URL as `origin + pathname`, or a path with query and hash removed, max 500; empty for many unhandled rejections), `line`, and `col`. `line` and `col` are `0` when unknown. There is no `stack`. The same event also stores the usual tracker properties, including `path`, which is what `top_paths` uses. A page sends at most 5 `$error` events, and a repeat of the same message, source, and line on that page is dropped.\n\n**Group key, then SHA-256 hex `fingerprint`:** normalized message, source filename, numeric `line`. Message normalization removes URL query strings and fragments, then replaces UUIDs, hex hashes, and numbers. The filename drops its query and hash. `col` is not part of the key. Stack is not stored and is not part of the key. `line` stays in the key because message normalization strips numbers. `message` in the response is one stored sample.\n\n**Window:** `since` accepts `7d` or `YYYY-MM-DD` and defaults to 7 days. A `since` that overflows is `400` `INVALID_SINCE`. `until` is an inclusive `YYYY-MM-DD` and defaults to today UTC. `count`, `users`, `sessions`, and `top_paths` (top 3 `path` values) use that window. `first_seen` and `last_seen` use every stored `$error` for that fingerprint, not only the window. Groups with no event in the window are omitted.\n\n**new_since:** optional. A `YYYY-MM-DD` is used as a UTC date, and a group is new when its earliest event's UTC date is on or after that date. Any other string is matched to project annotations: exact title, then case-insensitive title, then note, then substring. Zero matches is `400`. More than one match is `400` with `matches: [{ occurred_at, title }]`. One annotation match compares by that annotation's full UTC `occurred_at`, not by the calendar date alone. When the parameter is set, every group includes `new_since` true or false, and the response `new_since` is the resolved UTC date. `new_since_annotation` is present for an annotation match and omitted when the parameter was a date. The group boolean, the date, and `new_since_annotation` are omitted when the parameter is omitted.\n\n**Scan caps:** a large project still returns `200`. Every `200` includes `approximate`. It is `false` when the scan finishes inside both caps, and `true` when a cap is hit. When `approximate` is `true`, the body also includes `caps`, an array of the caps that were hit. There is no `cap` field. `distinct_triples` means `first_seen` used at most 5,000 distinct message, source, and line triples. `window_rows` means the in-window scan used the newest 50,000 rows.\n\n**Limit:** default 20. Values above 100 are clamped to 100. `top_paths` has at most 3 paths. `truncated` is true when more in-window groups exist than `limit`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 errors my-site --since 7d --new-since 2026-11-12`\n\n**MCP:** tool `errors`.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "description": "Window start. ISO date (`YYYY-MM-DD`) or `Nd` shorthand. Defaults to 7 days ago. A `since` that overflows is `400` `INVALID_SINCE`.",
            "schema": {
              "type": "string",
              "default": "7d"
            },
            "example": "7d"
          },
          {
            "name": "until",
            "in": "query",
            "required": false,
            "description": "Inclusive window end, `YYYY-MM-DD` UTC. Defaults to today UTC. Must be on or after `since` and on or before today UTC.",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "example": "2026-11-12"
          },
          {
            "name": "new_since",
            "in": "query",
            "required": false,
            "description": "`YYYY-MM-DD` or an annotation reference. A date compares each group's earliest event by UTC date. An annotation compares by that annotation's full UTC `occurred_at`.\nMatch order for a non-date: exact title, then case-insensitive title, then note, then substring. Zero matches is `400`. More than one match is `400` and lists `matches`.\n",
            "schema": {
              "type": "string"
            },
            "example": "2026-11-12"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Maximum groups to return. Default 20. Maximum 100.",
            "schema": {
              "type": "integer",
              "default": 20,
              "minimum": 1,
              "maximum": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Grouped `$error` events for the window.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorsResponse"
                },
                "examples": {
                  "annotation": {
                    "summary": "Annotation new_since, scan inside both caps",
                    "value": {
                      "project": "my-site",
                      "since": "2026-11-05",
                      "until": "2026-11-12",
                      "limit": 20,
                      "truncated": false,
                      "approximate": false,
                      "new_since": "2026-11-05",
                      "new_since_annotation": {
                        "occurred_at": "2026-11-05T12:00:00.000Z",
                        "title": "Ship errors"
                      },
                      "groups": [
                        {
                          "fingerprint": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                          "message": "Failed request 404 https://api.example/users/99?token=zzz",
                          "source": "app.js",
                          "line": 10,
                          "count": 4,
                          "users": 3,
                          "sessions": 3,
                          "first_seen": "2026-10-01",
                          "last_seen": "2026-11-11",
                          "top_paths": [
                            "/pricing",
                            "/"
                          ],
                          "new_since": false
                        }
                      ]
                    }
                  },
                  "scanCaps": {
                    "summary": "Both scan caps hit",
                    "value": {
                      "project": "my-site",
                      "since": "2026-11-05",
                      "until": "2026-11-12",
                      "limit": 20,
                      "truncated": false,
                      "approximate": true,
                      "caps": [
                        "distinct_triples",
                        "window_rows"
                      ],
                      "groups": [
                        {
                          "fingerprint": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                          "message": "Failed request 404 https://api.example/users/99?token=zzz",
                          "source": "app.js",
                          "line": 10,
                          "count": 4,
                          "users": 3,
                          "sessions": 3,
                          "first_seen": "2026-10-01",
                          "last_seen": "2026-11-11",
                          "top_paths": [
                            "/pricing",
                            "/"
                          ]
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "`new_since` matched no annotation, or more than one. More than one match includes `matches` with each candidate's `occurred_at` and `title`.\nA `since` that overflows is `INVALID_SINCE`.\nA large `$error` history is not a `400`. That read returns `200` with `approximate: true` and `caps` when a scan cap is hit.\n",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Error"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "matches": {
                          "type": "array",
                          "description": "Present when `new_since` matches more than one annotation.",
                          "items": {
                            "type": "object",
                            "additionalProperties": false,
                            "required": [
                              "occurred_at",
                              "title"
                            ],
                            "properties": {
                              "occurred_at": {
                                "type": "string",
                                "format": "date-time"
                              },
                              "title": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "examples": {
                  "ambiguousAnnotation": {
                    "summary": "new_since text matched two annotations",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "new_since matched more than one annotation",
                      "matches": [
                        {
                          "occurred_at": "2026-11-04T13:00:00.000Z",
                          "title": "Shipped pricing page"
                        },
                        {
                          "occurred_at": "2026-11-12T09:00:00.000Z",
                          "title": "Shipped pricing page"
                        }
                      ]
                    }
                  },
                  "unknownAnnotation": {
                    "summary": "new_since text matched no annotation and is not a date",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "new_since did not match a date or an annotation"
                    }
                  },
                  "sinceOverflow": {
                    "summary": "since overflow",
                    "value": {
                      "error": "INVALID_SINCE",
                      "message": "since overflow"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account (`PRO_REQUIRED`) or agent session missing `analytics:read`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "proRequired": {
                    "summary": "Free account",
                    "value": {
                      "error": "PRO_REQUIRED",
                      "message": "Pro plan required"
                    }
                  },
                  "missingScope": {
                    "summary": "Agent session is missing analytics:read",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: analytics:read"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Project is not owned by the account. Does not count as a read.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found or unauthorized"
                }
              }
            }
          }
        }
      }
    },
    "/catalog": {
      "get": {
        "operationId": "getCatalog",
        "summary": "Event names, property types, and example values",
        "description": "Returns one project's event catalog for a bounded window. For each event: name, exact count, first seen, and last seen. For each property key: inferred JSON type, how often the key is present in a sample of the newest 40 rows, and a few example values. Read this before `POST /query` or `POST /sql` so a filter names a key the project actually sends.\n\n**Auth:** API key, project key, or agent session. An agent session or a project key needs `analytics:read`.\n\n**Plan:** Pro only. A free account receives `403` `PRO_REQUIRED`. That response is not metered. One successful call counts as one metered read.\n\n**Context:** a project with saved context also receives `project_context`, the same optional field as the other project analytics reads. The field is omitted when the project has no stored context.\n\n**Window:** `days` defaults to 7 and is an integer from 1 through 90. Or send `date_from` and `date_to` as `YYYY-MM-DD`, both required together, inclusive span at most 90 days. Do not combine the date pair with `days`. A bad window is `400` `INVALID_WINDOW`.\n\n**Counts and sample:** event counts, `first_seen`, and `last_seen` are exact in the window. `first_seen` and `last_seen` are ISO-8601 from `MIN`/`MAX(timestamp)` (milliseconds; values under `1e12` are treated as seconds). Property types, presence, and examples come from at most 40 newest rows per event (`sampling.properties` is `newest_dates`, `sampling.per_event` is 40). The sample is the newest dates, not a uniform sample, and rows that share a date are not ordered by timestamp. `properties_exact` is true when `count` is at most 40 and `sample_size` includes every counted row. Invalid JSON and null `properties` still count in `sample_size`.\n\n**Property fields:** keys are alphabetical and 1 to 128 characters. Longer keys are omitted. `type` is `string`, `number`, `boolean`, `object`, `array`, `null`, or `mixed`. JSON integers and reals are `number`. `true` and `false` are `boolean`. A numeric string stays `string`. `types` counts the sample. `presence` is `present / sample_size`, rounded to 4 decimal places. `queryable` is `^[A-Za-z0-9_]{1,128}$`. `groupable` is that charset with length at most 64. `examples` has up to 3 values, each at most 80 characters after redaction. Objects and arrays contribute no examples.\n\n**Redaction:** example values are always returned. Email-shaped text is replaced with `[redacted-email]`. A key whose name contains `email` replaces the whole example. Object and array values are omitted, so an email nested in an object is not returned. There is no raw-example switch. Looking a person up by email stays the `POST /query` `email` parameter.\n\n**Pages:** events are ordered by name. `limit` is events per page (default 10, integer 1 through 18). `property_limit` is property keys per event (default 25, integer 1 through 40). `next_cursor` continues events. `properties_next_cursor` continues one event's keys. Pass `cursor` or `properties_cursor`, not both. Send the same window the cursor was issued for. Cursors are opaque and do not contain the project name. A bad limit, a bad cursor, a cursor from another window, or both cursors is `400` `VALIDATION_ERROR`.\n\n**Project:** `project` is required. Queries and the response `project` field use the stored name. Missing `project` is `400` `MISSING_FIELDS` (`project is required`). Unknown, or outside the session, is `404` `PROJECT_NOT_FOUND` (`project not found or unauthorized`). The body does not echo the requested name.\n\n**Other errors:** no customer database is `500` `DATABASE_NOT_PROVISIONED`. D1 read-budget exhaustion or an upstream 429 is HTTP 429. Other D1 failures are `500` `QUERY_FAILED`. The route does not take the `/sql` lease, and the response is not cached.\n\n**MCP:** tool `catalog` is planned. The current schema tool is `properties`, which calls `GET /properties`.\n\n**CLI:** command `catalog` is planned. The current command is `npx --yes @agent-analytics/cli@0.5.41 properties my-site`.\n\n**Guide:** https://docs.agentanalytics.sh/reference/catalog/\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": true,
            "description": "Project name or id. The response `project` field is the stored name.\nMissing: `400` `MISSING_FIELDS` (`project is required`).\nUnknown or outside the session: `404` `PROJECT_NOT_FOUND` (`project not found or unauthorized`). The body does not echo the requested name.\n",
            "schema": {
              "type": "string"
            },
            "example": "my-site"
          },
          {
            "name": "days",
            "in": "query",
            "required": false,
            "description": "Integer from 1 through 90. Do not combine with `date_from` and `date_to`. A bad window is `400` `INVALID_WINDOW`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 90,
              "default": 7
            }
          },
          {
            "name": "date_from",
            "in": "query",
            "required": false,
            "description": "Inclusive start date, `YYYY-MM-DD`. Pair it with `date_to`. Inclusive span at most 90 days. Do not combine with `days`.",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "example": "2026-11-14"
          },
          {
            "name": "date_to",
            "in": "query",
            "required": false,
            "description": "Inclusive end date, `YYYY-MM-DD`. Pair it with `date_from`. Inclusive span at most 90 days. Do not combine with `days`.",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "example": "2026-11-20"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Events per page. Integer from 1 through 18. A bad limit is `400` `VALIDATION_ERROR`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 18,
              "default": 10
            }
          },
          {
            "name": "property_limit",
            "in": "query",
            "required": false,
            "description": "Property keys per event. Integer from 1 through 40. A bad limit is `400` `VALIDATION_ERROR`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 40,
              "default": 25
            }
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "Opaque cursor from `next_cursor`. Continues the event list. Pass `cursor` or `properties_cursor`, not both.\nSend the same window the cursor was issued for. A bad cursor, a cursor from another window, or both cursors is `400` `VALIDATION_ERROR`.\nThe cursor does not contain the project name.\n",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "properties_cursor",
            "in": "query",
            "required": false,
            "description": "Opaque cursor from `properties_next_cursor`. Continues one event's property keys. Pass `cursor` or `properties_cursor`, not both.\nSend the same window the cursor was issued for. A bad cursor, a cursor from another window, or both cursors is `400` `VALIDATION_ERROR`.\n",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Event catalog for the window. `project_context` is present only when the project has stored context.\n",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "project",
                    "window",
                    "order",
                    "counts",
                    "sampling",
                    "redaction",
                    "events",
                    "next_cursor"
                  ],
                  "properties": {
                    "project": {
                      "type": "string",
                      "description": "Stored project name.",
                      "example": "my-site"
                    },
                    "project_context": {
                      "$ref": "#/components/schemas/ProjectContext"
                    },
                    "window": {
                      "type": "object",
                      "required": [
                        "date_from",
                        "date_to"
                      ],
                      "properties": {
                        "date_from": {
                          "type": "string",
                          "format": "date"
                        },
                        "date_to": {
                          "type": "string",
                          "format": "date"
                        }
                      }
                    },
                    "order": {
                      "type": "string",
                      "const": "event"
                    },
                    "counts": {
                      "type": "string",
                      "const": "exact"
                    },
                    "sampling": {
                      "type": "object",
                      "required": [
                        "properties",
                        "per_event",
                        "exact_when"
                      ],
                      "properties": {
                        "properties": {
                          "type": "string",
                          "const": "newest_dates"
                        },
                        "per_event": {
                          "type": "integer",
                          "const": 40
                        },
                        "exact_when": {
                          "type": "string"
                        }
                      }
                    },
                    "redaction": {
                      "type": "object",
                      "required": [
                        "examples",
                        "raw_examples"
                      ],
                      "properties": {
                        "examples": {
                          "type": "string",
                          "const": "email"
                        },
                        "raw_examples": {
                          "type": "boolean",
                          "const": false
                        }
                      }
                    },
                    "events": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "event",
                          "count",
                          "first_seen",
                          "last_seen",
                          "sample_size",
                          "properties_exact",
                          "properties",
                          "properties_next_cursor"
                        ],
                        "properties": {
                          "event": {
                            "type": "string"
                          },
                          "count": {
                            "type": "integer",
                            "description": "Exact event count in the window."
                          },
                          "first_seen": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "last_seen": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "sample_size": {
                            "type": "integer",
                            "maximum": 40
                          },
                          "properties_exact": {
                            "type": "boolean"
                          },
                          "properties": {
                            "type": "array",
                            "items": {
                              "type": "object",
                              "required": [
                                "key",
                                "type",
                                "types",
                                "queryable",
                                "groupable",
                                "present",
                                "presence",
                                "examples"
                              ],
                              "properties": {
                                "key": {
                                  "type": "string",
                                  "maxLength": 128
                                },
                                "type": {
                                  "type": "string",
                                  "enum": [
                                    "string",
                                    "number",
                                    "boolean",
                                    "object",
                                    "array",
                                    null,
                                    "mixed"
                                  ]
                                },
                                "types": {
                                  "type": "object",
                                  "additionalProperties": {
                                    "type": "integer"
                                  }
                                },
                                "queryable": {
                                  "type": "boolean"
                                },
                                "groupable": {
                                  "type": "boolean"
                                },
                                "present": {
                                  "type": "integer"
                                },
                                "presence": {
                                  "type": "number"
                                },
                                "examples": {
                                  "type": "array",
                                  "maxItems": 3,
                                  "items": {
                                    "type": "string",
                                    "maxLength": 80
                                  }
                                }
                              }
                            }
                          },
                          "properties_next_cursor": {
                            "type": [
                              "string",
                              "null"
                            ]
                          }
                        }
                      }
                    },
                    "next_cursor": {
                      "type": [
                        "string",
                        "null"
                      ]
                    }
                  }
                },
                "example": {
                  "project": "my-site",
                  "window": {
                    "date_from": "2026-11-14",
                    "date_to": "2026-11-20"
                  },
                  "order": "event",
                  "counts": "exact",
                  "sampling": {
                    "properties": "newest_dates",
                    "per_event": 40,
                    "exact_when": "count is at most per_event and the sample includes every counted row"
                  },
                  "redaction": {
                    "examples": "email",
                    "raw_examples": false
                  },
                  "events": [
                    {
                      "event": "page_view",
                      "count": 1280,
                      "first_seen": "2026-11-14T00:12:03.000Z",
                      "last_seen": "2026-11-20T15:04:05.000Z",
                      "sample_size": 40,
                      "properties_exact": false,
                      "properties": [
                        {
                          "key": "path",
                          "type": "string",
                          "types": {
                            "string": 40
                          },
                          "queryable": true,
                          "groupable": true,
                          "present": 40,
                          "presence": 1,
                          "examples": [
                            "/",
                            "/pricing"
                          ]
                        },
                        {
                          "key": "email",
                          "type": "string",
                          "types": {
                            "string": 12
                          },
                          "queryable": true,
                          "groupable": true,
                          "present": 12,
                          "presence": 0.3,
                          "examples": [
                            "[redacted-email]"
                          ]
                        }
                      ],
                      "properties_next_cursor": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "`MISSING_FIELDS` when `project` is missing (`project is required`).\n`INVALID_WINDOW` when `days` or the date pair is outside the window rules.\n`VALIDATION_ERROR` for a bad limit, a bad cursor, a cursor from another window, or both cursors.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "MISSING_FIELDS",
                  "message": "project is required"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Free account (`PRO_REQUIRED`, not metered) or agent session missing `analytics:read`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "proRequired": {
                    "summary": "Free account",
                    "value": {
                      "error": "PRO_REQUIRED",
                      "message": "Pro plan required"
                    }
                  },
                  "missingScope": {
                    "summary": "Agent session is missing analytics:read",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: analytics:read"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Unknown project, or a project outside the session. Does not count as a read.\nThe body does not include the requested name.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found or unauthorized"
                }
              }
            }
          },
          "429": {
            "description": "D1 read-budget exhaustion, or the upstream database returned 429.",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "`DATABASE_NOT_PROVISIONED` when the account has no customer database.\n`QUERY_FAILED` when the database read fails for another reason.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/properties": {
      "get": {
        "operationId": "getProperties",
        "summary": "Discover event names and property keys",
        "description": "Returns all event names with counts, and a list of known property keys from recent events.\nUseful for building dynamic filters and understanding what data is available.\n\nFor property types, presence, and example values, use `GET /catalog`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 properties my-site`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Event names and property keys",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "project": {
                      "type": "string"
                    },
                    "events": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "event": {
                            "type": "string",
                            "example": "page_view"
                          },
                          "count": {
                            "type": "integer"
                          },
                          "unique_users": {
                            "type": "integer"
                          },
                          "first_seen": {
                            "type": "string"
                          },
                          "last_seen": {
                            "type": "string"
                          }
                        }
                      }
                    },
                    "property_keys": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      },
                      "example": [
                        "browser",
                        "device",
                        "hostname",
                        "language",
                        "os",
                        "path",
                        "referrer",
                        "screen",
                        "title",
                        "url"
                      ]
                    }
                  }
                },
                "example": {
                  "events": [
                    {
                      "event": "page_view"
                    }
                  ],
                  "property_keys": [
                    "browser",
                    "device",
                    "hostname",
                    "language",
                    "os",
                    "path",
                    "referrer",
                    "screen",
                    "title",
                    "url"
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/properties/received": {
      "get": {
        "operationId": "getPropertiesReceived",
        "summary": "Property keys by event name",
        "description": "Returns which property keys appear on which event names, sampled from recent events.\nMore detailed than `/properties` — shows the event-to-property mapping.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "name": "sample",
            "in": "query",
            "required": false,
            "description": "Number of recent events to sample (100-10000, default 5000)",
            "schema": {
              "type": "integer",
              "default": 5000,
              "minimum": 100,
              "maximum": 10000
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Property-to-event mapping",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "project": {
                      "type": "string"
                    },
                    "sample_size": {
                      "type": "integer",
                      "example": 5000
                    },
                    "since": {
                      "type": "string"
                    },
                    "properties": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "key": {
                            "type": "string",
                            "example": "path"
                          },
                          "event": {
                            "type": "string",
                            "example": "page_view"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "sample_size": 5000,
                  "properties": [
                    {
                      "key": "path",
                      "event": "page_view"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/replays/settings": {
      "get": {
        "operationId": "getReplaySettings",
        "summary": "Get project replay settings",
        "description": "Returns explicit enablement, mandatory privacy controls, custom selectors, and hard limits. Replay remains off until the separate `replay.js` bootstrap is installed.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Replay settings and limits",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account authentication",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "operationId": "updateReplaySettings",
        "summary": "Enable, disable, or update project replay settings",
        "description": "Enabling requires Pro or complimentary access and explicit HTTPS allowed origins. Input masking and PII redaction are mandatory and cannot be disabled.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "project",
                  "enabled"
                ],
                "properties": {
                  "project": {
                    "type": "string"
                  },
                  "enabled": {
                    "type": "boolean"
                  },
                  "recording_start": {
                    "type": "string",
                    "enum": [
                      "immediate",
                      "after_consent"
                    ]
                  },
                  "mask_inputs": {
                    "type": "boolean",
                    "const": true
                  },
                  "redact_pii": {
                    "type": "boolean",
                    "const": true
                  },
                  "mask_selectors": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "block_selectors": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "ignore_selectors": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Updated replay settings and limits",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          },
          "400": {
            "description": "Invalid project origins or settings",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Replay entitlement required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/replays": {
      "get": {
        "operationId": "listReplays",
        "summary": "List replay metadata",
        "description": "Lists bounded replay metadata without returning recorded DOM data. Filter by analytics session ID to find all segments linked to one measured session.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "session_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "description": "Millisecond timestamp cursor returned as `next_before` by the previous page.",
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Replay summaries and pagination cursor",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "replays": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/ReplaySummary"
                      }
                    },
                    "next_before": {
                      "type": [
                        "integer",
                        "null"
                      ],
                      "format": "int64"
                    }
                  }
                },
                "example": {
                  "replays": [
                    {
                      "id": "rpl_abc123",
                      "status": "recording"
                    }
                  ]
                }
              }
            }
          }
        }
      },
      "delete": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "deleteReplayData",
        "summary": "Disable and delete replay data",
        "description": "Disables replay and deletes all retained replay objects for the account or one project. This operation requires explicit confirmation.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "confirm"
                ],
                "properties": {
                  "confirm": {
                    "type": "string",
                    "const": "delete_replay_data"
                  },
                  "project": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Deletion result",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    },
                    "deleted": {
                      "type": "integer"
                    },
                    "project": {
                      "type": [
                        "string",
                        "null"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/replays/usage": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getReplayUsage",
        "summary": "Get replay storage and ingestion usage",
        "description": "Returns retained, reserved, and rolling 30-day replay byte totals for the project.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Retained, reserved, and rolling 30-day replay bytes",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/replays/{replayId}": {
      "parameters": [
        {
          "name": "replayId",
          "in": "path",
          "required": true,
          "schema": {
            "type": "string"
          }
        }
      ],
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getReplay",
        "summary": "Get replay metadata and committed chunks",
        "description": "Returns replay metadata and the committed chunk boundaries for one replay.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Replay metadata and chunk boundaries",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/ReplaySummary"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "chunks": {
                          "type": "array",
                          "items": {
                            "type": "object"
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "id": "rpl_abc123",
                  "status": "recording"
                }
              }
            }
          }
        }
      },
      "delete": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "deleteReplay",
        "summary": "Delete one replay",
        "description": "Deletes one retained replay.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Replay deleted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/replays/{replayId}/open": {
      "post": {
        "operationId": "openReplay",
        "summary": "Create a short-lived sandboxed viewer link",
        "description": "Returns a replay-specific viewer URL that expires after one hour. The URL fragment contains the bearer token and must not be logged, persisted, or published.",
        "tags": [
          "Session Replay"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "replayId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Short-lived viewer link",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "viewer_url": {
                      "type": "string",
                      "format": "uri"
                    },
                    "expires_at": {
                      "type": "integer",
                      "format": "int64"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Replay is not playable",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/sessions": {
      "get": {
        "operationId": "getSessions",
        "summary": "List sessions",
        "description": "Returns individual session records with duration, entry/exit pages, event count, and bounce status.\nFilter by user ID and/or bounce status.\n\n`is_bounce` is computed from event names at query time.\n`1` means the session has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "$ref": "#/components/parameters/LimitParam"
          },
          {
            "name": "user_id",
            "in": "query",
            "required": false,
            "description": "Filter by user ID",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "is_bounce",
            "in": "query",
            "required": false,
            "description": "Filter by bounce status (0 or 1)",
            "schema": {
              "type": "integer",
              "enum": [
                0,
                1
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Session list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "project": {
                      "type": "string"
                    },
                    "sessions": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/SessionRow"
                      }
                    }
                  }
                },
                "example": {
                  "sessions": [
                    {
                      "is_bounce": 0,
                      "replays": [
                        {
                          "id": "rpl_abc123",
                          "status": "recording"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/breakdown": {
      "get": {
        "operationId": "getBreakdown",
        "summary": "Top property values",
        "description": "Breaks down events by a specific property, showing the top values by count.\nUseful for top pages, referrers, browsers, countries, UTM sources, etc.\n\nUse `property=country` to see visitor geography (ISO 3166-1 alpha-2 codes). Country is stored as a dedicated column for fast queries.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 breakdown my-site --property path --event page_view --days 7`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "property",
            "in": "query",
            "required": true,
            "description": "Property key to break down by (alphanumeric + underscores, max 128 chars). Use `country` for visitor geography.",
            "schema": {
              "type": "string"
            },
            "example": "path"
          },
          {
            "name": "event",
            "in": "query",
            "required": false,
            "description": "Filter to a specific event name",
            "schema": {
              "type": "string"
            },
            "example": "page_view"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Max values to return (1-1000, default 20)",
            "schema": {
              "type": "integer",
              "default": 20,
              "minimum": 1,
              "maximum": 1000
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Property breakdown",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BreakdownResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "property": "path",
                  "values": [
                    {
                      "value": "/pricing",
                      "count": 342,
                      "unique_users": 201
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Missing property parameter or invalid property key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/insights": {
      "get": {
        "operationId": "getInsights",
        "summary": "Period-over-period comparison",
        "description": "Compares the current period against the previous period of the same length.\nReturns change metrics and an overall trend indicator (`growing`, `stable`, `declining`).\n\n`bounce_rate` is computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 insights my-site --period 7d`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "period",
            "in": "query",
            "required": false,
            "description": "Comparison period",
            "schema": {
              "type": "string",
              "enum": [
                "1d",
                "7d",
                "14d",
                "30d",
                "90d"
              ],
              "default": "7d"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Insights with trend",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InsightsResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "trend": "growing"
                }
              }
            }
          },
          "400": {
            "description": "Invalid period",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/pages": {
      "get": {
        "operationId": "getPages",
        "summary": "Entry/exit page stats",
        "description": "Returns top entry pages, exit pages, or both — with session count, bounce rate, and average duration per page.\n\n`bounce_rate` is computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 pages my-site --type entry`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "type",
            "in": "query",
            "required": false,
            "description": "Page type to query",
            "schema": {
              "type": "string",
              "enum": [
                "entry",
                "exit",
                "both"
              ],
              "default": "entry"
            }
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Max pages to return (1-1000, default 20)",
            "schema": {
              "type": "integer",
              "default": 20,
              "minimum": 1,
              "maximum": 1000
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Page stats",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PagesResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "entry_pages": [
                    {
                      "page": "/pricing",
                      "bounce_rate": 0.45
                    }
                  ],
                  "exit_pages": [
                    {
                      "page": "/pricing",
                      "bounce_rate": 0.45
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid page type",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/sessions/distribution": {
      "get": {
        "operationId": "getSessionDistribution",
        "summary": "Session duration histogram",
        "description": "Returns a histogram of session durations in predefined buckets, with the median bucket and engaged session percentage (sessions >= 30 seconds).\n\n`bounces` in each bucket are computed from event names at query time.\nA session is a bounce when it has only non-interactive events:\n`page_view`, `$impression`, `$scroll_depth`, `$error`, `$time_on_page`, `$performance`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 sessions distribution my-site`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Session duration distribution",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionDistributionResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "distribution": [
                    {
                      "bucket": "0s"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/paths": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getPaths",
        "summary": "Bounded session path analysis",
        "description": "Analyze session-local journeys from entry pages through mixed page and event nodes, ending in `goal`, `drop_off`, or `truncated`.\nEach entry page also includes an `exit_pages` attribution table so agents can connect landing-page behavior to the pages where sessions actually ended.\n\nThis endpoint is explicitly bounded:\n- fixed `since` values only: `7d`, `14d`, `30d`, `90d`\n- `max_steps` is capped at 5\n- `entry_limit` is capped at 20\n- `path_limit` is capped at 10\n- `candidate_session_cap` is capped at 10,000\n- implementation is limited to two D1 read queries, with Worker-side tree assembly\n\nSession attribution is local to the session: the `goal_event` only counts if it occurs in the same session as the entry page.\nNon-converting terminal nodes are split by `exit_page`, so a branch can show whether the drop-off happened on `/pricing`, `/checkout`, or another exit page.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 paths my-site --goal signup --since 30d --max-steps 5`\n",
        "tags": [
          "Paths"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PathsRequest"
              },
              "examples": {
                "signupPaths": {
                  "summary": "Find landing paths that lead to signup",
                  "value": {
                    "project": "my-site",
                    "goal_event": "signup",
                    "since": "30d",
                    "max_steps": 5,
                    "entry_limit": 10,
                    "path_limit": 5,
                    "candidate_session_cap": 5000
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Aggregated session path tree by entry page",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PathsResponse"
                },
                "example": {
                  "project": "my-site",
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "goal_event": "signup",
                  "period": {
                    "from": "2026-03-11",
                    "to": "2026-04-10"
                  },
                  "bounds": {
                    "max_steps": 5,
                    "entry_limit": 10,
                    "path_limit": 5,
                    "candidate_session_cap": 5000
                  },
                  "entry_paths": [
                    {
                      "entry_page": "/landing",
                      "sessions": 120,
                      "conversions": 32,
                      "conversion_rate": 0.267,
                      "exit_pages": [
                        {
                          "exit_page": "/pricing",
                          "sessions": 42,
                          "conversions": 13,
                          "conversion_rate": 0.31,
                          "drop_offs": 29,
                          "drop_off_rate": 0.69
                        }
                      ],
                      "tree": [
                        {
                          "type": "page",
                          "value": "/pricing",
                          "exit_page": "/pricing",
                          "sessions": 42,
                          "conversions": 13,
                          "conversion_rate": 0.31
                        }
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Validation error for out-of-range bounds or missing goal_event",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/heatmap": {
      "get": {
        "operationId": "getHeatmap",
        "summary": "Day-of-week x hour traffic grid",
        "description": "Returns a grid of events by day-of-week and hour-of-day (UTC), with peak detection.\nUseful for understanding when your users are most active.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 heatmap my-site`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Heatmap grid",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HeatmapResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "heatmap": [
                    {
                      "day_name": "Monday"
                    }
                  ],
                  "busiest_day": "Monday",
                  "busiest_hour": 14
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/funnel": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getFunnel",
        "summary": "Funnel analysis",
        "description": "Ad-hoc funnel analysis: track where users drop off across a sequence of 2-8 events.\n\nEach step can have optional property filters (e.g. only count `page_view` events where `path=/pricing`).\nThe conversion window limits how long users have from entering step 1 to completing the final step.\n\nStep 1 is capped at 10,000 users to prevent unbounded scans.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 funnel my-site --steps \"page_view,signup,purchase\" --window 168 --breakdown country`\n",
        "tags": [
          "Funnels"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FunnelRequest"
              },
              "examples": {
                "basicFunnel": {
                  "summary": "Basic 3-step funnel",
                  "value": {
                    "project": "my-site",
                    "steps": [
                      {
                        "event": "page_view"
                      },
                      {
                        "event": "signup"
                      },
                      {
                        "event": "purchase"
                      }
                    ]
                  }
                },
                "filteredFunnel": {
                  "summary": "Funnel with per-step filters",
                  "value": {
                    "project": "my-site",
                    "steps": [
                      {
                        "event": "page_view",
                        "filters": [
                          {
                            "property": "path",
                            "op": "eq",
                            "value": "/pricing"
                          }
                        ]
                      },
                      {
                        "event": "signup"
                      },
                      {
                        "event": "purchase"
                      }
                    ],
                    "conversion_window_hours": 72,
                    "since": "30d"
                  }
                },
                "breakdownFunnel": {
                  "summary": "Funnel segmented by country",
                  "value": {
                    "project": "my-site",
                    "steps": [
                      {
                        "event": "page_view"
                      },
                      {
                        "event": "signup"
                      },
                      {
                        "event": "purchase"
                      }
                    ],
                    "breakdown": "country",
                    "breakdown_limit": 5
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Funnel analysis results",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FunnelResponse"
                },
                "example": {
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "steps": [
                    {
                      "step": 1,
                      "event": "page_view",
                      "users": 500,
                      "conversion_rate": 0.6,
                      "drop_off_rate": 0.4,
                      "avg_time_to_next_ms": 3600000
                    }
                  ],
                  "overall_conversion_rate": 0.12,
                  "breakdowns": [
                    {
                      "value": "US",
                      "overall_conversion_rate": 0.15
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Validation error (invalid steps, filters, window, or count_by)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/retention": {
      "get": {
        "operationId": "getRetention",
        "summary": "Cohort retention analysis",
        "description": "Track what percentage of users return over time using cohort analysis.\n\"Of users who first appeared in week X, what % came back in subsequent weeks?\"\n\nBy default uses session-based retention — a user is \"retained\" if they have any return visit\n(session) in a subsequent period. When `event` is specified, switches to event-based retention\nand only counts that specific event for first-seen and return.\n\nCapped at 10,000 users per query. Older cohorts appear first (top-down).\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 retention my-site --period week --cohorts 8`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "period",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "day",
                "week",
                "month"
              ],
              "default": "week"
            },
            "description": "Cohort grouping period"
          },
          {
            "name": "cohorts",
            "in": "query",
            "schema": {
              "type": "integer",
              "default": 8,
              "minimum": 1,
              "maximum": 30
            },
            "description": "Number of cohort periods (max: day=30, week=12, month=12)"
          },
          {
            "name": "event",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "First-seen event filter (e.g. `signup`). Switches to event-based retention."
          },
          {
            "name": "returning_event",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "What counts as \"returned\" (defaults to same as `event`)"
          },
          {
            "$ref": "#/components/parameters/SinceParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Cohort retention data",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RetentionResponse"
                },
                "examples": {
                  "weeklyRetention": {
                    "summary": "4-week retention",
                    "value": {
                      "period": "week",
                      "cohorts": [
                        {
                          "date": "2026-01-27",
                          "users": 142,
                          "retained": [
                            142,
                            64,
                            55,
                            46
                          ],
                          "rates": [
                            1,
                            0.451,
                            0.387,
                            0.324
                          ]
                        },
                        {
                          "date": "2026-02-03",
                          "users": 128,
                          "retained": [
                            128,
                            54,
                            46
                          ],
                          "rates": [
                            1,
                            0.422,
                            0.359
                          ]
                        },
                        {
                          "date": "2026-02-10",
                          "users": 156,
                          "retained": [
                            156,
                            70
                          ],
                          "rates": [
                            1,
                            0.449
                          ]
                        },
                        {
                          "date": "2026-02-17",
                          "users": 134,
                          "retained": [
                            134
                          ],
                          "rates": [
                            1
                          ]
                        }
                      ],
                      "average_rates": [
                        1,
                        0.441,
                        0.373,
                        0.324
                      ],
                      "users_analyzed": 560
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid period or cohorts value",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/stream": {
      "get": {
        "operationId": "streamEvents",
        "summary": "Live event stream (SSE)",
        "description": "Server-Sent Events stream of real-time events as they arrive.\n\nEvents are delivered as `event: track` SSE messages. Optionally filter by event name and/or property values.\n\nThe stream sends a `:heartbeat` comment every 30 seconds as a keepalive. Auto-disconnects after 30 minutes of no matching events.\n\nSupports agent-session bearer auth (`Authorization: Bearer aas_...`) or API key auth (`X-API-Key: aak_...`).\n\n**curl example:**\n```bash\ncurl -N \"https://api.agentanalytics.sh/stream?project=my-site&events=page_view,signup\" \\\n  -H \"Authorization: Bearer aas_...\"\n```\n",
        "tags": [
          "Streaming"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": false,
            "description": "Project name. Defaults to first project.",
            "schema": {
              "type": "string"
            },
            "example": "my-site"
          },
          {
            "name": "events",
            "in": "query",
            "required": false,
            "description": "Comma-separated event name filter. Omit for all events.",
            "schema": {
              "type": "string"
            },
            "example": "page_view,signup"
          },
          {
            "name": "filter",
            "in": "query",
            "required": false,
            "description": "Property filter as `key:value` pairs separated by `;`. Multiple filters use AND logic.",
            "schema": {
              "type": "string"
            },
            "example": "path:/pricing;browser:Chrome"
          }
        ],
        "responses": {
          "200": {
            "description": "SSE event stream",
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string",
                  "description": "SSE stream with events:\n- `event: connected` — sent once on connection with active filters\n- `event: track` — each matching event with `id` for reconnection\n- `:heartbeat` — keepalive comment every 30s\n"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "description": "Too many concurrent streams (max 10 per account). Retry-After is 1800.",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/live": {
      "get": {
        "operationId": "getLiveSnapshot",
        "summary": "Live snapshot (real-time)",
        "description": "Returns a point-in-time snapshot of active visitors, sessions, events per minute, top pages, top events, and recent events.\n\nReads from an in-memory ring buffer — no D1 query. Data is available only while events are being streamed (the ring buffer evicts events older than 5 minutes).\n\nSupports agent-session bearer auth (`Authorization: Bearer aas_...`) or API key auth (`X-API-Key: aak_...`).\n\n**curl example:**\n```bash\ncurl \"https://api.agentanalytics.sh/live?project=my-site&window=60\" \\\n  -H \"Authorization: Bearer aas_...\"\n```\n",
        "tags": [
          "Streaming"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": false,
            "description": "Project name. Defaults to the first project you own.",
            "schema": {
              "type": "string"
            },
            "example": "my-site"
          },
          {
            "name": "window",
            "in": "query",
            "required": false,
            "description": "Time window in seconds (10-300, default 60)",
            "schema": {
              "type": "integer",
              "default": 60,
              "minimum": 10,
              "maximum": 300
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Live snapshot",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LiveSnapshotResponse"
                },
                "example": {
                  "project": "my-site",
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  },
                  "window_seconds": 60,
                  "timestamp": 1708000060000,
                  "active_visitors": 12,
                  "active_sessions": 8,
                  "events_per_minute": 47,
                  "top_pages": [
                    {
                      "path": "/",
                      "visitors": 5
                    }
                  ],
                  "top_events": [
                    {
                      "event": "page_view",
                      "count": 32
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/website-scans": {
      "post": {
        "operationId": "createPublicWebsiteScan",
        "summary": "Create public landing-page website analysis preview",
        "description": "Creates the public landing-page website analysis preview. Requests are root-domain only and return a preview plus a one-analysis `rst_*` resume token. They do not create `aas_*` agent sessions.\n\nPublic product copy should frame this as the fastest path to useful analytics, not as a generic audit. Recommendations include implementation hints that map to supported tracker.js capabilities instead of duplicate custom events for automatic signals.\n",
        "tags": [
          "Website Analysis"
        ],
        "security": [
          {}
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebsiteScanCreateRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Preview or full website analysis",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebsiteScanResponse"
                },
                "example": {
                  "ok": true,
                  "analysis_id": "scan_...",
                  "status": "succeeded",
                  "mode": "anonymous_preview",
                  "normalized_url": "https://example.com/",
                  "hostname": "example.com",
                  "resume_token": "rst_...",
                  "preview": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "result": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "agent_handoff": {
                    "label": "Give your agent analytics judgment"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid or unsafe website URL, missing project context, or project/domain mismatch",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Login required for full analysis",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "429": {
            "description": "Anonymous analyzer busy, cooldown active, or quota reached",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "schema": {
                  "type": "integer"
                },
                "description": "Seconds to wait before retrying."
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebsiteScanBusyError"
                }
              }
            }
          },
          "502": {
            "description": "Downstream scanner failed safely",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/cli/website-scans": {
      "post": {
        "operationId": "createCliWebsiteScan",
        "summary": "Create authenticated npx website analysis",
        "description": "Creates an authenticated website analysis for the npx CLI. This endpoint never falls back to the public Turnstile-protected landing-page scan path.\n\nNormal accounts must include `project`, and the analyzed hostname must match that project's configured `allowed_origins`. Complimentary Pro accounts identified by `entitlement_source='complimentary'` may omit `project`, may scan outside a requested project's origins, and are not subject to signed-in scan quotas or provider daily caps.\n",
        "tags": [
          "Website Analysis"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebsiteScanCreateRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Preview or full website analysis",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebsiteScanResponse"
                },
                "example": {
                  "ok": true,
                  "analysis_id": "scan_...",
                  "status": "succeeded",
                  "mode": "anonymous_preview",
                  "normalized_url": "https://example.com/",
                  "hostname": "example.com",
                  "resume_token": "rst_...",
                  "preview": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "result": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "agent_handoff": {
                    "label": "Give your agent analytics judgment"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid or unsafe website URL, missing project context, or project/domain mismatch",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Login required for authenticated website analysis",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "429": {
            "description": "Scanner busy, provider cap active, or quota reached",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "schema": {
                  "type": "integer"
                },
                "description": "Seconds to wait before retrying."
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebsiteScanBusyError"
                }
              }
            }
          },
          "502": {
            "description": "Downstream scanner failed safely",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/website-scans/{id}": {
      "get": {
        "operationId": "getWebsiteScan",
        "summary": "Resume a website analysis",
        "description": "Returns a previously created analysis. Account owners can read their own analyses. Anonymous previews require the matching `resume_token` query parameter.\n",
        "tags": [
          "Website Analysis"
        ],
        "security": [
          {},
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "resume_token",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "One-analysis `rst_*` token returned by anonymous preview creation."
          }
        ],
        "responses": {
          "200": {
            "description": "Website analysis",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebsiteScanResponse"
                },
                "example": {
                  "ok": true,
                  "analysis_id": "scan_...",
                  "status": "succeeded",
                  "mode": "anonymous_preview",
                  "normalized_url": "https://example.com/",
                  "hostname": "example.com",
                  "resume_token": "rst_...",
                  "preview": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "result": {
                    "framing": "fastest_path_to_useful_analytics",
                    "normalized_url": "https://example.com/",
                    "hostname": "example.com",
                    "advanced_tracking_later": [
                      {
                        "capability": "data-aa-impression"
                      }
                    ]
                  },
                  "agent_handoff": {
                    "label": "Give your agent analytics judgment"
                  }
                }
              }
            }
          },
          "404": {
            "description": "Analysis not found or token/account mismatch",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/project-context": {
      "get": {
        "operationId": "getProjectContext",
        "summary": "Get project analytics context",
        "description": "Returns compact project goals, activation events, event-name glossary entries, and date annotations. Project-scoped analytics result endpoints include this data as `project_context` when it is non-empty.\n\nDirect `GET /project-context` returns all stored annotations. Analytics result endpoints include only annotations inside the requested analytics date range plus one day before and after.\n\nUse `/properties` or `/properties/received` to inspect current event names before building or refreshing glossary entries.\n",
        "tags": [
          "Project Context"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Project name or ID."
          }
        ],
        "responses": {
          "200": {
            "description": "Project context",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectContextResponse"
                },
                "example": {
                  "ok": true,
                  "project": "my-site",
                  "project_id": "proj_123",
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  }
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found or unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "operationId": "setProjectContext",
        "summary": "Set project analytics context",
        "description": "Replaces the compact context for one project. Keep entries short because the context is returned with project-scoped analytics results for agents.\n\nThe encoded JSON request body is limited to 512KB.\n\nEach glossary entry must include `event_name`; agents should use `/properties` or `/properties/received` first to discover current project event names.\n\nAnnotations are for major product changes such as landing page, pricing, onboarding, feature, release, or experiment changes. Do not store git commit logs, PII, secrets, noisy edits, or long release notes.\n\nThis PUT replaces the whole context document, including annotations. To append one annotation without replacing goals, activation events, the glossary, or existing annotations, use `POST /project-context/annotations`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 context set my-site --json '{\"goals\":[\"Improve activation\"],\"activation_events\":[\"signup_completed\"],\"glossary\":[{\"event_name\":\"signup_completed\",\"term\":\"Signup\",\"definition\":\"A verified account completed signup.\"}],\"annotations\":[{\"occurred_at\":\"2026-04-25T13:00:00.000Z\",\"title\":\"Changed pricing page offer\",\"note\":\"Moved annual plan discount above the fold.\"}]}'`\n",
        "tags": [
          "Project Context"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectContextRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Project context updated",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectContextResponse"
                },
                "example": {
                  "ok": true,
                  "project": "my-site",
                  "project_id": "proj_123",
                  "project_context": {
                    "goals": [
                      "Increase activated Agent Analytics accounts"
                    ],
                    "activation_events": [
                      "signup_completed",
                      "project_created",
                      "first_event_received"
                    ],
                    "glossary": [
                      {
                        "event_name": "first_event_received",
                        "term": "AA Activation",
                        "definition": "Signup, project created, and first event received."
                      }
                    ],
                    "annotations": [
                      {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Moved annual plan discount above the fold."
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid body or context limits exceeded",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found or unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/project-context/annotations": {
      "post": {
        "operationId": "appendProjectContextAnnotation",
        "summary": "Append one project annotation",
        "description": "Appends one date annotation. Goals, activation events, the glossary, and existing annotations stay.\nThe write is compare-and-swap on `project_contexts.updated_at`, so two appends do not replace each other.\n\nNot a metered read. Not paid-only. Auth matches `PUT /project-context`: API key, dashboard session, or an agent session with `projects:write`.\nUnknown fields are rejected. The encoded JSON body is limited to 512KB (524288 bytes).\n\nThe identity of an annotation is normalized `occurred_at` plus `title`. The same pair already stored returns `200` with `appended: false`, the existing annotation, and the unchanged count. The new note is not written.\n\n`PUT /project-context` still replaces the whole document. A PUT that read the context before someone else's append can overwrite that append. An append that is in flight when a PUT lands retries, up to 32 times.\n",
        "tags": [
          "Project Context"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectContextAnnotationAppendRequest"
              },
              "example": {
                "project": "my-site",
                "occurred_at": "2026-04-20T15:00:00+03:00",
                "title": "Shipped landing edit",
                "note": "Moved the signup form above the fold."
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Annotation appended, or the same `occurred_at` and `title` were already stored.",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectContextAnnotationAppendResponse"
                },
                "examples": {
                  "appended": {
                    "summary": "New annotation stored",
                    "value": {
                      "ok": true,
                      "appended": true,
                      "project": "my-site",
                      "project_id": "proj_123",
                      "annotation": {
                        "occurred_at": "2026-04-20T12:00:00.000Z",
                        "title": "Shipped landing edit",
                        "note": "Moved the signup form above the fold."
                      },
                      "annotation_count": 2
                    }
                  },
                  "duplicate": {
                    "summary": "Same occurred_at and title already stored",
                    "value": {
                      "ok": true,
                      "appended": false,
                      "project": "my-site",
                      "project_id": "proj_123",
                      "annotation": {
                        "occurred_at": "2026-04-25T13:00:00.000Z",
                        "title": "Changed pricing page offer",
                        "note": "Original note."
                      },
                      "annotation_count": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unknown field, bad datetime, missing or blank title, title over 120 characters, or note over 500 characters (`VALIDATION_ERROR`).\nMissing `project` is `MISSING_FIELDS` with message `project required`.\nInvalid JSON is `INVALID_JSON` with message `invalid json`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknownField": {
                    "summary": "Field outside project, occurred_at, title, and note",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "unknown field: change"
                    }
                  },
                  "badDatetime": {
                    "summary": "occurred_at is not an ISO-8601 datetime",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "annotations.occurred_at must be an ISO-8601 datetime"
                    }
                  },
                  "missingTitle": {
                    "summary": "Blank title",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "annotations.title is required"
                    }
                  },
                  "missingProject": {
                    "summary": "project missing",
                    "value": {
                      "error": "MISSING_FIELDS",
                      "message": "project required"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "AUTH_REQUIRED",
                  "message": "unauthorized"
                }
              }
            }
          },
          "403": {
            "description": "Agent session without `projects:write`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "FORBIDDEN",
                  "message": "agent session missing required scope: projects:write"
                }
              }
            }
          },
          "404": {
            "description": "Project not found or unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found or unauthorized"
                }
              }
            }
          },
          "405": {
            "description": "Any method other than POST",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "VALIDATION_ERROR",
                  "message": "method not allowed"
                }
              }
            }
          },
          "409": {
            "description": "`VALIDATION_ERROR`. The project already has 100 annotations, the stored document cannot be parsed, or 32 compare-and-swap attempts were exhausted.\nA duplicate annotation is not a 409. Nothing is dropped when the cap is hit.\nAn in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.\n",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "cap": {
                    "summary": "100 annotations already stored",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "annotations can include at most 100 entries; this project already has 100, so the new annotation was not stored"
                    }
                  },
                  "conflict": {
                    "summary": "Compare-and-swap retries exhausted",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "project context changed concurrently; retry the append"
                    }
                  },
                  "unreadable": {
                    "summary": "Stored document cannot be rewritten",
                    "value": {
                      "error": "VALIDATION_ERROR",
                      "message": "stored project context is not valid JSON; refusing to rewrite it"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "description": "Body over 512KB (524288 bytes)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "VALIDATION_ERROR",
                  "message": "request body must be 524288 bytes or less"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/portfolio-context": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getPortfolioContext",
        "summary": "Get account portfolio context",
        "description": "Returns compact account-level goals, surface roles, shared milestones, and glossary for related projects. This is interpretive context only; it does not replace per-project activation definitions.",
        "tags": [
          "Project Context"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Portfolio context",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PortfolioContextResponse"
                },
                "example": {
                  "ok": true,
                  "account_id": "acc_123",
                  "portfolio_context": {
                    "goals": [
                      "Increase qualified users who reach setup"
                    ],
                    "surface_roles": [
                      {
                        "project": "docs.example.com",
                        "role": "discovery_surface"
                      }
                    ],
                    "shared_milestones": [
                      "qualified_click_to_product",
                      "signup",
                      "project_created"
                    ],
                    "glossary": [
                      {
                        "term": "Qualified click",
                        "definition": "A visitor reaches the product with relevant intent."
                      }
                    ]
                  }
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "operationId": "setPortfolioContext",
        "summary": "Set account portfolio context",
        "description": "Replaces account-level portfolio context. Use this for shared goals and surface roles across related projects; do not store PII, secrets, or long release notes.",
        "tags": [
          "Project Context"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PortfolioContext"
              },
              "examples": {
                "growthSystem": {
                  "value": {
                    "goals": [
                      "Increase qualified users who reach setup"
                    ],
                    "surface_roles": [
                      {
                        "project": "agentanalytics.sh",
                        "role": "scanner_and_conversion"
                      },
                      {
                        "project": "docs.agentanalytics.sh",
                        "role": "docs_surface"
                      }
                    ],
                    "shared_milestones": [
                      "qualified_click_to_product",
                      "signup",
                      "project_created"
                    ],
                    "glossary": [
                      {
                        "term": "Qualified click",
                        "definition": "A visitor reaches the product with relevant intent."
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Portfolio context updated",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PortfolioContextResponse"
                },
                "example": {
                  "ok": true,
                  "account_id": "acc_123",
                  "portfolio_context": {
                    "goals": [
                      "Increase qualified users who reach setup"
                    ],
                    "surface_roles": [
                      {
                        "project": "docs.example.com",
                        "role": "discovery_surface"
                      }
                    ],
                    "shared_milestones": [
                      "qualified_click_to_product",
                      "signup",
                      "project_created"
                    ],
                    "glossary": [
                      {
                        "term": "Qualified click",
                        "definition": "A visitor reaches the product with relevant intent."
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid body or context limits exceeded",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/portfolios": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "listPortfolios",
        "summary": "List identity lookup portfolios",
        "description": "Lists named project portfolios used to scope privacy-first HMAC email lookup across related projects.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Portfolio list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "portfolios": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Portfolio"
                      }
                    }
                  }
                },
                "example": {
                  "portfolios": [
                    {
                      "id": "pf_abc123",
                      "account_id": "acc_123",
                      "slug": "growth-system",
                      "name": "Growth system"
                    }
                  ]
                }
              }
            }
          }
        }
      },
      "post": {
        "operationId": "createPortfolio",
        "summary": "Create an identity lookup portfolio",
        "description": "Creates a named portfolio and optional project membership list. Existing member projects require `allow_move: true` before they can be moved from another portfolio.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "slug",
                  "name"
                ],
                "properties": {
                  "slug": {
                    "type": "string",
                    "pattern": "^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$",
                    "example": "growth-system"
                  },
                  "name": {
                    "type": "string",
                    "maxLength": 96,
                    "example": "Growth system"
                  },
                  "projects": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "example": [
                      "agentanalytics.sh",
                      "docs.agentanalytics.sh"
                    ]
                  },
                  "allow_move": {
                    "type": "boolean",
                    "default": false
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "201": {
            "description": "Portfolio created",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    },
                    "portfolio": {
                      "$ref": "#/components/schemas/Portfolio"
                    }
                  }
                },
                "example": {
                  "portfolio": {
                    "id": "pf_abc123",
                    "account_id": "acc_123",
                    "slug": "growth-system",
                    "name": "Growth system"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid body",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Slug or membership conflict. An in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/portfolios/{idOrSlug}": {
      "get": {
        "operationId": "getPortfolio",
        "summary": "Get an identity lookup portfolio",
        "description": "Returns the identity lookup portfolio identified by id or slug.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "idOrSlug",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Portfolio",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "portfolio": {
                      "$ref": "#/components/schemas/Portfolio"
                    }
                  }
                },
                "example": {
                  "portfolio": {
                    "id": "pf_abc123",
                    "account_id": "acc_123",
                    "slug": "growth-system",
                    "name": "Growth system"
                  }
                }
              }
            }
          }
        }
      },
      "patch": {
        "operationId": "updatePortfolio",
        "summary": "Update an identity lookup portfolio",
        "description": "Updates a portfolio name and/or replaces its project membership. Portfolio slugs are immutable.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "name": "idOrSlug",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "maxLength": 96
                  },
                  "projects": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "allow_move": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Portfolio updated",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    },
                    "portfolio": {
                      "$ref": "#/components/schemas/Portfolio"
                    }
                  }
                },
                "example": {
                  "portfolio": {
                    "id": "pf_abc123",
                    "account_id": "acc_123",
                    "slug": "growth-system",
                    "name": "Growth system"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid body",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Portfolio not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Membership conflict. An in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      },
      "delete": {
        "operationId": "deletePortfolio",
        "summary": "Delete an empty identity lookup portfolio",
        "description": "Deletes a portfolio only when it has no member projects.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "idOrSlug",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Portfolio deleted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Auth required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Portfolio not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Portfolio has members",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/projects": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "listProjects",
        "summary": "List all projects",
        "description": "Returns projects under your account with event/read counts and tier info.\nA session or project key limited to one project sees only that project.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 projects`\n",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Project list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "projects": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Project"
                      }
                    },
                    "has_api_key": {
                      "type": "boolean"
                    },
                    "tier": {
                      "type": "string",
                      "enum": [
                        "free",
                        "pro"
                      ]
                    }
                  }
                },
                "example": {
                  "projects": [
                    {
                      "name": "my-site",
                      "project_token": "aat_...",
                      "allowed_origins": "*"
                    }
                  ],
                  "tier": "free"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "post": {
        "operationId": "createProject",
        "summary": "Create a new project",
        "description": "Creates a new project and provisions a D1 database if needed.\nReturns the project token and a ready-to-use tracking snippet.\n\nCreating a project needs `admin` and an All projects grant. A project-limited caller cannot create a project, even at `admin`. Agent sessions cannot create, rotate, or reveal API keys.\n\nProject names must be alphanumeric with hyphens, underscores, or dots (max 64 chars).\nIf an active project with the same name already exists, returns the existing project (idempotent).\n\nHosted only: a name that matches a soft-deleted project on the same account is refused with `409` `PROJECT_NAME_RETIRED`. The message states that the name belonged to a deleted project and its events still exist. Active-name uniqueness is unchanged. Delete behavior is unchanged. The same refusal applies when renaming a project onto that name.\n\nPass `source_scan_id` when creating the project from a website analysis so activation can be tied back to the recommended instrumentation plan.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 create my-new-site --domain https://example.com --source-scan scan_...`\n",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name"
                ],
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "Project name (alphanumeric, hyphens, underscores, dots; max 64 chars)",
                    "pattern": "^[a-zA-Z0-9._-]{1,64}$",
                    "example": "my-new-site"
                  },
                  "allowed_origins": {
                    "type": "string",
                    "description": "Allowed origins for CORS. Use `*` for any origin.",
                    "default": "*",
                    "example": "https://example.com"
                  },
                  "source_scan_id": {
                    "type": "string",
                    "description": "Optional website analysis id to link to this project. Requires account ownership and hostname/origin match.",
                    "example": "scan_..."
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Project already exists (returned existing project)",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "project_token": {
                      "type": "string"
                    },
                    "existing": {
                      "type": "boolean",
                      "example": true
                    }
                  }
                }
              }
            }
          },
          "201": {
            "description": "Project created",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "project_token": {
                      "type": "string",
                      "example": "aat_..."
                    },
                    "allowed_origins": {
                      "type": "string"
                    },
                    "source_scan_id": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "snippet": {
                      "type": "string",
                      "description": "Ready-to-use HTML tracking snippet"
                    },
                    "api_example": {
                      "type": "string",
                      "description": "Example curl command for querying stats"
                    }
                  }
                },
                "example": {
                  "project_token": "aat_..."
                }
              }
            }
          },
          "400": {
            "description": "Missing name or invalid project name",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Duplicate origin, or `PROJECT_NAME_RETIRED` when the name matches a soft-deleted project on the same hosted account.\nThe retired-name message states that the name belonged to a deleted project and its events still exist.\nAn in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.\n",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "retiredName": {
                    "summary": "Name matches a soft-deleted project",
                    "value": {
                      "error": "PROJECT_NAME_RETIRED",
                      "message": "The name belonged to a deleted project and its events still exist."
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/projects/{id}": {
      "get": {
        "operationId": "getProject",
        "summary": "Get project details",
        "description": "Returns a single project with its configuration and today's usage stats.",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Project details",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "project_token": {
                      "type": "string"
                    },
                    "allowed_origins": {
                      "type": "string"
                    },
                    "usage_today": {
                      "type": "object"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Not your project",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "patch": {
        "operationId": "updateProject",
        "summary": "Update a project",
        "description": "Update a project's name and/or allowed origins.\n\n**Note:** Project name cannot be changed after events have been recorded.\n\nHosted only: renaming to a name that matches a soft-deleted project on the same account is `409` `PROJECT_NAME_RETIRED`. The message states that the name belonged to a deleted project and its events still exist. Active-name uniqueness is unchanged.\n",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "New project name"
                  },
                  "allowed_origins": {
                    "type": "string",
                    "description": "New allowed origins"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated project",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "project_token": {
                      "type": "string"
                    },
                    "allowed_origins": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid name or no fields to update",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Name locked (events recorded), duplicate name or origin, or `PROJECT_NAME_RETIRED` when the new name matches a soft-deleted project on the same hosted account.\nThe retired-name message states that the name belonged to a deleted project and its events still exist.\nAn in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.\n",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "retiredName": {
                    "summary": "Rename matches a soft-deleted project",
                    "value": {
                      "error": "PROJECT_NAME_RETIRED",
                      "message": "The name belonged to a deleted project and its events still exist."
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      },
      "delete": {
        "operationId": "deleteProject",
        "summary": "Delete a project",
        "description": "Soft-deletes a project. Revokes the project token (no new events can be written).\nEvent data is preserved in the database but no longer accessible via API.\nOn hosted, that name stays retired. Creating or renaming onto it returns `409` `PROJECT_NAME_RETIRED`.\n",
        "tags": [
          "Projects"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Project deleted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "deleted": {
                      "type": "string",
                      "description": "Project ID"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Not your project",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getAccount",
        "summary": "Get account info",
        "description": "Returns your account details, tier, limits, and project count.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 whoami` prints this account. For an agent session it also prints `project` (name or null) and `level` (`read`, `manage`, `admin`, or `legacy`).\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Account info",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountResponse"
                },
                "examples": {
                  "freeTier": {
                    "summary": "Free tier account",
                    "value": {
                      "id": "acc_free123",
                      "email": "free@example.com",
                      "github_login": "freeuser",
                      "tier": "free",
                      "created_at": "2026-02-01T12:00:00.000Z",
                      "projects_count": 2,
                      "tier_limits": {
                        "max_events_per_month": 100000,
                        "max_projects": 2,
                        "max_reads_per_month": 500,
                        "retention_days": 90,
                        "rate_limit_rpm": 10
                      },
                      "monthly_spend_cap_dollars": null
                    }
                  },
                  "proTier": {
                    "summary": "Pro tier account",
                    "value": {
                      "id": "acc_pro123",
                      "email": "pro@example.com",
                      "github_login": "prouser",
                      "tier": "pro",
                      "created_at": "2026-02-01T12:00:00.000Z",
                      "projects_count": 42,
                      "tier_limits": {
                        "max_events_per_month": -1,
                        "max_projects": -1,
                        "max_reads_per_month": -1,
                        "retention_days": 365,
                        "rate_limit_rpm": 1000
                      },
                      "monthly_spend_cap_dollars": 50
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/bot-traffic": {
      "get": {
        "operationId": "getBotTrafficOverview",
        "summary": "Filtered automated traffic for one project",
        "description": "Returns a project-scoped summary of automated traffic that reached Agent Analytics and was filtered out of normal analytics.\n\nThis endpoint reports daily aggregates only: automated request count, dropped event count, category breakdown, top actors, and a zero-filled time series for the selected period.\n\nThis is **not** full site bot visibility like CDN logs. It only includes automated requests that actually reached `POST /track` or `POST /track/batch`.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 bot-traffic my-site --period 7d --limit 5`\n\n**MCP:** `bot_traffic_overview`\n",
        "tags": [
          "Analytics"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          },
          {
            "name": "period",
            "in": "query",
            "required": false,
            "description": "Comparison period",
            "schema": {
              "type": "string",
              "enum": [
                "1d",
                "7d",
                "14d",
                "30d",
                "90d"
              ],
              "default": "7d"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Max actors to include in the top-actor list (1-50, default 10)",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 10
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Project bot traffic overview",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BotTrafficOverviewResponse"
                },
                "examples": {
                  "empty": {
                    "summary": "Empty state",
                    "value": {
                      "scope": "project",
                      "project": "my-site",
                      "period": {
                        "label": "7d",
                        "from": "2026-03-07",
                        "to": "2026-03-13",
                        "previous_from": "2026-02-28",
                        "previous_to": "2026-03-06"
                      },
                      "summary": {
                        "automated_requests": {
                          "current": 0,
                          "previous": 0,
                          "change": 0,
                          "change_pct": 0
                        },
                        "dropped_events": {
                          "current": 0,
                          "previous": 0,
                          "change": 0,
                          "change_pct": 0
                        },
                        "last_seen_at": null
                      },
                      "categories": [],
                      "actors": [],
                      "time_series": [
                        {
                          "date": "2026-03-13",
                          "requests": 0,
                          "dropped_events": 0
                        }
                      ]
                    }
                  },
                  "active": {
                    "summary": "Active bot traffic",
                    "value": {
                      "scope": "project",
                      "project": "my-site",
                      "period": {
                        "label": "7d",
                        "from": "2026-03-07",
                        "to": "2026-03-13",
                        "previous_from": "2026-02-28",
                        "previous_to": "2026-03-06"
                      },
                      "summary": {
                        "automated_requests": {
                          "current": 5,
                          "previous": 1,
                          "change": 4,
                          "change_pct": 400
                        },
                        "dropped_events": {
                          "current": 7,
                          "previous": 1,
                          "change": 6,
                          "change_pct": 600
                        },
                        "last_seen_at": 1773459600000
                      },
                      "categories": [
                        {
                          "category": "ai_agent",
                          "requests": 3,
                          "dropped_events": 5,
                          "share_pct": 60
                        },
                        {
                          "category": "search_crawler",
                          "requests": 2,
                          "dropped_events": 2,
                          "share_pct": 40
                        }
                      ],
                      "actors": [
                        {
                          "actor": "ChatGPT-User",
                          "category": "ai_agent",
                          "requests": 3,
                          "dropped_events": 5,
                          "last_seen_at": 1773459600000
                        },
                        {
                          "actor": "Googlebot",
                          "category": "search_crawler",
                          "requests": 2,
                          "dropped_events": 2,
                          "last_seen_at": 1773456000000
                        }
                      ],
                      "time_series": [
                        {
                          "date": "2026-03-13",
                          "requests": 5,
                          "dropped_events": 7
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid period or missing project",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found or unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/usage": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getAccountUsage",
        "summary": "Read account usage, pricing, and human payment handoff",
        "description": "Requires account authority; agent sessions need account:read. This is an unmetered\naccount read available on Free, subscription Pro, and complimentary Pro.\nReturns current limits, usage, estimates, spend cap, and a versioned payment object.\nOpen payment.next_action.url in the human browser when present. Only the human's\ndashboard session can create checkout or change billing. Poll this endpoint every\nfive seconds for up to fifteen minutes, then ask the human to return after activation.\nRetry the original task when payment.status.can_retry_pro_task is true; the route\nstill checks its own scopes and limits. A checkout redirect is not completion evidence.\nEstimates use Hosted billing math and exclude taxes and discounts; complimentary\naccounts have a zero estimate and no spend cap. No session, key, card, or signed\nbilling portal credential is returned.\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "AgentSession": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Current account commercial status",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "tier": {
                      "type": "string"
                    },
                    "entitlement_source": {
                      "type": "string",
                      "enum": [
                        "free",
                        "subscription",
                        "complimentary"
                      ]
                    },
                    "billing_status": {
                      "type": "string"
                    },
                    "account_activation": {
                      "type": "object",
                      "additionalProperties": true
                    },
                    "limits": {
                      "type": "object",
                      "additionalProperties": true
                    },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "total_events_this_month": {
                          "type": "integer"
                        },
                        "total_events_lifetime": {
                          "type": "integer"
                        },
                        "total_reads_this_month": {
                          "type": "integer"
                        },
                        "estimated_bill": {
                          "type": "number",
                          "description": "Estimated monthly USD charge before taxes and discounts; zero for non-subscription accounts."
                        },
                        "monthly_events_history": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "additionalProperties": true
                          }
                        }
                      },
                      "additionalProperties": true
                    },
                    "spend_cap": {
                      "type": "object",
                      "properties": {
                        "monthly_spend_cap_dollars": {
                          "type": [
                            "number",
                            "null"
                          ]
                        },
                        "spend_percentage": {
                          "type": [
                            "number",
                            "null"
                          ]
                        }
                      }
                    },
                    "projects": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "additionalProperties": true
                      }
                    },
                    "payment": {
                      "$ref": "#/components/schemas/PaymentHandoff"
                    }
                  }
                },
                "example": {
                  "entitlement_source": "free"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account authority",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Agent session missing account:read",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/all-sites": {
      "get": {
        "operationId": "getAllSitesOverview",
        "summary": "Historical all-sites overview",
        "description": "Returns a lightweight historical summary across all active projects in your account.\n\nThis endpoint is optimized for a single account-level dashboard view: total event trend, active project count, daily event time series, and a top-project list.\n\nUse `/live` for a real-time snapshot of one project. Use project-scoped endpoints like `/stats` and `/insights` when you want deeper analysis for one project.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 all-sites --period 7d`\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "period",
            "in": "query",
            "required": false,
            "description": "Comparison period",
            "schema": {
              "type": "string",
              "enum": [
                "1d",
                "7d",
                "14d",
                "30d",
                "90d"
              ],
              "default": "7d"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Max projects to include in the top-project list (1-50, default 10)",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 10
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Account-wide historical overview",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AllSitesOverviewResponse"
                },
                "example": {
                  "scope": "account",
                  "period": {
                    "label": "7d",
                    "from": "2026-03-03",
                    "to": "2026-03-09",
                    "previous_from": "2026-02-24",
                    "previous_to": "2026-03-02"
                  },
                  "summary": {
                    "total_projects": 3,
                    "active_projects": 2,
                    "total_events": {
                      "current": 120,
                      "previous": 90,
                      "change": 30,
                      "change_pct": 33
                    }
                  },
                  "time_series": [
                    {
                      "date": "2026-03-09",
                      "events": 40
                    }
                  ],
                  "projects": [
                    {
                      "id": "proj_123",
                      "name": "my-site",
                      "events": 80,
                      "share_pct": 66.7,
                      "last_active_date": "2026-03-09"
                    }
                  ],
                  "remaining_projects": 1
                }
              }
            }
          },
          "400": {
            "description": "Invalid period",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/bot-traffic": {
      "get": {
        "operationId": "getAllSitesBotTrafficOverview",
        "summary": "Filtered automated traffic across all active projects",
        "description": "Returns an account-scoped summary of automated traffic that reached Agent Analytics and was filtered out of normal analytics.\n\nThis endpoint is optimized for a lightweight all-sites view: total filtered requests, dropped events, active-project count, top-project list, category breakdown, and a zero-filled daily time series.\n\nDeleted projects are excluded from the totals and rankings.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 bot-traffic --all --period 7d --limit 10`\n\n**MCP:** `all_sites_bot_traffic`\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "period",
            "in": "query",
            "required": false,
            "description": "Comparison period",
            "schema": {
              "type": "string",
              "enum": [
                "1d",
                "7d",
                "14d",
                "30d",
                "90d"
              ],
              "default": "7d"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Max projects to include in the top-project list (1-50, default 10)",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 10
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Account-wide bot traffic overview",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AllSitesBotTrafficOverviewResponse"
                },
                "examples": {
                  "accountOverview": {
                    "summary": "Account bot traffic overview",
                    "value": {
                      "scope": "account",
                      "period": {
                        "label": "7d",
                        "from": "2026-03-07",
                        "to": "2026-03-13",
                        "previous_from": "2026-02-28",
                        "previous_to": "2026-03-06"
                      },
                      "summary": {
                        "automated_requests": {
                          "current": 5,
                          "previous": 1,
                          "change": 4,
                          "change_pct": 400
                        },
                        "dropped_events": {
                          "current": 6,
                          "previous": 1,
                          "change": 5,
                          "change_pct": 500
                        },
                        "active_projects": 2,
                        "total_projects": 4,
                        "last_seen_at": 1773459600000
                      },
                      "categories": [
                        {
                          "category": "ai_agent",
                          "requests": 3,
                          "dropped_events": 4,
                          "share_pct": 60
                        },
                        {
                          "category": "search_crawler",
                          "requests": 2,
                          "dropped_events": 2,
                          "share_pct": 40
                        }
                      ],
                      "projects": [
                        {
                          "id": "proj_123",
                          "name": "my-site",
                          "requests": 3,
                          "dropped_events": 4,
                          "share_pct": 60,
                          "last_seen_at": 1773459600000
                        },
                        {
                          "id": "proj_456",
                          "name": "second-site",
                          "requests": 2,
                          "dropped_events": 2,
                          "share_pct": 40,
                          "last_seen_at": 1773456000000
                        }
                      ],
                      "remaining_projects": 0,
                      "time_series": [
                        {
                          "date": "2026-03-13",
                          "requests": 5,
                          "dropped_events": 6
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid period",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/agent-sessions": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "listAgentSessions",
        "summary": "List active and historical agent sessions for the account",
        "description": "Returns agent sessions created for CLI, MCP, and managed runtimes under the authenticated account.\n",
        "tags": [
          "Agent Sessions"
        ],
        "security": [
          {
            "AgentSessionBearer": []
          },
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Agent sessions for the account",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "sessions": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/AgentSessionSummary"
                      }
                    }
                  }
                },
                "example": {
                  "sessions": [
                    {
                      "level": "read",
                      "status": "active"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/revoke-key": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "revokeKey",
        "summary": "Revoke and regenerate API key",
        "description": "Revokes the current API key and generates a new one. The old key stops working immediately.\nThe new key is returned in the response — this is the only time it's shown.\nThis route does not accept scoped agent-session bearer tokens.\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "New API key",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "api_key": {
                      "type": "string",
                      "description": "The new API key. Save this — it won't be shown again.",
                      "example": "aak_..."
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "api_key": "aak_..."
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Agent-session bearer auth is not allowed for raw API-key rotation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/account/feedback": {
      "post": {
        "operationId": "submitFeedback",
        "summary": "Submit product or workflow feedback",
        "description": "Sends feedback about Agent Analytics product gaps, confusing workflows, or missing capabilities to the internal review channel.\n\nThis endpoint is meant for sanitized summaries of what was hard and what Agent Analytics should have done instead. Do not include private owner details, secrets, API keys, or raw customer data.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 feedback --message \"...\"`\n",
        "tags": [
          "Account"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FeedbackRequest"
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Feedback accepted",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      }
    },
    "/account/deletion-feedback": {
      "post": {
        "operationId": "submitDeletionFeedback",
        "summary": "Send account deletion feedback",
        "description": "Accepts one post-delete survey response. The body carries a one-time `survey_token` from account deletion. No dashboard session is required.\n\n`reason` is one of `install_too_complicated`, `looking_for_human_dashboard`, `not_sure`, or `other`. `other` requires `details`. `detail_code` is only valid when `reason` is `install_too_complicated`, and then it is one of `install_docs`, `auth_or_login`, `paperclip_plugin`, `tracking_setup`, or `not_sure_where_to_start`.\n\nAn optional `Idempotency-Key` is honored only when the caller also presents an authenticated grant. The survey token alone is not that grant, so a key with no grant returns `401` `AUTH_REQUIRED`.\n",
        "tags": [
          "Account"
        ],
        "security": [],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "survey_token",
                  "reason"
                ],
                "properties": {
                  "survey_token": {
                    "type": "string",
                    "minLength": 1
                  },
                  "reason": {
                    "type": "string",
                    "enum": [
                      "install_too_complicated",
                      "looking_for_human_dashboard",
                      "not_sure",
                      "other"
                    ]
                  },
                  "detail_code": {
                    "type": "string",
                    "enum": [
                      "install_docs",
                      "auth_or_login",
                      "paperclip_plugin",
                      "tracking_setup",
                      "not_sure_where_to_start"
                    ]
                  },
                  "details": {
                    "type": "string"
                  }
                }
              },
              "example": {
                "survey_token": "survey_example",
                "reason": "not_sure"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Feedback accepted",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "ok"
                  ],
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "const": true
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "description": "Missing token, invalid reason, or details required for other",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Idempotency-Key was sent without an authenticated grant",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "410": {
            "description": "Survey token is missing, used, or expired",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "AUTH_REQUIRED",
                  "message": "survey unavailable or expired"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          },
          "503": {
            "description": "Survey storage is unavailable",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/experiments/config": {
      "get": {
        "operationId": "getExperimentConfig",
        "summary": "Get experiment config for tracker.js",
        "description": "Returns active experiments for a project, used by `tracker.js` to assign variants client-side.\nThis is a **public** endpoint — authenticated by project token (same as `/track`), not API key.\n\nYou don't call this directly — the tracker fetches it automatically on page load.\n",
        "tags": [
          "Experiments"
        ],
        "security": [],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "token",
            "in": "query",
            "required": true,
            "description": "Project token (`aat_*`)",
            "schema": {
              "type": "string"
            },
            "example": "aat_51da22cdcab084ae1cdb50fd4841c642f0dafdb1d9adfa6b"
          }
        ],
        "responses": {
          "200": {
            "description": "Active experiments for this project",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "experiments": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "key": {
                            "type": "string",
                            "example": "signup_cta"
                          },
                          "variants": {
                            "type": "array",
                            "items": {
                              "type": "object",
                              "properties": {
                                "key": {
                                  "type": "string"
                                },
                                "weight": {
                                  "type": "integer"
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "experiments": [
                    {
                      "key": "signup_cta"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Missing token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/experiments": {
      "post": {
        "operationId": "createExperiment",
        "summary": "Create an A/B experiment",
        "description": "Creates a new experiment for the specified project. **Pro tier only.**\n\nVariants are assigned client-side by `tracker.js` using a deterministic hash — same user always gets the same variant. Exposure events (`$experiment_exposure`) are tracked automatically.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 experiments create my-site --name signup_cta --variants control,new_cta --goal signup`\n",
        "tags": [
          "Experiments"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "project",
                  "name",
                  "variants",
                  "goal_event"
                ],
                "properties": {
                  "project": {
                    "type": "string",
                    "description": "Project name",
                    "example": "my-site"
                  },
                  "name": {
                    "type": "string",
                    "description": "Experiment name (alphanumeric, hyphens, underscores; max 64 chars)",
                    "pattern": "^[a-zA-Z0-9_-]{1,64}$",
                    "example": "signup_cta"
                  },
                  "variants": {
                    "type": "array",
                    "description": "2-4 variant keys",
                    "minItems": 2,
                    "maxItems": 4,
                    "items": {
                      "type": "string"
                    },
                    "example": [
                      "control",
                      "new_cta"
                    ]
                  },
                  "goal_event": {
                    "type": "string",
                    "description": "Event name to measure conversion (max 256 chars)",
                    "example": "signup"
                  },
                  "weights": {
                    "type": "array",
                    "description": "Optional traffic weights per variant (must sum to 100). Defaults to equal split.",
                    "items": {
                      "type": "integer"
                    },
                    "example": [
                      50,
                      50
                    ]
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "201": {
            "description": "Experiment created",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Experiment"
                },
                "example": {
                  "id": "exp_a1b2c3d4e5f6g7h8",
                  "name": "signup_cta",
                  "variants": [
                    {
                      "key": "control",
                      "weight": 50
                    }
                  ],
                  "goal_event": "signup",
                  "status": "active"
                }
              }
            }
          },
          "400": {
            "description": "Validation error (missing fields, invalid variants, duplicate name)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Pro tier required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Experiment name already exists in this project. An in-progress Idempotency-Key also uses this status, with error IDEMPOTENCY_IN_PROGRESS and a Retry-After header.",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      },
      "get": {
        "operationId": "listExperiments",
        "summary": "List experiments",
        "description": "Returns all experiments for a project (active, paused, and completed).\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 experiments list my-site`\n",
        "tags": [
          "Experiments"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/ProjectParam"
          }
        ],
        "responses": {
          "200": {
            "description": "Experiment list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "experiments": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Experiment"
                      }
                    }
                  }
                },
                "example": {
                  "experiments": [
                    {
                      "id": "exp_a1b2c3d4e5f6g7h8",
                      "name": "signup_cta",
                      "variants": [
                        {
                          "key": "control",
                          "weight": 50
                        }
                      ],
                      "goal_event": "signup",
                      "status": "active"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Missing project parameter",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Project not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/experiments/{id}": {
      "get": {
        "operationId": "getExperiment",
        "summary": "Get experiment with live results",
        "description": "Returns experiment config plus live Bayesian A/B test results.\n\nResults include `probability_best` (probability each variant is the winner), `lift` (relative improvement over baseline), `sufficient_data` (whether enough exposures exist), and a human-readable `recommendation`.\n\nThe system needs ~100 exposures per variant before results are statistically significant.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 experiments get exp_abc123`\n",
        "tags": [
          "Experiments"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Experiment ID (`exp_*`)",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Experiment with results",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Experiment"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "results": {
                          "$ref": "#/components/schemas/ExperimentResults"
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "id": "exp_a1b2c3d4e5f6g7h8",
                  "name": "signup_cta",
                  "variants": [
                    {
                      "key": "control",
                      "weight": 50
                    }
                  ],
                  "goal_event": "signup",
                  "status": "active",
                  "results": {
                    "variants": [
                      {
                        "key": "control",
                        "exposures": 520,
                        "unique_users": 480,
                        "conversions": 48,
                        "conversion_rate": 0.1
                      }
                    ],
                    "probability_best": {
                      "control": 0.06,
                      "new_cta": 0.94
                    },
                    "lift": {
                      "control": -0.32,
                      "new_cta": 0.47
                    },
                    "sufficient_data": true,
                    "recommendation": "'new_cta' is the winner with 94% probability (47% lift over baseline)"
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Not your experiment",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Experiment not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "patch": {
        "operationId": "updateExperiment",
        "summary": "Update experiment status",
        "description": "Update an experiment's status. Valid status transitions:\n- `active` → `paused` or `completed`\n- `paused` → `active` or `completed`\n- `completed` is terminal (no further changes)\n\nWhen completing, optionally set `winner` to a variant key.\n\n**CLI:**\n- `npx --yes @agent-analytics/cli@0.5.41 experiments pause exp_abc123`\n- `npx --yes @agent-analytics/cli@0.5.41 experiments resume exp_abc123`\n- `npx --yes @agent-analytics/cli@0.5.41 experiments complete exp_abc123 --winner new_cta`\n",
        "tags": [
          "Experiments"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Experiment ID (`exp_*`)",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "status": {
                    "type": "string",
                    "enum": [
                      "active",
                      "paused",
                      "completed"
                    ],
                    "description": "New status"
                  },
                  "winner": {
                    "type": "string",
                    "description": "Variant key to declare as winner (only when completing)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated experiment",
            "headers": {
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/IdempotentReplayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Experiment"
                },
                "example": {
                  "id": "exp_a1b2c3d4e5f6g7h8",
                  "name": "signup_cta",
                  "variants": [
                    {
                      "key": "control",
                      "weight": 50
                    }
                  ],
                  "goal_event": "signup",
                  "status": "active"
                }
              }
            }
          },
          "400": {
            "description": "Invalid status transition or missing status",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Not your experiment",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Experiment not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyInProgress"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyMismatch"
          }
        }
      },
      "delete": {
        "operationId": "deleteExperiment",
        "summary": "Delete an experiment",
        "description": "Permanently deletes an experiment. Event data (exposures, conversions) is preserved in the events table — only the experiment config is removed.\n\n**CLI:** `npx --yes @agent-analytics/cli@0.5.41 experiments delete exp_abc123`\n",
        "tags": [
          "Experiments"
        ],
        "security": [
          {
            "ApiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Experiment ID (`exp_*`)",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Experiment deleted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean",
                      "example": true
                    },
                    "deleted": {
                      "type": "string",
                      "description": "Experiment ID"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid API key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Not your experiment",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Experiment not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/erasures": {
      "post": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "createErasure",
        "summary": "Erase one subject",
        "description": "Delete one subject's stored rows. One subject per request. Available on all plans, including free.\n\n**Caller:** erasure needs `manage` or `admin`. A dashboard session cookie can erase. A project key (`aapk_*`) can erase at `manage` or `admin`, and only in its one project. `read` on `GET` and `POST` is `403` `FORBIDDEN_SCOPE`. The legacy account key (`aak_*`) is `403` `FORBIDDEN_SCOPE` with message `account API key cannot erase; use a project key or agent session with manage or admin`. A session without `erasures:write` is `403` `FORBIDDEN` with message `agent session missing required scope: erasures:write`. `analytics:read` and `projects:write` are not enough. The demo project is `403` `DEMO_READ_ONLY`. A project-limited caller that names another project receives `404` `PROJECT_NOT_FOUND`. Legacy sessions keep their stored scopes and all-projects access.\n\n**Rate:** 20 erasure accepts per account per hour. The cap is separate from the per-minute request limit. An erasure is not metered as a read. Over the cap is `429` `RATE_LIMITED` with `reason: \"erasure_rate_limit\"`.\n\n**Subject:** exactly one of `user_id`, `session_id`, or `email`. `confirm` must be the string `erase`. `idempotency_key` is required and unique per account. The same key and the same body return the original job. A retry of a failed job continues. The same key with a different body is `409` `IDEMPOTENCY_CONFLICT`.\n\n**user_id:** matches `events.user_id`, `events.resolved_user_id`, `sessions.user_id`, `sessions.resolved_user_id`, `identity_map.previous_id`, `identity_map.canonical_id`, `identity_aliases.alias_id`, `identity_aliases.canonical_id`, and `user_profiles.user_id`, limited to this project. The job walks `identity_map` and `identity_aliases` once and deletes those linked ids too, then deletes events, sessions, identity rows, `user_profiles`, and `email_lookup_index` rows for this project only.\n\n**session_id:** deletes events, sessions, and replay for that session, with no identity graph walk.\n\n**email:** normalized and HMAC'd the same way project email lookup is built, then the `user_id` path runs. The raw email is not stored on the job and is not returned. `portfolio` defaults to false and applies only to email. `portfolio: true` uses the portfolio HMAC and loops member projects. The default stays inside the named project.\n\nEvent and session deletes use the project name. Email lookup deletes use `scope_id = project:<uuid>`. A second project in the same database is left untouched. Rows whose properties merely contain the id are left in place.\n\n`include_replays` defaults to true. `confirm_large: true` is required when the subject matches more than 100,000 events. The pre-count is `COUNT(*)` on `events`. Otherwise the response is `400` `CONFIRM_LARGE_REQUIRED`.\n\nA missing `confirm`, two subject fields, an empty subject, or a subject longer than 256 characters is `400` `INVALID_ERASURE`.\n\n**Response:** `200` if the job finishes inside the request, `202` while it is still running. Poll `GET /erasures/{id}`. `GET /erasures?project=` returns the 100 newest receipts. Receipts include `subject_type` and counts. They omit the subject value, event payloads, and the raw email.\n\n**Late events:** Late events for an erased id are dropped for 7 days. After that, a new event with the same id is accepted. The tombstone stores the account, the project name, the SHA-256 of each id, and the email HMAC.\n\n**Audit:** Audit rows keep hashes for 24 months. Hashes are still identifiers. The audit row stores `subject_hash` and `requested_by` (`api_key`, `session`, or `agent_session` plus the session id). It omits the raw subject, property JSON, and replay bytes.\n\n**Restore:** A database restore can bring erased rows back for up to 30 days. Ask support to re-apply erasures after any restore.\n\n**Self-hosted:** the same route runs synchronously inside the request. Identity tables in OSS are only `identity_map`. Whoever holds `API_KEYS` can erase. A project string is not an authorization boundary. The operator re-applies after restoring a SQLite snapshot or a D1 Time Travel bookmark.\n\n**CLI:** `aa erase <project> --user-id <id> --confirm erase`. Also `--session-id` or `--email`. `--idempotency-key` is optional. When it is omitted, the CLI generates one and prints it. `aa erasures <project>` lists receipts. `aa erasures get <id>` reads one. When the level is too low, the command prints a clear hint to use `manage` or `admin`. `whoami` prints the project and level.\n\n**MCP:** `erase_subject` has `readOnlyHint: false` and `destructiveHint: true`. It requires `confirm` `erase`. It is registered only at `manage` or `admin`, when the session scopes include `erasures:write`. It is absent from the demo MCP. The tools that read a receipt are read-only. Agent sessions still need `manage` or `admin` (`erasures:write`) to call these routes. A `404` or `403` is returned as clear error text. When the grant is one project, tools default the project argument to that project.\n",
        "tags": [
          "Erasures"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ErasureCreateRequest"
              },
              "examples": {
                "userId": {
                  "summary": "Erase one user id inside a project",
                  "value": {
                    "project": "my-site",
                    "idempotency_key": "erase-user-123-2026-11-13",
                    "confirm": "erase",
                    "user_id": "user_123"
                  }
                },
                "emailInPortfolio": {
                  "summary": "Erase one email across the portfolio",
                  "value": {
                    "project": "my-site",
                    "idempotency_key": "erase-visitor-email-2026-11-13",
                    "confirm": "erase",
                    "email": "visitor@example.com",
                    "portfolio": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The job finished inside the request. `status` is `completed` or `failed`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErasureReceipt"
                },
                "examples": {
                  "completed": {
                    "summary": "Finished delete",
                    "value": {
                      "id": "era_01HZX",
                      "status": "completed",
                      "project": "my-site",
                      "subject_type": "user_id",
                      "counts": {
                        "events": 12,
                        "sessions": 2,
                        "identity_rows": 3,
                        "profiles": 1,
                        "email_lookups": 1,
                        "replay_sessions": 1,
                        "replay_objects": 4
                      },
                      "replay_included": true,
                      "completed_at": "2026-11-13T18:04:11.000Z",
                      "error": null
                    }
                  },
                  "failed": {
                    "summary": "Finished with a failure. A retry with the same key and body continues the job.",
                    "value": {
                      "id": "era_01HZX",
                      "status": "failed",
                      "project": "my-site",
                      "subject_type": "user_id",
                      "counts": {
                        "events": 0,
                        "sessions": 0,
                        "identity_rows": 0,
                        "profiles": 0,
                        "email_lookups": 0,
                        "replay_sessions": 0,
                        "replay_objects": 0
                      },
                      "replay_included": true,
                      "completed_at": "2026-11-13T18:04:11.000Z",
                      "error": "delete failed before completion"
                    }
                  }
                }
              }
            }
          },
          "202": {
            "description": "The job is still `pending` or `running`. Poll `GET /erasures/{id}`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErasureReceipt"
                },
                "example": {
                  "id": "era_01HZX",
                  "status": "running",
                  "project": "my-site",
                  "subject_type": "user_id",
                  "counts": {
                    "events": 0,
                    "sessions": 0,
                    "identity_rows": 0,
                    "profiles": 0,
                    "email_lookups": 0,
                    "replay_sessions": 0,
                    "replay_objects": 0
                  },
                  "replay_included": true,
                  "completed_at": null,
                  "error": null
                }
              }
            }
          },
          "400": {
            "description": "`INVALID_ERASURE` when `confirm` is missing, two subject fields are set, the subject is empty, or the subject is longer than 256 characters.\n`CONFIRM_LARGE_REQUIRED` when the subject matches more than 100,000 events and `confirm_large` is not true.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missingConfirm": {
                    "summary": "confirm is missing or is not erase",
                    "value": {
                      "error": "INVALID_ERASURE",
                      "message": "confirm must be the string erase"
                    }
                  },
                  "twoSubjects": {
                    "summary": "user_id and email were both set",
                    "value": {
                      "error": "INVALID_ERASURE",
                      "message": "send exactly one of user_id, session_id, or email"
                    }
                  },
                  "emptySubject": {
                    "summary": "The subject string is empty",
                    "value": {
                      "error": "INVALID_ERASURE",
                      "message": "subject must be a non-empty string"
                    }
                  },
                  "subjectTooLong": {
                    "summary": "Subject is longer than 256 characters",
                    "value": {
                      "error": "INVALID_ERASURE",
                      "message": "subject must be at most 256 characters"
                    }
                  },
                  "confirmLarge": {
                    "summary": "More than 100,000 matching events",
                    "value": {
                      "error": "CONFIRM_LARGE_REQUIRED",
                      "message": "subject matches more than 100,000 events; set confirm_large to true"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "`FORBIDDEN_SCOPE` when the level is `read`, and when the caller is a legacy account key (`aak_*`). The account key message is `account API key cannot erase; use a project key or agent session with manage or admin`.\n`FORBIDDEN` when an agent session lacks `erasures:write`. The message is `agent session missing required scope: erasures:write`.\n`DEMO_READ_ONLY` on the demo project.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missingScope": {
                    "summary": "Agent session without erasures:write",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: erasures:write"
                    }
                  },
                  "accountKey": {
                    "summary": "Legacy account key cannot erase",
                    "value": {
                      "error": "FORBIDDEN_SCOPE",
                      "message": "account API key cannot erase; use a project key or agent session with manage or admin"
                    }
                  },
                  "demo": {
                    "summary": "Demo project is read-only",
                    "value": {
                      "error": "DEMO_READ_ONLY",
                      "message": "demo project is read-only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Project is missing",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found"
                }
              }
            }
          },
          "409": {
            "description": "The idempotency key already exists for a different body",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "IDEMPOTENCY_CONFLICT",
                  "message": "idempotency_key was already used with a different body"
                }
              }
            }
          },
          "429": {
            "description": "20 erasure accepts per account per hour. `reason` is `erasure_rate_limit`.\nThis cap is separate from the per-minute request limit. An erasure is not metered as a read.\n",
            "headers": {
              "RateLimit": {
                "$ref": "#/components/headers/RateLimit"
              },
              "RateLimit-Policy": {
                "$ref": "#/components/headers/RateLimitPolicy"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfterLimit"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/Error"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "reason": {
                          "type": "string",
                          "const": "erasure_rate_limit"
                        },
                        "limit": {
                          "type": "integer",
                          "example": 20
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "error": "RATE_LIMITED",
                  "message": "erasure rate limit exceeded (20 accepts per hour)",
                  "reason": "erasure_rate_limit",
                  "limit": 20
                }
              }
            }
          }
        }
      },
      "get": {
        "operationId": "listErasures",
        "summary": "List erasure receipts for a project",
        "description": "Returns the 100 newest receipts for `project`. No subject values, no event payloads, and no raw email.\nOne subject per request still applies to `POST /erasures`. Available on all plans, including free.\nErasure reads need `manage` or `admin`. `read` and the legacy account key (`aak_*`) receive `403` `FORBIDDEN_SCOPE`. The account key message is `account API key cannot erase; use a project key or agent session with manage or admin`. A session without `erasures:write` is `403` `FORBIDDEN` with message `agent session missing required scope: erasures:write`. This read does not spend the 20 erasure accepts per hour cap and is not metered as a read.\n",
        "tags": [
          "Erasures"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "project",
            "in": "query",
            "required": true,
            "description": "Project name",
            "schema": {
              "type": "string"
            },
            "example": "my-site"
          }
        ],
        "responses": {
          "200": {
            "description": "Newest receipts, at most 100",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErasureList"
                },
                "example": {
                  "project": "my-site",
                  "erasures": [
                    {
                      "id": "era_01HZX",
                      "status": "completed",
                      "project": "my-site",
                      "subject_type": "user_id",
                      "counts": {
                        "events": 12,
                        "sessions": 2,
                        "identity_rows": 3,
                        "profiles": 1,
                        "email_lookups": 1,
                        "replay_sessions": 1,
                        "replay_objects": 4
                      },
                      "replay_included": true,
                      "completed_at": "2026-11-13T18:04:11.000Z",
                      "error": null
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "`FORBIDDEN_SCOPE` for `read` or a legacy account key (`aak_*`).\n`FORBIDDEN` when an agent session lacks `erasures:write`. The message is `agent session missing required scope: erasures:write`.\n`DEMO_READ_ONLY` on the demo project.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missingScope": {
                    "summary": "Agent session without erasures:write",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: erasures:write"
                    }
                  },
                  "accountKey": {
                    "summary": "Legacy account key cannot erase",
                    "value": {
                      "error": "FORBIDDEN_SCOPE",
                      "message": "account API key cannot erase; use a project key or agent session with manage or admin"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Project is missing, or the caller is limited to a different project (`PROJECT_NOT_FOUND`)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "PROJECT_NOT_FOUND",
                  "message": "project not found"
                }
              }
            }
          }
        }
      }
    },
    "/erasures/{id}": {
      "get": {
        "operationId": "getErasure",
        "summary": "Get one erasure receipt",
        "description": "Returns one receipt by `era_...` id. No subject value, no event payloads, and no raw email.\nErasure reads need `manage` or `admin`. `read` and the legacy account key (`aak_*`) receive `403` `FORBIDDEN_SCOPE`. A session without `erasures:write` is `403` `FORBIDDEN` with message `agent session missing required scope: erasures:write`. This read is not metered as a read.\nAudit rows keep hashes for 24 months. Hashes are still identifiers.\nA database restore can bring erased rows back for up to 30 days. Ask support to re-apply erasures after any restore.\nLate events for an erased id are dropped for 7 days.\n",
        "tags": [
          "Erasures"
        ],
        "security": [
          {
            "ApiKey": []
          },
          {
            "AgentSessionBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Erasure id (`era_...`)",
            "schema": {
              "type": "string"
            },
            "example": "era_01HZX"
          }
        ],
        "responses": {
          "200": {
            "description": "The receipt. `status` may still be `pending` or `running`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErasureReceipt"
                },
                "example": {
                  "id": "era_01HZX",
                  "status": "completed",
                  "project": "my-site",
                  "subject_type": "session_id",
                  "counts": {
                    "events": 4,
                    "sessions": 1,
                    "identity_rows": 0,
                    "profiles": 0,
                    "email_lookups": 0,
                    "replay_sessions": 1,
                    "replay_objects": 2
                  },
                  "replay_included": true,
                  "completed_at": "2026-11-13T18:04:11.000Z",
                  "error": null
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid account auth",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "`FORBIDDEN_SCOPE` for `read` or a legacy account key (`aak_*`). The account key message is `account API key cannot erase; use a project key or agent session with manage or admin`.\n`FORBIDDEN` when an agent session lacks `erasures:write`. The message is `agent session missing required scope: erasures:write`.\n`DEMO_READ_ONLY` on the demo project.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missingScope": {
                    "summary": "Agent session without erasures:write",
                    "value": {
                      "error": "FORBIDDEN",
                      "message": "agent session missing required scope: erasures:write"
                    }
                  },
                  "accountKey": {
                    "summary": "Legacy account key cannot erase",
                    "value": {
                      "error": "FORBIDDEN_SCOPE",
                      "message": "account API key cannot erase; use a project key or agent session with manage or admin"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Unknown erasure id",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "NOT_FOUND",
                  "message": "erasure not found"
                }
              }
            }
          }
        }
      }
    },
    "/tracker.js": {
      "get": {
        "parameters": [
          {
            "$ref": "#/components/parameters/ApiVersion"
          }
        ],
        "operationId": "getTracker",
        "summary": "JavaScript tracker script",
        "description": "Returns the lightweight JavaScript tracker used for browser-side analytics.\n\nEmbed it in your HTML:\n\n```html\n<script defer src=\"https://api.agentanalytics.sh/tracker.js\"\n        data-project=\"my-site\" data-token=\"aat_...\"\n        data-track-vitals=\"true\"></script>\n```\n\nRequired attributes:\n\n- `data-project`: project name\n- `data-token`: project token (`aat_*`)\n\nThe default snippet sets `data-track-vitals=\"true\"`. Hosted stores `cwv_*` on `page_view`. Self-hosted core stores the same keys on `$web_vitals`. `data-track-vitals=\"false\"`, or omitting the attribute, leaves collection off.\n\nThe tracker records an initial page view by default. Automatic `url` and `referrer` values are sanitized to `origin + pathname`; UTM collection is limited to the allowlisted `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, and `utm_term` parameters. SPA route changes require `data-track-spa=\"true\"` on the script tag or manual `page` calls. Browser, OS, device, language, timezone, session count, and first-touch attribution are collected without cookies.\n\nFull tracker documentation now lives in the docs site:\nhttps://docs.agentanalytics.sh/reference/tracker-js/\n",
        "tags": [
          "Tracking"
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "JavaScript file",
            "content": {
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    }
  }
}
