# Capture filters, body limits and retention

What the proxy records in HTTP history, how much body data it keeps in
memory and on disk, and how stored history is pruned. Traffic is never
changed by these settings: an exchange that is not recorded is still
relayed to the client.

Code: `backend/app/core/capture/` (rules, preset, filter),
`backend/app/core/proxy/capture_budget.py` (memory budget),
`backend/app/runtime/capture.py` and `retention.py` (live copies and the
scheduled task), `backend/app/services/capture/` (settings, prune
planning, statistics), `backend/app/repositories/flow_retention.py`,
`backend/app/api/v1/capture.py`, `backend/app/mcp/tools/capture.py`.

## Capture settings (`proxy.capture`)

`GET /api/v1/proxy/capture` returns the settings in effect, the static
preset and counters; `PUT` replaces them as a whole (fields left out take
their default).

| Field | Default | Meaning |
| --- | --- | --- |
| `in_scope_only` | `false` | Record only hosts in the capture vault's scope |
| `exclude_static` | `false` | Skip images, fonts, style sheets, audio and video (preset below) |
| `rules` | `[]` | Include / exclude rules, at most 200 |
| `max_body_bytes` | `null` = `PROXY_BODY_LIMIT` (512 KiB) | Bytes kept per request or response body; 1 KiB to 64 MiB |
| `memory_budget_bytes` | `null` = 128 MiB | Bytes all captured bodies in flight may hold together; 1 MiB to 4 GiB, at least `max_body_bytes` |
| `ws_max_frames` | `null` = 10,000 | WebSocket messages recorded per session; 1 to 1,000,000 ([WebSocket sessions](websocket.md)) |
| `ws_max_bytes` | `null` = 32 MiB | WebSocket payload bytes stored per session; 0 to 4 GiB |

Checks run in order and the first that rejects gives the skip reason:
`out_of_scope`, `static`, `excluded` (an enabled exclude rule matched),
`not_included` (enabled include rules exist and none matched). An
exchange held in intercept is always recorded. Replayed flows are always
recorded; HAR import has its own `in_scope_only` option.

### Rules

A rule is `{id?, enabled, action, field, operator, value, negate, note}`,
validated like an intercept rule
([Proxy protocol support](protocols.md#intercept)); a bad rule is
refused with 422 and `details: {index, field}`.

| | Values |
| --- | --- |
| `action` | `include`, `exclude` |
| `field` | `host`, `method`, `path` (no query), `extension` (last path segment, no dot), `mime` (response media type; absent without a response) |
| `operator` | `equals`, `contains`, `starts_with`, `ends_with`, `wildcard` (whole value, case-insensitive), `regex` (searched anywhere), `one_of` (comma-separated exact values, e.g. `png, jpg`) |

Host, method, extension and mime ignore case; path does not, except with
`wildcard`. Values are at most 512 characters; a regex must compile, sees
at most 64 KiB of a value and each search stops after 50 ms (counted as no
match and logged once per rule).

### Static preset

Extensions: `png jpg jpeg gif webp avif bmp ico svg tif tiff heic woff
woff2 ttf otf eot css mp4 webm ogg ogv mp3 wav flac aac m4a mov avi mkv`.
Media types: `image/*`, `font/*`, `audio/*`, `video/*`, `text/css` and the
legacy font types. `GET /proxy/capture` lists them in `static_preset`.

### Counters

`counters` in `GET /proxy/capture`: `skipped` and `skipped_by_reason`
(not recorded by the filter), `dropped` (write queue full),
`buffered_bytes` (body bytes in memory now), `budget_truncations`. They
count since the backend started and are not persisted. `GET
/proxy/status` carries `skipped`; the vault statistics carry the
per-vault numbers.

## Bounded buffering

Each captured body keeps at most `max_body_bytes`; the rest is relayed
but not stored, and `request_truncated` / `response_truncated` are set
with the full size in `request_size` / `response_size`. The limit is read
for every new exchange, so a change applies at once; it is also the
largest body intercept can hold and edit, and it applies to replay and
HAR import.

All captured bodies in flight share `memory_budget_bytes`. A body that
cannot reserve more stops keeping data for good (the stored bytes are
always a clean prefix) and is flagged truncated; a truncated body shorter
than `max_body_bytes` was cut by the budget. Reservations return when the
flow is stored, skipped or dropped, and when a lost buffer is garbage
collected. The budget bounds Phantom's copies only, not the relay's own
transfer buffers.

## Retention (`proxy.retention`)

One global policy; every limit applies to each vault's history
separately. `GET /api/v1/proxy/retention` returns `{policy, last_run}`;
`PUT` replaces the policy.

| Field | Default | Meaning |
| --- | --- | --- |
| `enabled` | `false` | Enforce on a schedule |
| `interval_minutes` | `10` | Minutes between runs (1 to 1440) |
| `max_flows` | `null` | Flows kept per vault |
| `max_body_bytes` | `null` | Stored request + response body bytes kept per vault |
| `max_age_days` | `null` | Flows recorded longer ago are deleted |
| `include_annotated` | `false` | Annotated flows may be deleted too |

Limits apply in order, each to what the previous left, oldest first:
age (by recording time; imported flows keep their original time, so an
old HAR import is pruned by age at once), then count (by id), then bytes
(by id). Flows with a bookmark, note or tag count towards the limits but
are kept unless `include_annotated`, so a vault can stay above a limit.
Deleted flows lose their annotations and tag links in the same
transaction; tags stay.

**Scheduled.** While enabled with at least one limit, a background task
prunes every vault each interval, each vault in its own transaction.
Saving a policy restarts the interval. `last_run` reports `{at, vaults,
deleted, bytes, error}`.

**On demand.** `POST /api/v1/vaults/{vault_id}/flows/prune` with
`{dry_run, limits?}` (the saved limits when `limits` is omitted, enabled
or not). The result is the same for a dry run and the real run:

```json
{"vault_id": 1, "dry_run": true, "deleted": 120, "bytes": 5242880,
 "by_reason": {"age": 100, "count": 20, "bytes": 0}, "annotated_kept": 3,
 "remaining_flows": 400, "remaining_bytes": 9437184, "limits": {...}}
```

A real prune that deleted flows emits one `proxy.pruned` event
`{vault_id, deleted, bytes}`; dry runs and empty prunes emit nothing.

## Storage statistics

`GET /api/v1/vaults/{vault_id}/flows/stats`: `flows`, `body_bytes`,
`request_body_bytes`, `response_body_bytes`, `frame_bytes`,
`websocket_sessions`, `oldest_at`, `newest_at`, `by_source` (`proxy`,
`replay`, `import`), `annotated`, `skipped_by_filter` and
`skipped_by_reason` (since start). `body_bytes` includes WebSocket frame
payload bytes, and so does the `max_body_bytes` retention limit: a
session's frames count as its flow's stored bytes and are pruned with it.

## Body store

Request and response bodies are not kept in the flow rows. Each body is
stored once per content in a table of its own, keyed by its SHA-256,
and a flow keeps only the hashes of its two bodies. The same script,
image or answer captured many times is stored once, and listing History
reads flow rows without loading any body. Body search (`body:`) looks
through the stored bodies as before. A body shared by several flows
counts toward each of them in the statistics above, since pruning one
flow does not free it while others still use it.

Bodies that no flow refers to any more (after a prune, a delete or a
deleted vault) are removed with the flows that held them.

| Route | Does |
|---|---|
| `GET /api/v1/proxy/bodies` | `bodies` (distinct), `bytes`, `references` (flow sides pointing at a body) and `orphans` |
| `POST /api/v1/proxy/bodies/verify` | Recompute every body's SHA-256: `checked`, `broken` (hashes whose content no longer matches) and `orphans_removed` |

In the interface: Proxy settings, Storage, **Verify integrity**.

## Agents (MCP)

| Tool | Behaviour |
| --- | --- |
| `proxy_capture_get` | Capture settings and counters |
| `proxy_retention_get` | Policy and last run |
| `flow_stats` | Vault statistics |
| `flow_prune` | Preview only: `dry_run` defaults to true; `dry_run=false` fails with `permission_denied` (`details: {setting: "proxy.retention"}`) |

Agents cannot change the capture settings or the retention policy (no
tools; the policy refuses agent calls in the service), and replay or
intercept edits to the workstation's own API on this machine (which
includes `/proxy/retention`, `/vaults/{id}/flows/prune` and
`/vaults/{id}/flows/delete`) are refused, like the MCP endpoint. Deleting history this way stays a
user decision, as with the redaction policies. `flow_clear` and
`flow_delete` are refused for agents for the same reason.

## Interface

Proxy → Settings has three cards (`frontend/src/components/proxy/settings/capture/`,
state in `stores/capture.ts`, helpers in `utils/captureLimits.ts`):

- **What gets recorded**: switches for in-scope only and the static
  preset (saved at once; "What it covers" lists the preset's extensions
  and media types), the capture rules written as sentences in the same
  look as intercept rules ("Skip exchanges where Extension is one of
  mp4, webm"), saved as one list with Discard, and live counters of what
  was relayed but not recorded, by reason. Skipped traffic emits no
  event, so the counters are polled every 5 s while the page is open.
- **Memory**: the per-body limit and the in-flight budget as a number
  with a unit (KiB, MiB, GiB), checked against the backend ranges before
  saving; what is held now and how many bodies the budget cut. "Use
  defaults" sends `null` for both, so the settings follow the defaults
  again; values equal to a default are always sent as `null`.
- **Storage and retention**: the active vault's statistics (flows by
  source, stored bodies, span, annotated), the policy on a draft (each
  limit switched on or off, include annotated, automatic cleanup and its
  interval) saved with Save policy, "Preview cleanup" (a dry run with the
  limits being edited, before or without saving them) and "Clean up now"
  after an in-place confirmation naming how many flows go, and the last
  scheduled run. Statistics refresh on `proxy.pruned`, `proxy.imported`
  and new traffic; the history reloads on `proxy.pruned`.
