# Saved queries

A saved query is a question you have asked once and want answered the same way every time: a
[query spec](query-spec.md) pinned as a **version**, with the **typed variables** it needs, a record
of every run, and, if an organization owner chooses, a REST endpoint an outside system can call.
People run them from the dashboard; agents run them as `saved_query_run`; a team can keep the
approved version in `bucker.yml`.

## What a version is

A version is immutable. Changing anything is a new version.

| Field | Meaning |
| --- | --- |
| `spec` | A strict query spec v1. A saved query reads `spans`, `logs`, `events` or `metrics`; a dataset that needs `analytics:read` or `cost:read` is refused until those datasets exist. |
| `variables` | `[{ name, type, required: true, enum?, min?, max? }]` with type `string`, `number` or `string_list`. **Every variable is required**; there is no default. |
| `specDigest`, `compiledDigest` | SHA-256 of the canonical spec and of what it compiles to. Computed by Bucker from the spec; a caller cannot state one. |
| `outputSchema` | The columns a row has, derived from the spec. A group column is customer text and is marked so. |
| `tokenCeiling`, `freshnessSeconds` | What an agent calling the version is promised: at most this many tokens, data at most this old. |
| `author`, `sponsor` | Who proposed it, and the person an agent acted for. Read from Bucker's record of the requester, never from the request. |

A query has a **state** (`draft`, `shared`, `disabled`), a **shared version** (the one that runs by
default), a **published version** (the one the external endpoint serves), a `certified` flag
(reserved for WH-18) and an archive flag.

## Variables are bound, never interpolated

A filter names a variable (`{ "key": "service", "op": "eq", "var": "service" }`); a run supplies its
value, and the printer binds it as a **parameter**. An injection through a value is one bound
parameter, shown in the run's `compiled.params`; the statement text never holds it. A value outside
its declared `enum`, `min` or `max` is a 422 that names the variable. A variable that names the
tenant (`org`, `org_id`, `project`, `project_id`, `tenant`, `workspace`, and spellings of them) is
refused when the version is proposed, and a run that supplies a name the version does not declare is
refused: the organization and the project always come from the call, never from a value.

## Drafts, sharing and approval

| You want | Call | What happens |
| --- | --- | --- |
| Try a query out | `saved_query_propose` with `visibility: draft` | Stored **at once** (`saved_query.draft`). Private to you; runs charge your own scan budget; the operation's time-box ends after 14 days (the registry's default) and archives the query if it is still exactly as that draft left it; a later draft or an approved shared version supersedes that, and an unshared draft is in any case hidden on read after 30 days. Only on a query nobody has shared. |
| Share a query | `visibility: shared` | `saved_query.create` (first version) or `.update` (a new one). **Always pending approval**, whatever the organization's policy says. Nothing is live until a person approves the plan with its digests. |
| Re-pin an earlier version, enable, disable, withdraw the endpoint, archive | `saved_queries_update` | The act is derived from what would change: `saved_query.update`, `.disable`, `.unpublish`, `.archive`. Disabling a query something reads is SENSITIVE. |
| Undo a new shared version | `operation_revert` | Re-pins the previous shared version. |

Applying is a compare-and-swap on the query's revision: an approval given to revision N is never
spent on revision N+1, including after an edit through any other door. A draft cannot be stored on a
query that is already shared: a change to a live query is a proposal for a new shared version.

**Publishing, query tokens and deletion are a person's.** `saved_query.publish`, `query_token.create`
and `saved_query.delete` are human-only: no agent, no OAuth client and no delegated credential reaches
them, and the governed engine refuses them too. Publishing and minting need `org:admin`.

## Slugs and tool names

A slug is 2 to 60 lower-case letters, digits and hyphens. Its per-version tool name is `sq_<slug>`
(hyphens become underscores), generated from the slug alone: the free-text name and description
travel as scrubbed data and never become part of a name an agent calls. A slug is refused when its
tool name would exceed 40 characters, contains a forbidden word as a whole segment (`delete`,
`publish`, `launch`, `ship`, `erase`, `purge`, `widen`) or as a fragment (`approve`, `merge`,
`deploy`, `buy`, `purchase`, `lift`), or starts with `view-` (the prefix a converted Explore view
carries). The `sq_<slug>` aliases themselves are not served yet.

## Explore views

A saved view of surface `explore` is shown as a saved query with one version (its question as a
spec) and the slug `view-<id>`. Nothing is written or moved: the view keeps working exactly as before,
and a private view is still its owner's alone.

## Running

| Door | Who | Notes |
| --- | --- | --- |
| `saved_query_run` (MCP) | Any caller with `event:read` on the project | Up to 200 rows, a cursor, the evidence block, the scan class. |
| `POST …/saved-queries/{slug}/run` | A signed-in caller with `event:read` | The same function. |
| `POST …/saved-queries/{slug}/versions/{v}/run` | A **query token** | The external endpoint. Published versions only. |

Every run is a query-log row of surface `saved_query` carrying the saved query's id and the version;
`GET …/saved-queries/{slug}/runs` lists them (your own, unless you can read the organization's log).
A version nobody has shared runs for its author only; a disabled or archived query refuses every run.
Rows are telemetry: group labels are cleaned and listed as untrusted, and an agent receives them
fenced. So are the words the query's author wrote that a run hands back: the query's name and the
bound values in the compiled statement (the spec's own filter values among them).

## The external endpoint and query tokens

An organization owner publishes the **current shared version** (`POST …/versions/{v}/publish`).
A version that needs issue data (the `events` dataset) or a person-level key cannot be published: a
query token carries neither. `GET …/versions/{v}/openapi.json` describes the run route, its typed
variables as a required body and the shape of a row.

A **query token** (`bkr_qt_…`) is minted by a person (`POST …/query-tokens`, owner or admin, behind the
password step-up):

- it pins **at most 20** published versions of one project and lives **at most 90 days**;
- it runs **60 times a minute** (counted from the log, so it holds across machines);
- it is shown **once**, stored only as a SHA-256 digest, and backed by a service principal with no
  membership;
- it is accepted by exactly two routes, the run route and `openapi.json`. Everywhere else it is an
  invalid access token; the RFC 8693 exchange and the MCP server refuse it.

Revoking is idempotent and needs only an owner or admin.

## In `bucker.yml`

```yaml
version: 2
projects:
  checkout:
    savedQueries:
      - slug: checkout-errors
        name: Checkout errors by service
        version:
          spec: { v: 1, dataset: spans, select: [{ fn: count, as: n_spans }],
                  where: [{ key: service, op: eq, var: service }],
                  variables: { service: { type: string, required: true } } }
          variables: [{ name: service, type: string, required: true }]
```

Applying a file **proposes** the version through the governed operation, which asks for approval, so
nothing a file says is live until an approver says yes. A file never deletes a query, never exports a
private draft, and `plan` after `export` is `unchanged`.

## Not yet

Materialization (WH-17), suggestions and certification (WH-18), alert rules reading a query (MON-32)
and the `sq_<slug>` per-version tools are later work; the tools that would carry them answer
`not_available` rather than reading as empty.
