> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Test filters

> Speed up CI with test filters that run only the tests a pull request can affect with --changed-since, and start the tests the change most likely affects first.

With `--changed-since <ref>`, a test filter leaves out the tests the change
since that ref can't affect, and starts the files of the likeliest to fail first. The
decision filter asks a [decision model](https://e2e.com/docs/decision-models), such as Jev, about
each test. Without the flag, as on `main` and locally, every test runs.

<Video>
  <video src="/images/filters.mp4" aria-label="Two runs side by side. With --changed-since, the decision filter leaves out 25 of 27 tests and the run passes in 12 seconds. The full run is still going after 30 seconds." muted loop playsInline controls />

  With `--changed-since origin/main`, the decision filter leaves out 25 of 27 tests.
</Video>

## Add the decision filter

<CodeGroup>
```bash npm
npm install -D @e2e-dev/decision ai
```

```bash pnpm
pnpm add -D @e2e-dev/decision ai
```

```bash bun
bun add -d @e2e-dev/decision ai
```
</CodeGroup>

```ts title="e2e.config.ts"

export default {
  targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
  filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })],
} satisfies E2EConfig;
```

In CI, pass `--changed-since` on pull requests, and give the e2e step the
AI Gateway key:

```yaml title=".github/workflows/e2e.yml"
steps:
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
    with:
      fetch-depth: 0
  # ...
  - run: npx e2e run ${{ github.event_name == 'pull_request' && format('--changed-since origin/{0}', github.base_ref) || '' }}
    env:
      AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }}
```

Pass `--changed-since` only on `pull_request` events so pushes, merge
queues, and scheduled runs still run the full suite. Never use it on
`pull_request_target` (where untrusted fork diffs run alongside your
secrets). `fetch-depth: 0` gives git the base branch history it needs to
compute the merge base; without it, the run fails.

The decision filter compares your branch commits against the merge base,
reads the diff plus your test and setup files (with static secrets redacted,
except values returned by a secret provider), and skips tests rated under
20% likely affected. Anything the model can't judge (a very large diff, an
oversized test file, or a failed call like a missing API key on a fork PR)
still runs, with a warning in the output and any directly edited tests
prioritized first. Requires `ai` 7.0.134+.

Any [decision model](https://e2e.com/docs/decision-models) that answers `boolean` questions
works (for example `typeSafeAi.decisionModel('jev-latest')` directly via
`@ai-sdk/typesafe-ai` with `TYPESAFE_AI_API_KEY`). Pass `providerOptions`
for gateway settings like `{ gateway: { zeroDataRetention: true } }`.

## Preview locally

<CodeGroup>
```bash npm
npx e2e list --changed-since origin/main
```

```bash pnpm
pnpm exec e2e list --changed-since origin/main
```

```bash bun
bunx e2e list --changed-since origin/main
```
</CodeGroup>

`e2e list` prints every test that a filter skipped along with its reason. It
doesn't start your app, and makes the same model calls as a run. Commit your
changes first so the filter can read the diff.

## What always runs

- The full suite whenever `--changed-since` isn't passed (or nothing changed
  since the merge base).
- `--last-failed` reruns and subsequent `--watch` reruns.

The decision filter also always runs:

- Any test whose test file, setup file, or stored screenshots changed.
- The full suite whenever your `e2e.config.*` or a dependency lockfile
  changes (like `pnpm-lock.yaml`, `Podfile.lock`, `gradle.lockfile`,
  `Gemfile.lock`, `go.sum`, `Cargo.lock`, or `libs.versions.toml`).

If a filter throws, returns an invalid result, or times out after 5 minutes,
e2e logs a warning and that filter excludes nothing (later filters in the
chain still run). On other CI services, pass `--changed-since origin/main`
on PR builds with enough git history for the merge base (see
[GitLab](https://e2e.com/docs/ci/gitlab#run-only-affected-tests)). With `--shard`, each shard
filters only its own slice.

## Start the likeliest first

The decision filter scores every kept test by how likely it is to be
affected (100% for directly edited tests, setups, and snapshots; otherwise
the model's probability), and runs the riskiest files first so failures show
up early, especially with `--max-failures` or CI's single-worker default.
Within each priority band, multi-worker runs also sort by
[timings history](https://e2e.com/docs/ci#cache-the-timings-history).

Custom filters can provide the same ordering by returning `relevance` scores
between 0 and 1 ([see below](#write-your-own)).

## What you see

- **Terminal**: one line per filter, such as
  `decision kept 7 of 77 tests, left out 70 (1 call, 17.6k tokens, $0.0007)`.
  The decision filter's note ends with its spend: model calls, tokens, and
  the cost when the provider reports it, as the AI Gateway does. A line such
  as `ranked 7 of 7 tests by relevance, likeliest first` follows when
  the scores put tests in more than one band. A `Left out` row follows in the summary. When the
  filters leave nothing to run, the run passes and starts no app.
- **[Pull request comment](https://e2e.com/docs/github) and `summary.md`**: the headline
  `7 passed, 70 left out by filters`, and a folded table of the tests with
  their reasons.
- **`junit.xml` and `report.json`**: each left-out test is a skipped case,
  with `skip.filter` in the report, beside `run.filters` and `run.changes`.
  See [Reporters](https://e2e.com/docs/reference/reporters#test-filters).

## Adjust the decision filter

Wrap the decision filter to change what it judges. This one runs every
test when `infra/` changes, leaves `apps/mobile/`, which these tests don't
reach, out of the change, and always runs the `smoke` tests:

```ts title="tuned-filter.ts"

const decision = decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') });

export const tuned = {
  name: 'decision',
  filter(tests, context) {
    if (context.changes.files.some((file) => file.startsWith('infra/'))) return { exclude: {}, note: 'infra/ changed' };
    const judged = tests.filter((test) => !test.tags.includes('smoke'));
    const files = context.changes.files.filter((file) => !file.startsWith('apps/mobile/'));
    if (files.length === 0) return { exclude: Object.fromEntries(judged.map((test) => [test.id, 'only apps/mobile/ changed'])) };
    return decision.filter(judged, { ...context, changes: { ...context.changes, files } });
  },
} satisfies TestFilter;
```

Put `tuned` in `filters` in place of `decisionFilter(...)`. To run every
test on one pull request, leave out `--changed-since` when it has the
`all-tests` label. Add `labeled` to the events so adding the label starts a
run:

```yaml title=".github/workflows/e2e.yml"
on:
  pull_request:
    types: [opened, synchronize, reopened, labeled]
# ...
      - run: npx e2e run ${{ github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'all-tests') && format('--changed-since origin/{0}', github.base_ref) || '' }}
```

## Write your own

A filter is `{ name, filter }`: `filter` gets the tests and the change, and
returns the tests to leave out with a reason for each. It can also score the
rest from 0 to 1 with `relevance`. This one maps changed paths to test tags,
and starts the tests whose area the change reaches first:

```ts title="areas-filter.ts"

/** The test tags each part of the app reaches, by path from the repository root. */
const AREAS: Readonly<Record<string, readonly string[]>> = {
  'src/todos/': ['todos'],
  'src/auth/': ['auth', 'smoke'],
  'src/checkout/': ['checkout'],
};
/** Every tag an area reaches; a test without one always runs. */
const AREA_TAGS: ReadonlySet<string> = new Set(Object.values(AREAS).flat());

export const areas = {
  name: 'areas',
  filter(tests, { changes }) {
    const reached = new Set<string>();
    let unmapped: string | undefined;
    for (const file of changes.files) {
      const area = Object.keys(AREAS).find((prefix) => file.startsWith(prefix));
      if (area === undefined) unmapped = file;
      else for (const tag of AREAS[area] ?? []) reached.add(tag);
    }
    const exclude: Record<string, string> = {};
    const relevance: Record<string, number> = {};
    for (const test of tests) {
      const tags = test.tags.filter((tag) => AREA_TAGS.has(tag));
      if (tags.some((tag) => reached.has(tag))) relevance[test.id] = 1;
      else if (tags.length > 0 && unmapped === undefined) exclude[test.id] = 'the change reaches none of its areas';
    }
    if (unmapped === undefined) return { exclude, relevance };
    return { exclude, relevance, note: `${unmapped} is in no area, so areas leaves nothing out` };
  },
} satisfies TestFilter;
```

Put it before the decision filter, so the model judges only the tests
`areas` kept:

```ts title="e2e.config.ts"

export default {
  targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
  filters: [areas, decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })],
} satisfies E2EConfig;
```

- Any test you don't list in `exclude` runs (along with any excluded test
  that shares a serial group with a kept test).
- `relevance` maps test IDs to scores from 0 to 1 (highest score wins across
  multiple filters). Even a throwing filter can attach a `relevance` map to
  its error so directly changed tests still run first.
- Filters chain in order, so each one only sees the tests kept by the
  previous filter.
- Pass `signal` to any async work, and pass prompts through `redact` before
  sending them to a model. `redact` masks static secrets and credential
  passwords (including any 8+ character substring of one), but values
  returned by a secret provider pass through.
- Keep filtering work inside `filter()` rather than module top level, since
  worker processes also import your config file.

See [`TestFilter`](https://e2e.com/docs/reference/config#testfilter) for the types.

## Next

<CardGroup cols={2}>
  <Card title="Continuous integration" icon="rotate" href="/ci">
    Gate pull requests, shard, and rerun failures.
  </Card>
  <Card title="Reporters" icon="file-lines" href="/reference/reporters">
    Read `run.changes`, `run.filters`, and `skip.filter` from your own reporter.
  </Card>
</CardGroup>
