Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(endpoints): add five agent skills for working with endpoints (#60271)

Jovan Sakovicca11cfe98ab0
diff --git a/products/endpoints/skills/auditing-endpoints/SKILL.md b/products/endpoints/skills/auditing-endpoints/SKILL.md
new file mode 100644
index 000000000000..15c960455e04
--- /dev/null
+++ b/products/endpoints/skills/auditing-endpoints/SKILL.md
@@ -0,0 +1,210 @@
+---
+name: auditing-endpoints
+description: >
+ Audit every endpoint in a PostHog project for staleness, failed materialisations, and unused
+ materialised versions. Use when the user asks "what endpoints can I clean up?", "are any of my
+ endpoints broken?", "which materialised versions are still being called?", or wants a one-shot
+ cleanup pass over the Endpoints product. Produces a prioritised report grouped by issue type, with
+ recommended actions but does not modify anything without explicit confirmation.
+---
+
+# Auditing endpoints
+
+This skill produces a project-wide audit of the Endpoints product. Use it when the user wants to
+**find what to clean up** — unused endpoints, failing materialisations, materialised versions that
+nobody calls any more. It does not modify anything; it reports.
+
+The deeper investigation per endpoint is `diagnosing-endpoint-performance`. The audit's job is to
+find candidates and hand off.
+
+## When to use this skill
+
+- "Audit my endpoints" / "What endpoints can I clean up?"
+- The user is taking over a project and wants to know what they've inherited
+- A periodic review (monthly / quarterly) of endpoint sprawl
+- The user is over a materialisation cost budget and wants to know what to disable
+
+The dedicated tools give a fast endpoint-level view. For call frequency, recency, and cost over
+time, query the `query_log` table with `execute-sql` (endpoint-level). Per-version recency comes
+from `endpoint-versions` — each version carries its own `last_executed_at`.
+
+## Available tools
+
+| Tool | What it's for |
+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `execute-sql` (HogQL) | **Primary read path.** Query `system.data_modeling_endpoints` for metadata (name, is_active, current_version, derived_from_insight, last_executed_at) and `query_log` for endpoint-level usage (call counts, recency, duration, bytes) |
+| `endpoint-materialization-status` | Per endpoint: is materialisation eligible, current status, last run, last error (not in the system tables — use this tool) |
+| `endpoint-versions` | All versions for one endpoint, latest first, with each version's query, materialisation state, and `last_executed_at` |
+| `endpoint-update` | Write path — disable (`is_active: false`) or unmaterialise (`is_materialized: false`) after the user confirms |
+| `agent-feedback` | Tell the PostHog team what's missing or confusing in this flow so the product and skill improve |
+
+Prefer reading from the system tables over the `endpoints-get-all` / `endpoint-get` tools — one
+SQL query returns the whole inventory and lets you join metadata to usage in `query_log`.
+
+## What counts as an issue
+
+| Category | Trigger | Typical action |
+| ------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- |
+| **Never called** | No rows in `query_log` for the endpoint (personal-API-key calls only) | Confirm with the user, then disable |
+| **Stale** | `query_log` shows the last call more than 30 days ago | Confirm with the user; often safe to disable |
+| **Inactive** | `is_active = 0` in `system.data_modeling_endpoints` | Verify intent; if abandoned, delete |
+| **Failing materialisation** | `endpoint-materialization-status` returns `Failed` with an error | Hand off to `diagnosing-endpoint-performance` |
+| **Unused materialised version** | A materialised version whose `last_executed_at` (from `endpoint-versions`) is null or long stale | Unmaterialise that version, or roll to a newer one |
+| **Drifted versions** | Many versions exist (query changed repeatedly) | History noise — not an issue, but worth noting |
+
+Usage counts only **personal-API-key calls** — an endpoint exercised solely from the Playground
+tab or the app will look unused. Per-version `last_executed_at` is recorded only for runs since
+that tracking was added, so a version can read null while still being used; always confirm before
+removing.
+
+## Workflow
+
+### 1. List endpoints and their metadata
+
+One `execute-sql` query gets the whole inventory from `system.data_modeling_endpoints`:
+
+```sql
+SELECT name, is_active, current_version, derived_from_insight, last_executed_at
+FROM system.data_modeling_endpoints
+ORDER BY name
+```
+
+No rows → the project has no endpoints; say so and stop. Don't invent issues. (The
+`last_executed_at` column here is a convenience endpoint-level timestamp; for call frequency and
+cost, use `query_log` in the next step.)
+
+### 2. Pull usage from `query_log`
+
+`query_log` records every personal-API-key call, tagged with the endpoint name. One query gives
+recency and call counts across all endpoints:
+
+```sql
+SELECT name, count() AS calls, max(query_start_time) AS last_called
+FROM query_log
+WHERE endpoint LIKE '%/endpoints/%' AND is_personal_api_key_request
+GROUP BY name
+ORDER BY name
+```
+
+Cross-reference with step 1:
+
+- **In metadata, absent from `query_log`** → never called via API key
+- **Last call more than 30 days ago** → stale
+
+`query_log` also exposes `query_duration_ms`, `read_rows`, and `read_bytes` per call — useful to
+flag expensive endpoints in the same pass. This is endpoint-level; per-version recency comes from
+`endpoint-versions` (step 3).
+
+### 3. Check materialisation health and unused versions
+
+For each materialised endpoint, call `endpoint-materialization-status` (this isn't in the system
+tables). Surface any with `status: "Failed"` separately — these are active failures, not staleness.
+
+Then call `endpoint-versions` and read each version's `last_executed_at`: a **materialised**
+version that's null or long stale is an unused-materialised-version candidate. Treat this as a
+lead, not proof — per-version recency only counts API-key runs since tracking was added, so confirm
+with the user before unmaterialising.
+
+### 4. Present the audit
+
+Render a prioritised report grouped by category. Don't dump raw JSON; use a readable table per
+section:
+
+```text
+## Endpoints audit — 9 issues
+
+### 🔴 Failing materialisations (1)
+- weekly_revenue (v3) — Failed 2h ago, "Column 'event_date' does not exist"
+ → hand off to diagnosing-endpoint-performance
+
+### 🟠 Never called via API key (3)
+- internal_admin_query — created 5 months ago
+- legacy_signup_funnel — created 1 year ago, materialised
+- experiment_arm_lookup — created 9 months ago
+
+### 🟠 Unused materialised versions (2) [from endpoint-versions]
+- monthly_active_users — v3 materialised, last_executed_at null (currently on v4 — unmaterialise v3)
+- order_summary — v1 materialised, last_executed_at null
+
+### 🟡 Stale (3)
+- holiday_promo_2024 — last called 4 months ago
+- ab_test_phase_1 — last called 2 months ago
+- daily_revenue_cohort — last called 45 days ago
+
+Recommended order:
+1. Investigate the failing materialisation (blocks fresh data)
+2. Unmaterialise the unused versions (free storage + compute)
+3. Disable the never-called endpoints (if user confirms)
+4. Review stale endpoints with the user
+```
+
+The exact format is less important than: prioritised, grouped, actionable, and hand-off
+clear.
+
+### 5. Offer the next step
+
+End with a clear question, not a decision:
+
+- "Want me to unmaterialise the unused versions?" — needs `endpoint-update` with
+ `is_materialized: false` per version
+- "Want me to disable the never-called endpoints?" — needs `endpoint-update` with `is_active: false`
+- "Want me to dig into the failing materialisation?" — hands off to
+ `diagnosing-endpoint-performance`
+
+**Never act from the audit alone.** Disabling or unmaterialising affects external API consumers;
+always confirm before modifying.
+
+## Example interaction
+
+```text
+User: "Audit my endpoints"
+
+Agent steps:
+- execute-sql on system.data_modeling_endpoints → 12 endpoints (4 materialised)
+- execute-sql on query_log grouped by name → 8 endpoints have calls
+- endpoint-materialization-status on each materialised endpoint → 1 failing
+- endpoint-versions on the materialised ones → order_summary v2's last_executed_at is null
+
+- Report:
+ "Found 6 things worth looking at across 12 endpoints:
+
+ 🔴 Failing materialisations (1)
+ - monthly_active_users (v2) — materialisation failed yesterday with
+ 'memory limit exceeded'. The endpoint is still callable inline but
+ responses will be slower.
+
+ 🟠 Never called via API key (3)
+ - legacy_funnel_v1 — created 11 months ago
+ - test_export — created 3 months ago
+ - admin_dump — created 8 months ago, materialised (wasteful)
+
+ 🟠 Unused materialised versions (1) [from endpoint-versions]
+ - order_summary v2 — materialised but its last_executed_at is null
+ while v3 is current. Likely safe to unmaterialise v2.
+
+ 🟡 Stale (1)
+ - holiday_2024 — last called 5 months ago
+
+ Caveat: usage only counts personal-API-key calls; playground and
+ dashboard runs aren't counted. Per-version recency comes from
+ endpoint-versions and is sparse. Confirm before disabling.
+
+ Want me to start with the failing materialisation, or clean up the
+ unused version first?"
+```
+
+## Important notes
+
+- **The audit is read-only.** Never call destructive tools from this flow. Hand off or confirm
+ before any modification.
+- **Empty = healthy.** Don't pad an empty report with theoretical issues. "Nothing to clean up"
+ is a good answer.
+- **Read with SQL, drill in with the version tool.** `system.data_modeling_endpoints` (metadata)
+ and `query_log` (endpoint-level call counts, recency, cost) via `execute-sql` answer most of the
+ audit. Per-version recency comes from `endpoint-versions` (each version's `last_executed_at`).
+- **API-key-only scope.** Usage only counts personal-API-key calls. An endpoint exercised only from
+ the Playground tab or the app will look unused. Always confirm before acting.
+- **Materialisation costs storage and compute.** When an endpoint no longer needs materialisation,
+ the cheapest fix is `endpoint-update` with `is_materialized: false` — not deleting the endpoint.
+- **Inactive ≠ stale.** An endpoint with `is_active: false` was deliberately turned off. Don't
+ recommend deletion unless the user confirms it's truly abandoned.
diff --git a/products/endpoints/skills/consuming-endpoints-from-client-code/SKILL.md b/products/endpoints/skills/consuming-endpoints-from-client-code/SKILL.md
new file mode 100644
index 000000000000..62006e4cdc87
--- /dev/null
+++ b/products/endpoints/skills/consuming-endpoints-from-client-code/SKILL.md
@@ -0,0 +1,237 @@
+---
+name: consuming-endpoints-from-client-code
+description: >
+ Wire a PostHog endpoint into a client app or SDK. Covers fetching the OpenAPI spec, generating a
+ typed client with openapi-generator or @hey-api/openapi-ts, sending the right auth header,
+ shaping the variables payload (HogQL code_name vs insight breakdown property), handling
+ rate-limit and materialised-endpoint error responses. Use when the user says "how do I call my
+ endpoint", "generate a client for this", or "what auth header do I use".
+---
+
+# Consuming endpoints from client code
+
+This skill is the **caller-side** counterpart to `creating-an-endpoint`. It helps integrate an
+existing endpoint into a separate codebase — a mobile app, server backend, customer dashboard,
+or downstream pipeline. No PostHog code is modified here.
+
+## When to use this skill
+
+- "How do I call my endpoint?" / "What does a request look like?"
+- "Generate a typed TypeScript / Python / Go client for this endpoint"
+- "I'm getting a 401 calling the endpoint" / auth questions
+- "The endpoint rejects my call when I omit `user_id`" → materialised-endpoint variable
+ questions
+- "How do I handle rate limits?"
+
+If the user is **creating** the endpoint, use `creating-an-endpoint` first.
+
+## Available tools
+
+| Tool | Purpose |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------- |
+| `endpoint-get` | Full config for a named endpoint, including the query shape and required variables |
+| `endpoint-openapi-spec` | OpenAPI 3.0 spec for one endpoint, ready to feed to a code generator |
+| `endpoint-run` | A live call against the endpoint — useful to confirm a payload works before sharing it with the user's app |
+
+## The endpoint URL
+
+```text
+/api/projects/{team_id}/endpoints/{name}/run
+```
+
+- `team_id` is the project ID (numeric). Available in PostHog under project settings, or via
+ `posthog-get-projects` if the user doesn't know it.
+- `name` is the endpoint name — see `endpoints-get-all` if the user isn't sure.
+- The trailing `/run` is required.
+
+`POST` is the canonical method. `GET` also works for simple cases without a request body but
+POST is preferred — variables go in the body.
+
+## Auth
+
+Endpoints are authenticated with a **personal API key**. The header is:
+
+```http
+Authorization: Bearer <key>
+```
+
+Keys are scoped — for endpoints, the key needs at least `endpoint:read`. If the user gets a 403,
+they're usually missing the scope; if they get a 401, the key is missing or malformed.
+
+Never put a personal API key in client-side code that's shipped to end users (mobile apps,
+browser JS). Personal API keys grant scoped account access. For customer-facing apps, route
+through the user's own backend, which holds the key.
+
+## The request payload
+
+```json
+{
+ "variables": { "code_name_1": value, "code_name_2": value },
+ "limit": 100,
+ "offset": 0,
+ "refresh": "cache"
+}
+```
+
+| Field | Notes |
+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `variables` | Keyed by `code_name` for HogQL endpoints; for insight endpoints with breakdowns, key is the **breakdown property name** |
+| `limit` | Max rows returned. |
+| `offset` | Skip rows. Only HogQL endpoints |
+| `refresh` | `"cache"` (return cached results if fresh enough), `"force"` (always recalculate), `"direct"` (bypass materialisation, materialised endpoints only). Default is `"cache"` |
+
+Call `endpoint-get` to see the exact variable shape. The response includes the query definition
+with declared variables — each variable's `code_name` is what the client should send.
+
+## Materialised endpoints: all variables are required
+
+If `endpoint-get` shows `is_materialized: true` on the current version, the endpoint requires
+**every declared variable** to be passed on each call. This is a security boundary — without
+filters, a single call would return the entire pre-aggregated dataset.
+
+Common symptom: the user's app worked when the endpoint was unmaterialised, then started
+returning 400 errors after materialisation was enabled. The error message lists which variables
+are missing.
+
+Optional/partial variables on materialised endpoints are a known limitation the PostHog team plans
+to lift. If requiring every variable is blocking the user's use case, send a note via the
+`agent-feedback` tool — that demand signal is how the team prioritises it.
+
+## Generating a typed client
+
+The endpoint exposes its own OpenAPI 3.0 spec via `endpoint-openapi-spec`. Feed that into a code
+generator:
+
+| Language | Tool | Command shape |
+| ---------- | ----------------------- | -------------------------------------------------------------------------------- |
+| TypeScript | `@hey-api/openapi-ts` | `openapi-ts -i spec.json -o ./generated` |
+| TypeScript | `openapi-generator-cli` | `openapi-generator-cli generate -i spec.json -g typescript-fetch -o ./generated` |
+| Python | `openapi-generator-cli` | `openapi-generator-cli generate -i spec.json -g python -o ./generated` |
+| Go | `oapi-codegen` | `oapi-codegen -package=client spec.json > client.go` |
+
+The generated client gives the user types for the variables payload and the response shape. Re-
+generate when the endpoint's query changes (each new version may have different variables).
+
+If the user has multiple endpoints, generate a spec per endpoint and either combine them, or
+generate one client per endpoint and use them side-by-side.
+
+## Response shape
+
+A typical successful response:
+
+```json
+{
+ "results": [[...], [...]],
+ "columns": ["col_a", "col_b"],
+ "types": ["Int64", "String"],
+ "hasMore": false,
+ "name": "endpoint_name",
+ "endpoint_version": 4,
+ "endpoint_version_created_at": "2026-01-15T..."
+}
+```
+
+- `results` is an array of rows; each row is an array of cell values in the order of `columns`.
+- `endpoint_version` tells the client which version actually ran — useful for logging and for
+ pinning to a known version with `?version=N`.
+
+For insight endpoints, the response shape depends on the query kind (`TrendsQuery`,
+`LifecycleQuery`, `RetentionQuery`) — the OpenAPI spec captures the right shape for the current
+version. Insight kinds that can't be materialised (e.g. `FunnelsQuery`) still return their inline
+result shape.
+
+## Calling from the PostHog CLI
+
+For local testing, scripts, or CI, the repo's `posthog-cli` calls endpoints without hand-rolling
+HTTP:
+
+- `posthog-cli exp endpoints run` — execute an endpoint (from a local YAML definition)
+- `posthog-cli exp endpoints {list,get,pull,push,diff}` — inspect endpoints, or manage them as YAML
+ files in version control (GitOps-style)
+
+Auth uses the same personal API key, via `posthog-cli login` or the `POSTHOG_CLI_API_KEY` /
+`POSTHOG_CLI_PROJECT_ID` / `POSTHOG_CLI_HOST` env vars. (These live under `exp` — experimental, may
+change.)
+
+## Error responses to handle
+
+| Status | When | Handling |
+| ------ | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
+| 400 | Missing required variable on a materialised endpoint, or invalid variable type | Surface the error message; fix the call |
+| 401 | Missing / wrong personal API key | Check the Authorization header |
+| 403 | Key lacks `endpoint:read` scope, or endpoint is in another project | Adjust key scopes |
+| 404 | Endpoint name typo, or endpoint not active | Confirm name; check `is_active` |
+| 429 | Rate limited — limits are per team, not per endpoint (see note below) | Exponential backoff; cache responses client-side if possible |
+| 5xx | Query execution failure (ClickHouse error, timeout, etc.) | Retry with backoff. If persistent, hand off to `diagnosing-endpoint-performance` |
+
+## Workflow
+
+1. Confirm endpoint name. If unknown, list them with `execute-sql` on
+ `system.data_modeling_endpoints` (or `endpoints-get-all`).
+2. `endpoint-get` to see the full shape: variables, materialisation status, query kind.
+3. Decide the auth posture: personal API key on a server, never client-side.
+4. If the user wants generated types, call `endpoint-openapi-spec`, hand them the spec, and
+ recommend a generator for their language.
+5. Build a sample request payload from the variable declarations and walk through a test call.
+6. Optionally call `endpoint-run` from this skill to confirm the payload works.
+7. Wrap up with handling notes: the materialised-variables rule, the rate-limit shape, and
+ pinning to a version with `?version=N`.
+
+## Example interaction
+
+```text
+User: "I want to call monthly_active_users from my Node.js backend.
+ Can you help me wire it up with types?"
+
+Agent steps:
+- endpoint-get monthly_active_users → HogQL, variables: lookback_days
+ (int, default 30), org_id (string, no default), is_materialized: true
+- "Two things to know upfront:
+ 1. This endpoint is materialised, so both lookback_days and org_id
+ must be passed on every call. Calls without them will be rejected.
+ 2. You'll need a personal API key with endpoint:read scope. Set it
+ as PH_API_KEY in your server env — never ship it in client code."
+
+- endpoint-openapi-spec monthly_active_users → returns spec
+
+- "Here's the spec. Drop it in your repo and run:
+ pnpm dlx @hey-api/openapi-ts -i spec.json -o ./generated/posthog
+ That gives you typed client functions.
+
+ A minimum call looks like:
+ POST /api/projects/12345/endpoints/monthly_active_users/run
+ Authorization: Bearer <PH_API_KEY>
+ Content-Type: application/json
+
+ { 'variables': { 'org_id': 'acme', 'lookback_days': 30 } }
+
+ The response includes columns and rows — your client will pick that
+ up from the generated types.
+
+ Want me to do a sample call to verify the payload works?"
+```
+
+## Important notes
+
+- **Personal API keys are server-side only.** Never ship them in mobile apps or browser JS.
+- **Re-generate the client when the query changes.** Each new endpoint version may add or
+ remove variables — keep types in sync by re-fetching the spec.
+- **Materialised endpoints reject calls missing variables.** This is intentional. If the user
+ reports a 400 after materialisation was enabled, the fix is in the call, not in the endpoint.
+- **Pin to a version — don't rely on "latest".** Always call with `?version=N`. Without it the
+ latest active version runs, so a future query edit (which cuts a new version) can silently change
+ a caller's results. Bump the pinned version deliberately once you've validated the new one.
+- **Caching on the client side is fair game.** The endpoint already caches via
+ `data_freshness_seconds`, but the client can layer another cache on top for hot paths. Be
+ mindful of total staleness (endpoint cache + client cache).
+- **Rate limits are per team, by category — not per endpoint.** Calls to non-materialised
+ endpoints share the team-wide API-query budget (~240/min burst, ~2400/hour sustained) with all
+ other query traffic; materialised endpoints draw on a separate, higher shared bucket
+ (~1200/min, ~12000/hour). There is no per-endpoint-name limit, so hammering one endpoint can
+ starve others on the same team. Heavy callers should batch where possible and back off on 429.
+- **Pricing.** Calling endpoints isn't billed today, but it will be once endpoints ship alongside
+ the [managed warehouse](https://posthog.com/data-stack/managed-warehouse). Flag this to the user
+ if they're planning high-volume usage so the future cost isn't a surprise.
+- **Tell PostHog what's missing.** If an error, a limit, or a missing capability gets in the way,
+ use the `agent-feedback` tool — it's the main signal the team uses to improve endpoints and these
+ tools.
diff --git a/products/endpoints/skills/creating-an-endpoint/SKILL.md b/products/endpoints/skills/creating-an-endpoint/SKILL.md
new file mode 100644
index 000000000000..2ae4ba087e0e
--- /dev/null
+++ b/products/endpoints/skills/creating-an-endpoint/SKILL.md
@@ -0,0 +1,224 @@
+---
+name: creating-an-endpoint
+description: >
+ Create a PostHog endpoint with the right shape on the first try — covers query kind choice, name
+ conventions, what to expose as variables (HogQL code_name vs insight breakdown),
+ data_freshness_seconds, and whether to materialise on day one. Use when the user says "create an endpoint", "expose this
+ query as an API", "turn this insight into an endpoint", or asks for help structuring a new
+ endpoint. Steers away from common mistakes: materialising a query with cohort breakdowns or
+ compare mode, inline-only variables on a materialised endpoint, unbounded date ranges, ambiguous
+ names.
+---
+
+# Creating an endpoint
+
+This skill walks through creating a new endpoint with the right configuration. Endpoints expose
+saved HogQL or insight queries as callable HTTP routes — the configuration choices made at
+creation time determine cost, latency, and how callers integrate.
+
+The materialisation deep-dive lives at `references/materializing.md`. Pull it in when the
+materialisation decision is non-obvious.
+
+## When to use this skill
+
+- "Create an endpoint for [query]"
+- "Expose this insight as an API"
+- "Help me turn this HogQL into a callable endpoint"
+- A new caller (mobile app, customer-facing dashboard, downstream pipeline) needs PostHog data
+ and the user is choosing how to deliver it
+
+## Decisions to make in order
+
+### 1. Should this even be an endpoint?
+
+Endpoints are right when:
+
+- An **external system** (someone else's code) needs to call PostHog for data
+- The query is **stable** — not exploratory analysis
+- The shape is **reusable** — same query with different parameters
+
+Endpoints are wrong when:
+
+- An internal PostHog dashboard or insight needs the data — use the insight directly; an endpoint
+ only adds an external API surface you don't need internally
+- One-off, exploratory analysis — use the `execute-sql` tool (or the SQL editor) directly
+
+Heavy aggregation is **not** a reason to avoid an endpoint. Endpoints are themselves saved
+queries, and a heavy, frequently-called aggregation is often the _best_ case for an endpoint with
+materialisation turned on.
+
+If the user is unsure, ask what's calling the endpoint and what shape they expect.
+
+### 2. Pick a name
+
+Names are URL-safe (letters, numbers, hyphens, underscores), start with a letter, max 128 chars,
+must be unique within the project. Lean toward:
+
+- **Descriptive over generic** — `weekly_active_users_by_org` over `metrics`
+- **Snake_case** — matches how the name appears in code paths and URLs
+- **No version in the name** — versions are managed by the endpoint itself
+- **No "endpoint" in the name** — redundant
+
+The name appears in the URL: `/api/projects/{team_id}/endpoints/{name}/run`. It's not
+trivially renameable later (callers depend on the path) — get it right at creation.
+
+### 3. Pick the query kind
+
+Two options exist:
+
+- **HogQL** (`HogQLQuery`) — raw SQL written by the user. Variables defined via `{variables.x}`
+ syntax, matched on `code_name`. Recommended for new endpoints when the caller cares about
+ the exact column shape of the response.
+- **Insight** — wraps an existing insight definition. Best supported for `TrendsQuery`,
+ `LifecycleQuery`, and `RetentionQuery`: these can be materialised, and the breakdown can act as
+ a variable (Trends and Retention only; Lifecycle has no breakdown). Other insight kinds such as
+ `FunnelsQuery` can run inline but **cannot be materialised and don't expose breakdown
+ variables** — rewrite those as HogQL if you need either.
+
+HogQL is the more flexible choice. Pick insight only when the user is genuinely re-publishing an
+existing insight (see "Creating from an existing insight" below) rather than building a new query.
+
+### 4. Decide which inputs become variables
+
+Anything that should change per-caller goes in variables; the rest is hard-coded in the query.
+
+**For HogQL endpoints**, variables are declared in the query payload with `code_name`, `type`,
+and `default`. Each execution call passes `{ "variables": { "<code_name>": value } }`.
+
+Common patterns:
+
+- Time windows: `date_from`, `date_to`, or a single `lookback_days` integer
+- Identity filters: `user_id`, `account_id`, `team_id`
+- Pagination control beyond `limit` / `offset` (these are first-class on the run endpoint already)
+
+**For insight endpoints**, the breakdown property acts as the variable (Trends and Retention
+only — Lifecycle has no breakdown). Pass the breakdown property name as the key. `date_from` /
+`date_to` are accepted as variables **only on non-materialised** insight endpoints — a materialised
+endpoint bakes its date range into the view, so callers can't shift the window.
+
+Avoid:
+
+- **Variables that change the shape of the result** — keep the columns stable. If callers need
+ fundamentally different result shapes, ship separate endpoints.
+- **Variables that bypass safety** — don't expose a `where_clause` variable that lets callers
+ inject arbitrary SQL.
+
+### Creating from an existing insight
+
+There's no server-side "make an endpoint from insight N" operation. To do it: read the insight's
+query (via the insight tools), pass that query to `endpoint-create`, and set `derived_from_insight`
+to the insight's short id so the origin is recorded. The endpoint then owns its own **copy** of
+the query — later edits to the insight don't propagate. Starting from scratch instead? Build the
+query first with the insight / `sql-variables` tools, then create the endpoint from it.
+
+### 5. Set `data_freshness_seconds`
+
+This one field does **two** jobs, so set it deliberately:
+
+1. **Cache TTL** — results are served from cache until they're this many seconds old.
+2. **Materialisation refresh frequency** — on a materialised endpoint, this is also how often the
+ warehouse recomputes the materialised view.
+
+So a lower value means fresher data _and_ more frequent recompute/refresh cost; a higher value is
+cheaper on both counts but staler.
+
+The value must be one of a fixed set: `900` (15 min), `1800` (30 min), `3600` (1 h), `21600`
+(6 h), `43200` (12 h), `86400` (24 h, default), `604800` (7 d). There is no sub-15-minute
+option — `900` is the floor.
+
+| `data_freshness_seconds` | When to pick it |
+| ------------------------ | -------------------------------------------------------------------- |
+| 900–1800 | Freshest available — dashboards where staleness is visible |
+| 3600–43200 | Most cases — fresh enough for product usage, cheap to recompute |
+| 86400–604800 | Reports, weekly/daily metrics, anything aggregated over long periods |
+
+Bias toward higher values unless the user explicitly needs fresher data. On a materialised
+endpoint, remember this also sets the refresh cadence.
+
+### 6. Decide on day-one materialisation
+
+See `references/materializing.md` for the full decision tree. Short version:
+
+- **Recommend materialisation** when the endpoint will be called frequently, latency matters,
+ and the user can tolerate staleness equal to the refresh interval (typically 5-15 minutes for
+ scheduled materialisation, or hourly).
+- **Skip materialisation** for low-traffic endpoints, exploratory new endpoints (you don't
+ know yet if it'll get called), and queries where freshness is critical.
+
+If unsure, create unmaterialised and add `is_materialized: true` later once usage stabilises.
+That avoids paying for materialisation on a query nobody ends up calling.
+
+## Workflow
+
+1. Confirm the use case (step 1 above). If it's not actually a fit for an endpoint, recommend
+ the alternative.
+2. Agree a name with the user.
+3. Walk through the query — confirm it's HogQL or insight, and that the columns/shape make sense.
+4. Identify what should be a variable. Show the user the variable declaration syntax.
+5. Pick `data_freshness_seconds` based on the user's freshness requirement (ask if not clear) —
+ remembering it also sets the materialisation refresh cadence.
+6. Make the materialisation call. If on the fence, ship without and revisit later.
+7. Call `endpoint-create` with the agreed config.
+8. Confirm by calling `endpoint-run` with a sample payload to verify the response shape.
+9. Hand off to `consuming-endpoints-from-client-code` if the user is about to wire it up.
+
+## Example interaction
+
+```text
+User: "I want to expose our monthly active users count as an API
+ for our analytics partner"
+
+Agent:
+- "Quick check: is the partner going to call this on demand, or
+ should we be pushing data to them? Endpoints are pull-only."
+- User: "On demand"
+- "Got it. A few choices:
+ - Name: how about monthly_active_users? Lowercase, descriptive,
+ no version baggage.
+ - The query — is it HogQL or are you exposing an existing insight?
+ HogQL gives you exact column control; insight reuses what you've
+ already built.
+ - What should the partner be able to filter by? Org, time window,
+ both?
+ - How fresh? If MAU drifts within a day is fine, we can cache
+ results for 1-24 hours and serve almost everything from cache.
+ - Materialisation: if the partner is going to hit this many times
+ per day, materialising it would make responses near-instant.
+ The trade-off is ~10-15 minute staleness.
+
+ What's your starting point on these?"
+
+[user picks: HogQL, lookback_days + org_id variables, 3600s TTL,
+ not materialised yet]
+
+- endpoint-create monthly_active_users {query, variables, ...}
+- endpoint-run with sample payload {org_id: "test", lookback_days: 30}
+- "Created and tested. Want help wiring up the client code?
+ That's consuming-endpoints-from-client-code."
+```
+
+## Important notes
+
+- **The name lives in the URL.** Changing it later requires migrating callers. Pick well.
+- **HogQL endpoints are more flexible than insight endpoints.** Default to HogQL unless the
+ user has a specific reason to wrap an existing insight.
+- **Variables with no default fail at call time.** Always set defaults during creation so the
+ endpoint is testable from the playground without specifying every variable.
+- **Materialised endpoints require all variables to be passed.** Calls without them are
+ rejected — this is intentional (security: prevents returning unfiltered data). Pair the
+ materialisation recommendation with a note to the user about which variables become required.
+ (Optional/partial variables on materialised endpoints are a known limitation the PostHog team
+ plans to lift — if it's blocking the user, nudge them via the `agent-feedback` tool.)
+- **Don't enable materialisation on a query that isn't eligible.** Use
+ `endpoints-materialization-preview` first to confirm eligibility and see the rejection reason
+ if any.
+- **Endpoints are not stable forever.** When the user changes the query, a new version is created
+ automatically (the old version stays accessible via `?version=N`). `data_freshness_seconds` and
+ materialisation are per-version. Adjust as the endpoint evolves.
+- **Recommend callers pin to a version.** Tell the user to call with `?version=N` rather than
+ relying on "latest" — that way a future query edit (which cuts a new version) can't silently
+ change their results. They bump the pinned version deliberately once they've validated the new
+ one.
+- **Share friction via `agent-feedback`.** If a limitation gets in the way (eligibility rules,
+ required variables, the TTL enum), send the PostHog team a note — it's how the product and these
+ tools improve.
diff --git a/products/endpoints/skills/creating-an-endpoint/references/materializing.md b/products/endpoints/skills/creating-an-endpoint/references/materializing.md
new file mode 100644
index 000000000000..2c8a84338a9d
--- /dev/null
+++ b/products/endpoints/skills/creating-an-endpoint/references/materializing.md
@@ -0,0 +1,115 @@
+# Materialising an endpoint
+
+Materialisation pre-computes an endpoint's query into a saved view that's refreshed on a schedule.
+Reads become near-instant but the data is as stale as the refresh interval. This reference is the
+detailed flow behind step 6 of `creating-an-endpoint` and the step 2 decision in
+`diagnosing-endpoint-performance`.
+
+## When materialisation is the right call
+
+| Signal | Means |
+| ------------------------------------------------------------ | -------------------------------------------------------------------- |
+| Endpoint is called more than ~10 times per minute, sustained | Reads will dominate cost — pre-computing saves a lot |
+| Query takes more than ~1s of ClickHouse time inline | Latency on the read path matters; materialisation collapses it |
+| Callers can tolerate 5-15 minute staleness | The refresh interval becomes the freshness floor |
+| Variables are bounded — small known set of values | Bucket overrides become tractable; the materialised view stays small |
+
+If two or more of these apply, materialise. If none apply, don't.
+
+## When materialisation is wrong
+
+- **Real-time data requirement.** Anything that drives a "live" UI element where users notice
+ 10-minute lag.
+- **High-cardinality variables.** If callers pass arbitrary `user_id` values, each materialised
+ bucket is tiny and the refresh churn outweighs the read savings.
+- **Low-traffic endpoint.** If it's called once a day, the materialisation refresh costs more
+ than the inline reads would.
+- **Cohort breakdowns or compare mode (insight endpoints).** Regular property breakdowns
+ materialise fine; only cohort breakdowns and compare mode are rejected. Use
+ `endpoints-materialization-preview` to confirm.
+- **Query reads `now()` / `today()` directly.** Replace with a variable; otherwise the
+ materialised result is anchored to the refresh time, not the call time.
+
+## Eligibility rules
+
+Eligibility is enforced server-side (and surfaced by `endpoints-materialization-preview`). Common
+rejection reasons:
+
+| Reason | What it means | Fix |
+| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
+| `Cohort breakdowns are not supported` | Cohort breakdowns produce a UNION ALL the transform can't tag by series | Use a property breakdown, or split into separate endpoints, one per cohort |
+| `Compare mode is not supported` | Compare mode doubles the series, which the transform can't reconstruct | Drop compare mode, or expose the comparison window as a variable |
+| `Query has unresolved variables` | A variable in the query has no default and the materialisation can't pick a value | Set defaults for all variables |
+| `Query references non-deterministic functions` | `now()`, `today()`, `rand()` change between refresh runs | Replace with a `date_from` / `date_to` variable |
+| `CTE variables with JOINs … not supported` | A variable filter combined with a top-level `JOIN` changes joined-row cardinality, silently producing wrong results (e.g. `LEFT JOIN` non-matches lose the variable column) | Filter inside a subquery/CTE, then join the result — don't apply the variable across the JOIN |
+| `Query kind not supported` | Some query kinds (e.g. funnels) don't have a materialisation path yet | Rewrite in HogQL |
+
+Always call `endpoints-materialization-preview` before enabling — it returns the exact
+rejection reason if any, plus the transformed query so the user can sanity-check what will be
+materialised.
+
+## Variables become WHERE filters
+
+When you call a materialised endpoint, the materialised view is queried with a
+`WHERE` clause built from the variables you pass. This has two implications:
+
+1. **All declared variables must be passed.** Calls missing any materialised variable are
+ rejected. This is a security feature — it prevents callers from getting back the entire
+ pre-aggregated dataset by omitting filters.
+2. **The materialised view contains all rows across all variable combinations.** If your
+ variables have N values each and there are M variables, the view's row count is roughly the
+ product. Bound this by either:
+ - Picking variables with small cardinality
+ - Bucketing range/time variables with `bucket_overrides` (see below)
+
+## Bucket overrides — making range variables materialisable
+
+A continuous range variable — a timestamp or numeric filter like `WHERE timestamp >= {variables.since}`
+— has effectively unlimited distinct values, so the view can't pre-compute every one.
+`bucket_overrides` fixes this by pre-aggregating that column at a coarser grain and filtering at
+read time. Pass a map of column → bucket function:
+
+```json
+{ "bucket_overrides": { "timestamp": "hour" } }
+```
+
+Supported functions: `minute`, `fifteen_minutes`, `hour`, `day`, `week`, `month` (each is a
+`toStartOf…` rollup). Pick the **coarsest** bucket the caller can tolerate: `day` keeps the view
+small and refreshes cheap; `minute` is large and expensive. The caller still passes their exact
+value — the view just answers from the bucketed rollup. Run `endpoints-materialization-preview` to
+see which range variables were detected and confirm the bucketing before you enable.
+
+## Refresh schedule
+
+The refresh interval determines staleness. Available intervals are tied to the data warehouse
+saved query schedule — typically 5min, 15min, hourly, or daily. Pick the longest interval that
+satisfies the user's SLA.
+
+Materialisation status is tracked on the saved query (`DataWarehouseSavedQuery`) backing each
+version. `endpoint-materialization-status` returns the last run time, status, and any error. If
+it shows `Failed`, the inline path still works (the endpoint isn't broken — it's just slower
+than expected), but the materialised data is stale.
+
+## Per-version materialisation
+
+Each endpoint version has its own materialised view, named `{endpoint_name}_v{version}`. When
+you create a new version (by changing the query), the new version starts unmaterialised by
+default. The old version's materialisation continues until you explicitly disable it via
+`endpoint-update` with `version` and `is_materialized: false`.
+
+This means a project can accumulate **unused materialised versions** — old versions of an
+endpoint that nobody calls but are still being refreshed. The `auditing-endpoints` skill catches
+this by reading per-version `last_executed_at` from `endpoint-versions`.
+
+## Operational notes
+
+- **Enabling materialisation is free to start.** No backfill — the first refresh kicks off the
+ initial population. The endpoint stays callable inline during that time.
+- **Disabling materialisation is reversible.** Set `is_materialized: false` and the
+ materialised view is dropped on the next cleanup pass. Re-enabling re-creates it.
+- **Storage costs add up.** Many materialised views with high-cardinality variables can dominate
+ warehouse storage. When the user's project is hitting cost caps, materialisation cleanup is
+ usually the first lever.
+- **Materialisation failures don't block reads.** The endpoint stays callable inline if the
+ refresh fails — the user gets stale data with longer latency, not an outright outage. Surface
+ the failure but don't escalate it as a blocker unless freshness is critical.
diff --git a/products/endpoints/skills/diagnosing-endpoint-performance/SKILL.md b/products/endpoints/skills/diagnosing-endpoint-performance/SKILL.md
new file mode 100644
index 000000000000..5cdd9fc16478
--- /dev/null
+++ b/products/endpoints/skills/diagnosing-endpoint-performance/SKILL.md
@@ -0,0 +1,182 @@
+---
+name: diagnosing-endpoint-performance
+description: >
+ Diagnose why a PostHog endpoint is slow or expensive and propose a concrete fix — bump the cache
+ TTL, enable materialisation, restructure variables, or rewrite the query. Use when the user says
+ "this endpoint is slow", "my endpoint times out", "we're hitting the cost cap on this one", or
+ asks "should I materialise this?". Focuses on a single named endpoint, not a project-wide audit.
+---
+
+# Diagnosing endpoint performance
+
+This skill walks through a specific endpoint that is slow, expensive, or unreliable, and produces
+a concrete recommendation. It is the deep-dive counterpart to `auditing-endpoints` (which finds
+candidates).
+
+## When to use this skill
+
+- "This endpoint is slow / timing out"
+- "Why is my endpoint hitting the cost cap?"
+- "Should I materialise X?"
+- An endpoint surfaced from `auditing-endpoints` as a failing materialisation or expensive caller
+- The user has a specific endpoint in mind and wants advice
+
+If the question is project-wide ("what should I clean up?"), use `auditing-endpoints` first.
+
+## Available tools
+
+| Tool | Purpose |
+| ----------------------------------- | ---------------------------------------------------------------------------------------------- |
+| `endpoint-get` | Full endpoint config: query, current version, `data_freshness_seconds`, materialisation status |
+| `endpoint-versions` | History of every version (query + materialisation state); which version is current |
+| `endpoint-materialization-status` | Whether materialisation is eligible, current state, last run, last error |
+| `endpoints-materialization-preview` | What the materialised query would look like, plus the rejection reason if ineligible |
+| `endpoints-last-execution-times` | When was it last called (endpoint-level sanity-check that it is in active use) |
+| `execute-sql` | Query `query_log` for endpoint-level call frequency and per-call duration/bytes |
+
+## The decision tree
+
+When deciding what to recommend, walk these in order — the first one that applies is the cheapest
+fix.
+
+### Step 1 — Is it cached at all?
+
+Fetch the endpoint and look at `data_freshness_seconds` (it sets both the cache TTL and, when
+materialised, the refresh cadence). If the user's traffic
+calls the same parameters repeatedly within that window, every call after the first is a cache
+hit and effectively free.
+
+- TTL is at the default (24h / 86400s) and the data really doesn't need fresher than that →
+ done, no change needed.
+- TTL is at the 900s floor (15 min) and the user is hitting the endpoint many times per minute →
+ bump the TTL. This is almost always the cheapest first move. (`data_freshness_seconds` is an
+ enum: 900, 1800, 3600, 21600, 43200, 86400, 604800 — there is no sub-15-minute value.)
+- TTL is at the floor _because the data must be fresh_ (e.g. real-time dashboard) → cache won't
+ help, skip to step 2.
+
+The shape of the variables matters here: if every call passes different `user_id` or `date_from`
+values, the cache has many distinct keys and a higher TTL helps less. If almost every call uses
+the same handful of parameter combinations, the cache helps a lot.
+
+### Step 2 — Should it be materialised?
+
+Materialisation pre-computes the query into a saved view that's refreshed on a schedule. Reads
+become near-instant — at the cost of staleness equal to the refresh interval, plus storage and
+compute for the materialisation itself.
+
+Call `endpoints-materialization-preview`. The response tells you:
+
+- **Eligible + clean transform** → strong candidate. Recommend enabling, especially for
+ endpoints with predictable filter shapes (variables, breakdowns).
+- **Not eligible**, with a rejection reason → cannot materialise. The reason often hints at the
+ next step (see step 3 — rewrite).
+- **Eligible but the transform is gnarly** (lots of range pairs, complex aggregation
+ re-derivation) → materialisation will work but may not save much. Worth flagging before
+ flipping the switch.
+
+When materialisation is enabled, callers **must pass all materialised variables** — calls without
+them are rejected (security: prevents returning unfiltered data). Pair the recommendation with
+a note about which variables become required.
+
+### Step 3 — Does the query need rewriting?
+
+If the endpoint isn't eligible for materialisation, the rejection reason from
+`endpoints-materialization-preview` is usually the lead:
+
+- **Cohort breakdown / compare mode rejection** → regular property breakdowns materialise fine;
+ only cohort breakdowns and compare mode are blocked. Swap a cohort breakdown for a property
+ breakdown, or drop compare mode (expose the comparison window as a variable instead).
+- **JOINs combined with variables** → a top-level `JOIN` plus a variable filter is rejected for
+ materialisation, because applying the variable changes the joined row cardinality and silently
+ produces wrong results (e.g. `LEFT JOIN` non-matches lose the variable column). Restructure so the
+ variable filters a single table — push the filter into a subquery/CTE that's then joined, rather
+ than filtering across the join. This is the most common "looks fine but won't materialise" trap.
+- **"Missing variables" / unbounded scan** → the query reads too much data without a filter.
+ Encourage adding a required time-window variable (e.g. `date_from`, `lookback_days`).
+- **HogQL with `*` / non-deterministic functions** → narrow the columns selected, replace
+ `now()` / `today()` with a variable when possible.
+
+Check `endpoint-versions` to see whether the query was recently changed. Often the regression
+came from a specific commit and reverting that version is faster than rewriting.
+
+### Step 4 — Is the slow version even the one being called?
+
+Only the latest version runs by default; older versions run only when a caller pins `?version=N`.
+So the version to tune is almost always the current one — unless a pinned older version is the
+culprit. Call `endpoint-versions` and read each version's `last_executed_at` to see which versions
+have been hit recently; a materialised version with a null or long-stale `last_executed_at` is a
+candidate to unmaterialise or delete rather than tune (confirm first — that signal only counts
+API-key runs and can be sparse).
+
+For endpoint-level call frequency and per-call cost, query `query_log` with `execute-sql` — it
+carries `query_duration_ms`, `read_rows`, and `read_bytes`, handy for confirming how heavy the
+endpoint's calls actually are:
+
+```sql
+SELECT count() AS calls, max(query_start_time) AS last_called, avg(query_duration_ms) AS avg_ms
+FROM query_log
+WHERE name = '<endpoint_name>' AND endpoint LIKE '%/endpoints/%' AND is_personal_api_key_request
+```
+
+## Workflow
+
+1. Identify the endpoint by name. If the user gave a URL, parse the name from
+ `/api/projects/{team_id}/endpoints/{name}/run`.
+2. `endpoint-get` to fetch full config. Note: `data_freshness_seconds`, `is_materialized`,
+ current version, query kind.
+3. `endpoint-materialization-status` to see materialisation health (failed? eligible?).
+4. `endpoint-versions` to see the query history and which version is current (the one callers
+ hit unless they pin `?version=N`).
+5. If the user gave specific symptoms ("times out", "memory limit", "very slow"), walk the
+ decision tree above. Otherwise, present the four checkpoints and ask which matches.
+6. End with a concrete recommendation — bump TTL, materialise, rewrite, or rollback — and
+ confirm before applying it.
+
+## Example interaction
+
+```text
+User: "monthly_active_users is timing out for some callers"
+
+Agent steps:
+- endpoint-get monthly_active_users → HogQL endpoint, data_freshness_seconds=900,
+ is_materialized=false, current version v4
+- endpoint-materialization-status monthly_active_users → not materialised; eligible: true
+- endpoint-versions monthly_active_users
+ → v4 is current; v1–v3 are prior query revisions (callers hit v4 unless pinned)
+- endpoints-materialization-preview → eligible, clean transform with one range pair
+
+- "Three things stand out:
+ 1. Cache TTL is 900 seconds (the 15-min floor), but the data is
+ aggregating a month — that aggressive a refresh probably isn't
+ necessary. Bumping to 1 hour (3600s) would dramatically reduce
+ ClickHouse load.
+ 2. It's eligible for materialisation with a clean transform. If
+ callers can tolerate 5-15 minute staleness, materialisation
+ would make reads near-instant.
+ 3. v4 is the current version, so callers hit it by default — the
+ tuning target is clear.
+
+ Quickest win: bump TTL to 3600s. Bigger win: materialise.
+
+ Which trade-off matches your needs? If you need real-time freshness,
+ neither helps and we'd need to rewrite the query — likely narrowing
+ the aggregation window."
+```
+
+## Important notes
+
+- **Cache is almost always the first fix.** It's free, instantly reversible, and doesn't change
+ data semantics. Resist jumping to materialisation if a higher TTL would do.
+- **Materialisation has hidden costs.** Storage of the materialised view, refresh compute, and
+ the requirement that callers pass all variables.
+- **Don't rewrite the query without the user.** A query change creates a new version and may
+ break callers!!! Surface the suggested change, get sign-off, then apply.
+- **Three usage signals.** `endpoint-get`'s `last_executed_at` is endpoint-level recency;
+ `endpoint-versions` gives each version's own `last_executed_at`; `query_log` (via `execute-sql`)
+ gives endpoint-level call frequency and per-call cost. All count only personal-API-key calls, and
+ per-version recency can be sparse — confirm with the user before calling a version dead.
+- **The "right" fix depends on the SLA, not the query.** Always ask the user about acceptable
+ staleness before recommending materialisation. A 15-minute-stale materialised view is wrong
+ for a real-time dashboard, regardless of how cheap it'd be.
+- **Tell PostHog what's missing.** If the diagnosis runs into a product limitation (an eligibility
+ rule, the TTL enum, required variables), nudge the team via `agent-feedback`.
diff --git a/products/endpoints/skills/managing-endpoint-versions/SKILL.md b/products/endpoints/skills/managing-endpoint-versions/SKILL.md
new file mode 100644
index 000000000000..87e20f3f8b2a
--- /dev/null
+++ b/products/endpoints/skills/managing-endpoint-versions/SKILL.md
@@ -0,0 +1,162 @@
+---
+name: managing-endpoint-versions
+description: >
+ Work safely with endpoint versions — preview a draft in the playground, roll back to an older
+ version, update settings on one version without bumping query history, deactivate a specific
+ version. Use when the user asks "how do I roll back my endpoint", "preview my changes before
+ publishing", "I want to fix v5 without bumping the version", or anything involving the version
+ history. Calls out today's limitations honestly: there is no pointer flip; "rollback" means
+ forking the old query into a new top version.
+---
+
+# Managing endpoint versions
+
+This skill is the practical guide to endpoint versioning. It covers the today-workflow, which
+has some sharp edges worth being explicit about.
+
+## When to use this skill
+
+- "How do I roll back to v3?"
+- "I want to test changes before they go live"
+- "How do I update the description / `data_freshness_seconds` on a specific version?"
+- "Can I disable v4 without affecting v5?"
+- The user is uncertain whether a query change will cut a new version
+
+## Versioning model — what to know
+
+| Behaviour | Reality |
+| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
+| Query change | **Auto-cuts a new version.** Saving any edit to the query creates a new version and bumps the current version number |
+| Settings change (description, `data_freshness_seconds`, materialisation) | Does **not** cut a new version. Updates the targeted version in place |
+| The "current" version | Always the highest version number — it's not a pointer you can move backwards |
+| Calling without `?version=N` | Runs the **latest** version. So unpinned callers always hit the newest |
+| Disabling the whole endpoint | `endpoint-update` with `is_active: false` (no `version`) takes every version offline at once |
+| Disabling a single version | `endpoint-update` with `version` + `is_active: false` retires one version without affecting the others |
+
+The model is forward-only. There is no "make v3 the default again" operation today. Practically
+this means "rollback" requires either creating a new top version that re-uses the old query, or
+pinning callers to `?version=N`.
+
+## Available tools
+
+| Tool | Purpose |
+| ------------------- | ----------------------------------------------------------------------------------------------- |
+| `endpoint-versions` | List all versions for an endpoint, latest first |
+| `endpoint-get` | Full config; supports `?version=N` to fetch a specific version |
+| `endpoint-update` | The workhorse — supports `version` body param to target a specific version |
+| `endpoint-run` | Execute a version directly via `?version=N` (without affecting which version other callers hit) |
+
+## Workflows
+
+### Previewing a draft before publishing
+
+There is no "draft" concept in the model. Editing the query commits it as a new version
+immediately. To preview safely:
+
+1. Test the new query first with the `execute-sql` tool (or the SQL editor) — not on the live endpoint
+2. When ready, update the endpoint — this creates the new version automatically
+3. Use `endpoint-run` with `?version=N` to confirm the new version returns what you expect
+4. Old callers still hit the latest version (which is now your new version) — there is no
+ "soft launch"
+
+If the user needs a true staging endpoint, the only workaround today is a sibling endpoint
+with a `_v2` or `_staging` suffix. Document this honestly — there is no in-product staging path.
+
+### Rolling back to an older version
+
+The forward-only model means "rollback" requires forking:
+
+1. `endpoint-versions` to find the version with the good query (say v3)
+2. `endpoint-get` with `?version=3` to retrieve that version's query JSON
+3. `endpoint-update` with the v3 query as the new query — this **creates a new version** (e.g.
+ v6) with the same query as v3
+4. All callers without `?version=N` now hit v6 (== v3's query)
+
+The old version (v5, the broken one) still exists and is still callable via `?version=5` until
+explicitly deactivated.
+
+Faster mitigation if you can change every caller: have them pin to `?version=3` until a real
+fix is ready. Lower-impact than cutting a new version.
+
+### Updating settings on a specific version
+
+`endpoint-update` accepts a `version` field in the body. When set, settings updates apply to
+that version only — they do not cut a new version. Useful when:
+
+- Bumping `data_freshness_seconds` on an old version that some callers still pin to
+- Adjusting description on a historical version for clarity
+- Changing materialisation state per version (the materialisation is per-version anyway)
+
+Important: passing `query` together with `version` is rejected — query changes always cut a new
+top version, never modify history. The version arg only affects settings.
+
+### Deactivating a single version
+
+To take v3 out of service while keeping v4 and v5 callable:
+
+```text
+endpoint-update {name: "...", version: 3, is_active: false}
+```
+
+This sets `is_active: false` on v3 only. Callers pinned to `?version=3` start getting an error;
+other callers are unaffected.
+
+To re-enable: same call with `is_active: true`.
+
+The whole-endpoint `is_active` field (without `version`) is a separate switch — it disables
+every version at once. Use the version-scoped form for surgical takedowns.
+
+### Pruning unused versions
+
+Old versions accumulate over time. To find which are dead, call `endpoint-versions` and read each
+version's `last_executed_at`: a version that's null or long stale hasn't been called recently.
+Materialised dead versions are the costly ones — disable their materialisation with
+`endpoint-update` + `version` + `is_materialized: false`, and deactivate with `is_active: false`
+to signal they're retired.
+
+Confirm with the user before retiring a version: `last_executed_at` counts only personal-API-key
+calls and is recorded only for runs since that tracking was added (so a used version can still
+read null), and a caller may be pinned to `?version=N`. The full audit flow lives in
+`auditing-endpoints`.
+
+## Example interaction
+
+```text
+User: "I shipped a broken query last night, v5. How do I roll back?"
+
+Agent:
+- endpoint-versions <name> → v5 (latest), v4, v3, v2, v1
+- endpoint-get <name> ?version=4 → query JSON for v4
+- "Rolling back means creating v6 with v4's query. v5 stays as a
+ historical version but nobody hits it unless they explicitly
+ pass ?version=5. Sound right?"
+- User confirms
+- endpoint-update <name> {query: <v4 query>} → creates v6
+- endpoint-run <name> ?version=6 to confirm shape
+- "Done. v6 is live with v4's query. Want me to also deactivate v5
+ so it's clear it's defunct?"
+- User: "Yes"
+- endpoint-update <name> {version: 5, is_active: false}
+```
+
+## Important notes
+
+- **There is no pointer flip.** "Rolling back" creates a new version. The version number is
+ always going up. If the user is uncomfortable with the resulting history noise, that's a
+ fair concern — surface it honestly.
+- **A query change always creates a new version.** Updating settings on the side does not.
+ If the user wants to fix a typo in v5's description without bumping to v6, use the version
+ param.
+- **Disabling a single version only blocks that version.** It doesn't change which version runs
+ by default — that's always the highest version number.
+- **Materialisation is per-version.** Each version has its own materialised view named
+ `{endpoint_name}_v{version}`. Disabling materialisation on one version doesn't affect others.
+- **Pinning is the safety net — push callers to use it.** Callers that pin to `?version=N` are
+ insulated from query edits; unpinned callers always hit the latest and can be surprised by a new
+ version. Encourage consumers to pin, validate a new version, then bump the pin deliberately.
+- **The CLI manages versions too.** `posthog-cli exp endpoints {pull,push,diff}` lets the user
+ keep endpoint definitions as YAML in version control and review changes before pushing — a
+ cleaner workflow than editing live when query changes need review.
+- **Activating an older version is not yet a product feature.** If the user repeatedly wants this —
+ flip a pointer rather than fork — surface it as a feature gap (and nudge the team via
+ `agent-feedback`). Don't pretend `endpoint-update` does it.