# Capture rules

Capture rules let a project make its SDKs collect **less**, without a redeploy, and make sure nothing
can make them collect more except a person. They are one signed document per project, served to every
SDK, applied on top of what your code configured, and changed through one governed path.

```
        code configuration  ───────────────►  what the SDK collects
                                  ▲
 signed document (this page) ─────┘   can only remove, mask, lower or stop; never add, raise or restore
```

## The document

`bucker.capture-rules/1`. Every list holds at most 200 entries of at most 200 characters, with no
control characters. Everything in it is a name or a pattern the SDK compares against; nothing is code.

| Section | Fields | Written by |
| --- | --- | --- |
| `sampling` | `spans`, `logs`, `product.events`, `product.pageviews`, `product.autocapture` (a keep-rate ceiling, 0 to 1), `sampleBy` (`trace`, `session`, `user`) | `capture_rules_update` |
| `drop` | `eventNames`, `loggers`, `spanOps`, `breadcrumbKinds` | `capture_rules_update` |
| `mask` | `propertyKeys`, `headerKeys`, `selectors` | `capture_rules_update` |
| `propagation` | `removeTargets` (hosts the SDK stops attaching trace headers to) | `capture_rules_update` |
| `runtime` | `denyEntries` (the runtime deny list), `exceptionCapture` (Exception Replay) | `capture_rules_update` (deny entries); Exception Replay's own governed change (the entry) |
| `identity` | `denylist` | the identity rules' own governed change |
| `replay` | the replay rules | the replay rules' own governed change |
| `windows` | scheduled capture windows | the capture windows' own governed change |

A document is `shadow` (stored and previewed, never served) or `live` (served). A new document lands as
a shadow draft, and going live is its own act, so a person reading the draft sees what will be served
before an SDK does.

### What counts as collecting less

Every route and tool that writes the document uses the same comparison to decide whether the new
version collects less than the old one. It compares what an SDK actually collects (a shadow draft
collects like the empty document):

- a lower or newly set ceiling, a larger set, a newly chosen `sampleBy` is a **tightening**;
- a higher ceiling, a removed entry, a ceiling dropped to "no ceiling", a changed `sampleBy` or a live
  document withdrawn is a **widening**.

A widening is only ever a person's act (`capture_rule.widen`, `org:admin`). The first document of a
project tightens against the empty document: the code's own configuration is the first ceiling, and
the SDK enforces it again when it applies a served document.

## What an agent can do

`capture_rules_update` (MCP) and `PUT /orgs/:org/projects/:project/capture-rules` (REST) take the
**desired state** of the sections to change, the version the caller read, the digest of a counted
preview and a reason. The act is derived from what the diff does, never from an argument:

| What the change does | Act | Class | Decision |
| --- | --- | --- | --- |
| a draft saved, never served | `capture_rule.create` | ELEVATED | ALLOW |
| masks added that nothing reads | `capture_masking.narrow` | ELEVATED | ALLOW |
| ... when a dependent reads a masked field, or a removed propagation host sent spans | `capture_sampling.narrow` | SENSITIVE | ASK |
| drops or propagation hosts added that name nothing stored in 7 days | `capture_rule.update` | ELEVATED | ALLOW |
| ... naming data the project stored in the last 7 days | `capture_rule.update` | SENSITIVE, silencing-class, 90-day TTL | ASK |
| a sampling ceiling set or lowered | `capture_sampling.narrow` | SENSITIVE, 90-day TTL | ASK |
| runtime deny entries added | `capture_denylist.narrow` | SENSITIVE | ASK |
| anything that collects more | `capture_rule.widen` | human-only | refused to an agent, a service account and an OAuth client |

The SENSITIVE branches may be answered ALLOW by an organization's own policy, **up to 10% of a
signal's items on any day**. A change that drops more than that, or whose share could not be measured,
is CRITICAL, which no ALLOW row reaches. An unmeasured share is treated as wide, never as zero.

When the 90-day TTL ends, Bucker does not undo anything by itself: it asks an `org:admin` to keep
the rule or restore the previous document.

### The counted preview

Before anything is applied the change is previewed over the last 7 days of the project's own data, a
day at a time, and each figure says how it was measured:

- a name matched against stored rows (a logger, a span op) is `exact`;
- a ceiling applied to a day's count is an `estimate`;
- a signal nothing counted (product events outside the core-event rollup) is `unmeasured`.

The preview also lists the dependents that read a masked field (alert rules, saved views, board
widgets) and counts spans that went to a propagation host the change removes. A change that would drop
spans or logs of **a trace that holds an error is refused with no digest**: an SDK never samples an
error away, and a plan that takes the evidence an investigation needs is not offered to an approver.

Previews are their own tool (`capture_rules_list` with `include: ["preview"]`) and route
(`POST .../capture-rules/preview`), never a flag on the write. Giving a `reason` with the preview also
records it as the planned change, and the write must follow that preview within 30 minutes.

### After the apply

The apply is one compare-and-swap on the document's version: a human edit through any other route
between the approval and the retry closes the request `TARGET_CHANGED` and spends nothing. The
verification signal is `event_volume` over 60 minutes against the preview. The stored inverse of every
narrowing is `capture_rule.widen`, which is human-only, so `operation_revert` is refused to an agent
and to every other principal: a person restores a version through the widen route.

## Widening, by a person

`POST /orgs/:org/projects/:project/capture-rules/widen` takes either new `changes` or a
`restoreVersion`, a reason, and optionally the revision the screen showed. It needs an `OWNER`
(`org:admin`) on their own dashboard session, writes the new version and its audit row
(`capture_rule.widen`, flagged `loosened: true`) in one transaction and alerts the organization's
owners afterwards. It refuses a change that does not widen and points at the governed route. It also
refuses a change that widens in one place and narrows in another (`MIXED_WIDEN_AND_NARROW`): anything
that collects less goes through `capture_rules_update`, with its preview, ask and TTL, so a restore that
would also narrow takes two steps. Withdrawing a live document (`state: "shadow"`) is a widening, and
from then on SDKs are served nothing until the document goes live again.

## How an SDK gets it

`GET /api/:projectId/sdk-config?sentry_key=...` is authenticated by the DSN key the SDK already ships.
The project comes from the key: a key used with another project's id is refused, and nothing in
the path, query or a body can name another project's document.

The response is the newest version, signed, when that version is **live**:

```json
{ "v": 1, "alg": "ES256", "keyId": "...", "payload": "<the exact string that was signed>", "signature": "<base64url r||s>" }
```

`payload` is a string. The server signs those bytes and a verifier checks the signature over the string
it received and only then parses it, so no language ever has to reproduce another's JSON number
formatting. The payload names `schema`, `projectId`, `version`, `keyId`, `issuedAt` and the document
without its lifecycle.

- 204 when the newest version is not live (no document, a draft, or a withdrawn document), or Bucker
  has no signing key for the region yet. An unsigned document is never served, and the route never
  reaches past a newer shadow version to an older live one: what is served is what every change is classified against.
- `ETag` is a digest of the payload (stable across reads, independent of the signature);
  `If-None-Match` answers 304. `Cache-Control: public, max-age=300`.
- The public half of the signing key is published at `/.well-known/bucker-sdk-config.json` as JWKs.
  There is one P-256 signing key per region, created and rotated by a person at Bucker; the private
  key is never logged or written out.

### What the SDK does with it

`@bucker/sdk-core/remote-config` (`remoteCaptureRules()`) and `bucker_sdk.remote_config.install()`:

1. fetch, verify against the embedded public key, and cache for an hour (the cached copy is verified
   again on every read);
2. **refuse** a document that is unsigned, signed by an unknown key, for another project, of a lower
   version than the one already applied (a replay), of the wrong shape, or that widens anything (a
   ceiling above 1). A refusal keeps the code's own configuration;
3. apply each section on top of the code: minimise rates, add drop entries, mask keys, header keys and
   selectors, remove propagation targets;
4. report the applied version on every envelope header as `config_version`.

It is inert by default: nothing is fetched until the integration is installed. **Bucker's SDKs do not
embed Bucker's public key yet** (it is added once the regional signing key exists), so today they
apply no served document at all and your code's own configuration is what runs. Errors in this path
never reach the application.

## Tenancy and trust

- Every statement that reads or writes a document opens with the project, resolved inside the
  caller's organization. Another organization's project is "not found" on every route and tool, and
  nothing of it is counted, listed, previewed or written.
- A cached copy of a served document is kept per organization, project, version and key id, so one
  project is never served another's.
- Every entry of the document and every dependent's name that an MCP tool returns is scrubbed for
  agents and listed in `trust.untrustedFields` with its class (`plan_echo`).
- `capture_rules_update` needs `capture:write`; it is listed only for a token that holds it.
