# Docs

Lookup for the `hunt` CLI, `hunt.toml` and the `@slopkit/hunt` Step SDK. A first run is on Getting started: https://hunt.slopkit.dev/start/

Hunt runs Gherkin Scenarios against a deployed, running product and builds an Experience Map from the runs. Step definitions are TypeScript and run in a Step Host, in the JavaScript runtime the product chooses. Terms below follow the product's CONTEXT.md.

This page matches slopkit/hunt 0.1.0. `hunt --version` prints `hunt 0.1.0`. `hunt --help` prints the full usage and `hunt <command> --help` prints one command.

## Global options

These work on every command.

`-C, --dir <DIR>`
: Directory that holds `hunt.toml`, or a child of it. Hunt reads the nearest `hunt.toml` in that directory or its parents. Default: `.`

`--runtime <RUNTIME>`
: Replaces `runtime` from `hunt.toml` for this command, for example `"bun"` or `"deno run -A"`. The value is split on whitespace.

`-h, --help`, `-V, --version`
: Print help or the version.

## Exit status

`0` on success. `1` when `hunt run`, `hunt explore` or `hunt db` finishes with a failure. `2` when the command cannot run, for example when no `hunt.toml` is found. Errors print to stderr as `hunt: <message>`.

```
hunt: no hunt.toml in /tmp or its parents
```

## hunt list

List Features, Scenarios and Steps from the `.feature` files. Backgrounds, Rules and Outlines are expanded.

```
hunt list [-t|--tags <EXPR>] [--json]
```

`-t, --tags <EXPR>`
: Only Scenarios that match the tag expression, for example `"@smoke and not @slow"`.

`--json`
: Print JSON instead of text.

Text output is one `Feature: <name>` line per Feature, then per Scenario `Scenario: <name>  <tags>  [<id>]` and its Steps. A Scenario id is `<feature path>:<line>`. `hunt list` does not start a Step Host.

## hunt steps

List the Step definitions the Step Host loads.

```
hunt steps [--json]
```

Starts a Step Host, prints `Step Host: <runtime>` and one line per definition with its keyword, pattern and location, then shuts it down. It fails with exit `2` when the Step Host entry file is missing. See `host` under hunt.toml.

## hunt run

Run Scenarios through the Step Hosts.

```
hunt run [-t|--tags <EXPR>] [-j|--workers <N>] [--scenarios-from <FILE>]
         [--format text|json|message] [--json] [--messages <FILE>]
         [-u|--update | --ci] [--map]
```

| Option | Meaning |
| --- | --- |
| `-t, --tags <EXPR>` | Only Scenarios that match the tag expression. |
| `-j, --workers <N>` | Number of Step Hosts that run Scenarios in parallel. Default: `workers` in `hunt.toml`, else `1`. `0` is refused. Scenarios tagged `@controlled` always run alone. |
| `--scenarios-from <FILE>` | Only the Scenarios whose ids are listed in the file, one per line. The file is what `hunt select --out` writes. Combines with `--tags`. |
| `--format <FORMAT>` | `text` (default), `json`, or `message`. `message` writes Cucumber Messages as NDJSON to stdout and moves the human summary to stderr. |
| `--json` | Same as `--format json`. Conflicts with `--format`. |
| `--messages <FILE>` | Also write Cucumber Messages as NDJSON to this file. |
| `-u, --update` | Accept changed Snapshots and remove obsolete ones. Conflicts with `--ci`. |
| `--ci` | Write no Snapshots. A missing Snapshot fails. |
| `--map` | Run a Mapping Run: one Worker, then read each Step's Function Coverage from rat and write `map.json`. Conflicts with `--workers`. |

Results print as one block per Scenario, in Scenario order, whichever Worker finishes first. A Step's `ctx.log` lines appear under that Step. With more than one Worker the run starts with `Running <n> Scenarios on <w> workers`. After a full, passing run (no `--tags`), Snapshots that no Scenario used are reported as obsolete. The run ends with a line such as `Snapshots: 5 matched, 1 written`. When Scenarios reached Screens, `screens.json` is written under `<artifacts>/<run>/` and the run prints `Screens: <n> reached (<path>)`.

Exit `0` when every Scenario passes, `1` otherwise.

### Workers

Each Worker owns one Step Host process, so Step files, `ctx.state` and module state are not shared between Workers. Workers share one Browser Adapter (each Scenario run has its own browser session), one set of Snapshots and the same Stubs service. A Scenario tagged `@controlled` (on the Scenario, its Examples, the Rule or the Feature) holds the whole Environment. It waits for running Scenarios to finish and no other Scenario starts until it is done.

### Snapshot modes

| Run | New Snapshot | Mismatch |
| --- | --- | --- |
| `hunt run` | written | fails |
| `hunt run -u` | written | replaced |
| `hunt run --ci` | fails | fails |

### Cucumber Messages

The stream follows the Cucumber Messages protocol, version 35.0.0. A Scenario's messages are written when it finishes, in Scenario order, so the stream does not depend on the number of Workers. `testCaseStarted.workerId` says which Worker ran it. Hooks and attachments are not part of the stream yet.

## hunt explore

Run Steps once, without a `.feature` file. An Exploration uses the product's own Step definitions and never changes the Baseline.

```
hunt explore [STEP]... [--name <NAME>] [--save <FILE>] [--json]
```

`STEP`
: A Step, one per argument, for example `'When I sign up as "Ada"'`. With no arguments, or with `-`, Steps are read from stdin, one per line. A line without a keyword is a Step too. Tables and doc strings follow their Step as in a `.feature` file.

`--name <NAME>`
: Name of the Exploration, shown in the output and used by `--save`. Default: `Exploration`.

`--save <FILE>`
: Write the Steps as a new Scenario in a new `.feature` file. It refuses to overwrite a file that exists.

`--json`
: Print the outcome as JSON, with return values.

Output starts with `Exploration (nothing is recorded in the Baseline)`. Results print as in a run, plus what each Step returned. Hooks run, and `ctx.scenario.tags` contains `exploration`. Snapshots are never written: one the Baseline does not have is unrecorded, not a failure. Screens are listed after the Steps and are not added to the Experience Map. State does not carry from one `hunt explore` to the next. Exit `0` when every Step passed, `1` otherwise, `2` for bad input.

## hunt db

Check the Data Sources in `hunt.toml`.

```
hunt db [NAME]
```

`NAME`
: Only this Data Source. Default: every `[data_sources.<name>]`.

Prints `✓ <name>: connected, the role cannot write` per Data Source, or `✗` and the reason. With no Data Source configured it fails with `no [data_sources.<name>] in hunt.toml`. Exit `0` when every check passes, `1` otherwise.

## hunt select

Choose the Scenarios a code change can affect, for `hunt run --scenarios-from`.

```
hunt select [--diff <BASE...HEAD> | --changed-files <FILE>] [--out <FILE>] [--json]
            [--index <FILE>] [--index-branch <BRANCH>] [--always <EXPR>]
            [--ignore <GLOB>]... [--full-on <GLOB>]...
            [--unmapped-threshold <N>] [--shared-ratio <R>]
            [--service-prefix <SERVICE=PREFIX/>]... [--full]
            [--agent-cmd <CMD>] [--repo-root <DIR>]
```

| Option | Meaning |
| --- | --- |
| `--diff <BASE...HEAD>` | Changes between two commits, as any `git diff` range. Line ranges narrow the selection when the index has function lines. |
| `--changed-files <FILE>` | One changed path per line, relative to the repository root. The whole file counts as changed. |
| `--index <FILE>` | The Step to code index. Default: `.hunt/index.json` if present, else the newest run on `--index-branch` at the hosted service that has an index in its `map.json`. |
| `--index-branch <BRANCH>` | Branch whose newest indexed run supplies the index. Default: `main`. |
| `--always <EXPR>` | Scenarios that always run, as a tag expression. Default: `@smoke`. |
| `--ignore <GLOB>` | Changed files to ignore. Repeatable. Added to the defaults (`*.md`, `docs/**`, and others). |
| `--full-on <GLOB>` | Changed files that force a full run. Repeatable. Added to Step definitions and `hunt.toml`. |
| `--unmapped-threshold <N>` | How many changed files the index may not know before the selection falls back to the full suite. Default: `0`. |
| `--shared-ratio <R>` | A file mapped by more than this share of Scenarios is shared code, and changing it runs everything. `1` disables it. Default: `0.5`. |
| `--service-prefix <SERVICE=PREFIX/>` | Path prefix for a service's coverage files when its root is not the repository root. Repeatable. Only for an index read from a Mapping Run's `map.json`. |
| `--full` | Select every Scenario, whatever the diff says. |
| `--agent-cmd <CMD>` | A command that may adjust the selection. It gets JSON on stdin and prints `{"add":[ids],"remove":[ids]}`. `always` Scenarios cannot be removed. A failing command keeps the selection. |
| `--repo-root <DIR>` | Repository root that changed paths are relative to. Default: git's top level. |
| `--out <FILE>` | Write the Scenario ids, one per line. |
| `--json` | Print the decision as JSON on stdout. |

Selection rules, the index formats and the agent hook are in the product's `docs/ci.md`.

## hunt serve

Run the hosted service: media storage, the Experience Map and the Run Overview. One binary and one data directory, no database.

```
hunt serve [--listen <ADDR>] [--data <DIR>] [--project <NAME=TOKEN>]...
           [--viewer <NAME=TOKEN>]... [--projects-file <FILE>]
           [--main-branch <BRANCH>] [--font <FILE>]...
```

| Option | Environment | Meaning |
| --- | --- | --- |
| `--listen <ADDR>` | `HUNT_SERVER_LISTEN` | Address to listen on. Port `0` picks a free one. Default: `127.0.0.1:7430`. |
| `--data <DIR>` | `HUNT_SERVER_DATA` | Where media and runs are stored. Default: `hunt-data`. |
| `--project <NAME=TOKEN>` | `HUNT_SERVER_PROJECTS` | A project and its read and write token. The token has at least 8 characters. The environment variable is comma separated. |
| `--viewer <NAME=TOKEN>` | `HUNT_SERVER_VIEWERS` | A read-only token for the same project. |
| `--projects-file <FILE>` | `HUNT_SERVER_PROJECTS_FILE` | One project per line as `NAME TOKEN [VIEWER-TOKEN]`. `#` starts a comment. |
| `--main-branch <BRANCH>` | `HUNT_SERVER_MAIN_BRANCH` | The branch the Experience Map is built from. Default: `main`. |
| `--font <FILE>` | `HUNT_SERVER_FONT` | A font file for the PNG Run Overview. Repeatable. System font directories are loaded as well. The SVG needs no font. |

Put the service behind TLS. Media is only ever added, so back up the data directory. Run one server process per data directory.

### Routes

All routes are under `/p/<project>/`, except `GET /healthz`, which answers `ok`. Reads take `Authorization: Bearer <token>` with a viewer or full token, or `?token=`, which sets a cookie for browsing. Writes need the full token in the header.

| Route | Meaning |
| --- | --- |
| `PUT media/<sha256>` | Store a screenshot. The bytes must hash to the name. `HEAD` and `GET` read it. |
| `PUT runs/<id>` | Upload a run as JSON with `run_id`, `branch`, `commit`, `messages`, `screens` and `map`. Answers 409 while its media is missing. |
| `GET runs` | JSON list of runs. `?branch=` filters. |
| `GET runs/<id>` | The run's page. `runs/<id>/run.json` is the record and `runs/<id>/map.json` is the uploaded Mapping Run map. |
| `GET map`, `GET map.json` | The Experience Map. `?branch=` builds it from another branch. |
| `GET runs/<id>/overview.svg`, `overview.png` | The Run Overview. No token is needed: the run id is the capability. The PNG needs a font on the server, or it answers 501. |

## hunt upload

Send a run to the hosted service.

```
hunt upload [RUN] [--branch <BRANCH>] [--commit <SHA>] [--environment <NAME>]
            [--messages <FILE>] [--map <FILE>] [--json]
```

`RUN`
: The run id, a directory in the artifacts directory. Default: the newest run.

`--branch <BRANCH>`, `--commit <SHA>`
: Branch and commit of the run. Default: `CI_COMMIT_REF_NAME` and `CI_COMMIT_SHA`, or the GitHub equivalents, else git.

`--environment <NAME>`
: Name of the Environment the run was against.

`--messages <FILE>`
: Cucumber Messages file. Default: `messages.ndjson` in the run's directory.

`--map <FILE>`
: A Mapping Run's `map.json`. Default: `map.json` in the run's directory, if present.

`--json`
: Print the result as JSON.

Needs `[server]` in `hunt.toml` and the project token in the environment (`HUNT_TOKEN` by default). It sends the run's Cucumber Messages, `screens.json` and screenshots, and the `map.json` when there is one. It prints the run's URL, the Run Overview URL and a Markdown image for a merge request.

## hunt.toml

`hunt.toml` sits in the product's repository. Paths are relative to the directory that holds it. Unknown keys are an error.

```toml
features = "features"
steps = ["steps/**/*.ts"]
runtime = ["bun"]   # or ["node"], ["deno", "run", "-A"]
```

| Key | Default | Meaning |
| --- | --- | --- |
| `features` | `"features"` | Directory or file with the `.feature` files. |
| `steps` | `["steps/**/*.ts", "steps/**/*.js"]` | Globs for Step definition files. Files under `node_modules` are skipped. |
| `runtime` | `["node"]` | Command that starts the Step Host runtime: `["node"]`, `["bun"]` or `["deno", "run", "-A"]`. |
| `host` | `"node_modules/@slopkit/hunt/dist/host.js"` | Step Host entry file. The command is `runtime` followed by this path. |
| `step_timeout_secs` | `30` | Time a Step may take. |
| `workers` | `1` | Step Hosts that run Scenarios in parallel. |
| `artifacts` | `".hunt/runs"` | Where run artifacts such as screenshots and `screens.json` go, under `<run id>`. |

### [snapshots]

| Key | Default | Meaning |
| --- | --- | --- |
| `media` | `".hunt/media"` | Local store for screenshot images, addressed by hash. |
| `tolerance_percent` | `0.0` | Percent of pixels a screenshot may differ from its Baseline and still match. |

### [browser]

| Key | Default | Meaning |
| --- | --- | --- |
| `adapter` | `"agent-browser"` | The Browser Adapter. `agent-browser` is the only one in 0.1.0. |
| `command` | `["agent-browser"]` | Command that runs agent-browser. |
| `args` | `[]` | Extra flags for every call: the Browser Host and launch options, for example `["--headed"]`, `["--cdp", "9222"]` or `["--proxy", "http://127.0.0.1:7412"]`. |

### [data_sources.NAME]

A read-only Postgres connection that Steps query with `ctx.db`.

```toml
[data_sources.app]
url_env = "APP_DATABASE_URL"        # or url = "postgres://hunt_ro@db.internal/app?sslmode=require"
```

| Key | Meaning |
| --- | --- |
| `url_env` | Name of the variable that holds the connection URL. |
| `url` | The connection URL. Use it or `url_env`. |
| `statement_timeout_secs` | Longest a query may run. |
| `max_rows` | A query that returns more rows fails. |
| `tls_ca_file` | Extra CA certificates to trust. TLS is verified against the public roots plus this file. |

Only Postgres is supported. Use `sslmode=disable` in the URL for a local database without TLS.

### [server]

The hosted service. Without it, a changed screenshot whose Baseline image is not in the local media store is reported as unverified and does not fail.

| Key | Default | Meaning |
| --- | --- | --- |
| `url` | none | Base URL of `hunt serve`. |
| `project` | none | Project name. |
| `token_env` | `"HUNT_TOKEN"` | Name of the variable that holds the project token. The token is never read from the file. |

With `[server]` set, `hunt run` downloads missing Baseline images, sends new ones when it writes Snapshots, and keeps `messages.ndjson` in the run's artifacts directory for `hunt upload`. If the service cannot be reached, the run goes on and says so.

### [mapping]

Settings for `hunt run --map`.

| Key | Default | Meaning |
| --- | --- | --- |
| `rat_url` | `$STALKER_ENDPOINT`, else the local rat | Base URL of rat. Plain `http://`. |
| `write_key_env` | none | Name of the variable that holds rat's write key, sent as Basic auth. |
| `keys` | `["hunt.run", "hunt.scenario", "hunt.step"]` | Must equal the Sensors' `STALKER_COVERAGE_KEYS`. Without `hunt.run`, rat sums every run's data for the Scenario and Step. |
| `settle_ms` | `1500` | Wait before asking again for Steps that came back empty. |

## Mapping Runs

`hunt run --map` is an ordinary run plus a `map.json` in the run's artifacts directory. It needs Stalker Sensors in the Environment that file Function Coverage with rat, keyed by `STALKER_COVERAGE_KEYS=hunt.run,hunt.scenario,hunt.step`. Hunt sends all three as `baggage` on every Step request. A Mapping Run uses one Worker, because a Sensor measures the whole process.

`map.json` has `version`, `run`, `workers`, `scenarios`, `nodes`, `edges` and `totals`. Nodes are the Screens and Screen States that Steps declared. Edges are the Steps between two Screens of a Scenario. Coverage is `service`, then `file`, then functions. Skipped Steps are not asked about.

## Environment variables

| Name | Meaning |
| --- | --- |
| `HUNT_TOKEN` | Project token for `hunt upload` and `hunt run` with `[server]`. The name is set by `token_env`. |
| `HUNT_JETLAG_URLS` | Comma-separated Jetlag API URLs. Enables the `jetlag` Clock Driver. `JETLAG_URL` also works. |
| `HUNT_JETLAG_TARGET` | Jetlag Target to shift. Default: `child`, the program a `jetlag run --listen` started. |
| `DECOY_URL` | Decoy control API for Stubs. Default: `http://127.0.0.1:7411`. |
| `STALKER_ENDPOINT` | Default for `rat_url`. |
| `HUNT_SERVER_*` | Options of `hunt serve`, listed under that command. |

## @slopkit/hunt

The Step SDK. Version 0.1.0. It is published with each release to the slopkit/hunt npm registry on this GitLab and runs on Node and Bun. Point the `@slopkit` scope at the registry in `.npmrc`:

```
@slopkit:registry=https://gitlab.techtailors.net/api/v4/projects/slopkit%2Fhunt/packages/npm/
```

`./host` exports the Step Host entry, `dist/host.js`, which `hunt` starts by default.

### Defining Steps

```ts
import { Given, When, Then } from "@slopkit/hunt";

Given("an Account {string}", async (ctx, name: string) => {
  ctx.state.account = name;
});
```

`Given(pattern, fn)`, `When(pattern, fn)`, `Then(pattern, fn)`, `Step(pattern, fn)`
: Define a Step. `Step` matches any keyword. `pattern` is a Cucumber Expression or a `RegExp`. `fn` is called with `ctx`, then the captured arguments. A doc string and then a data table are appended after them. A return value is shown by `hunt explore`.

`Before(fn)`, `After(fn)`
: Hooks that run before a Scenario's first Step and after the Scenario, even when a Step failed. Each receives `ctx`.

A Step is matched in the Step Host. A Step with no matching definition has status `undefined`. A Step that matches more than one has status `ambiguous`. The Steps after a non-passing Step are `skipped`.

### Context

`ctx` is the first argument of every Step and hook.

| Member | Meaning |
| --- | --- |
| `ctx.scenario` | `{ id, feature, name, tags, runId, traceId }`. |
| `ctx.state` | Free-form object shared by the Steps of one Scenario. |
| `ctx.log(message)` | Write a line to the run's output, attributed to the current Step. |
| `ctx.trace` | `{ traceId, spanId, traceparent, baggage }` of the running Step. It changes with every Step. |
| `ctx.traceHeaders()` | The `traceparent` and `baggage` headers for the running Step. |
| `ctx.fetch(input, init?)` | `fetch` that adds the running Step's `traceparent` and `baggage`. Existing `baggage` entries in `init.headers` are kept. |
| `ctx.call(method, params?)` | Call a Hunt core service. |
| `ctx.browser` | This Scenario run's browser, opened on first use. |
| `ctx.stub(rule)` | Register a Stub. |
| `ctx.stubCalls(filter?)` | Read the calls Decoy intercepted for this Scenario run. |
| `ctx.clock` | Clock Shifts. |
| `ctx.db` | Read-only SQL against the Data Sources. |
| `ctx.screen(name, state?, options?)` | Declare a Screen. |
| `ctx.expect(value)` | Snapshots. |

### Trace context

Hunt gives every Scenario run one W3C trace id and every Step a new span id. `baggage` is `hunt.run=<run>,hunt.trace=<trace id>,hunt.scenario=<scenario id>,hunt.step=<index>`. `ctx.fetch` and `ctx.browser` send it on every request.

### ctx.browser

Each call becomes a request to the Browser Adapter. Every Scenario run gets its own browser session, closed when the Scenario ends. Before every Step the core sets the Step's `traceparent` and `baggage` as headers on the browser. These headers apply to every origin, so a cross-origin API must allow `traceparent` and `baggage` in `Access-Control-Allow-Headers`.

A target is a CSS string, or one of `{ role, name? }`, `{ label }`, `{ text }`, `{ placeholder }`, `{ testid }`, `{ css }`.

| Method | Meaning |
| --- | --- |
| `open(url)` | Open a URL. |
| `click(target)` | Click an element. |
| `fill(target, value)` | Fill an input. |
| `press(key)` | Press a key. |
| `text(target)` | Visible text of an element. Returns a string. |
| `url()` | Current URL. |
| `waitFor({ text } \| { url } \| { css })` | Wait until the page shows the text, matches the URL pattern, or has a CSS match. |
| `eval(js)` | Run JavaScript in the page and return the result. |
| `snapshot({ interactive? })` | Accessibility tree of the page. |
| `screenshot({ name?, full? })` | Save a screenshot under the run's artifacts and return its path. |
| `vitals()` | Core Web Vitals (LCP, CLS, TTFB, FCP, INP) of the current page. |
| `a11y()` | axe-core accessibility audit of the current page. |

### ctx.stub and ctx.stubCalls

A Stub is a Decoy Rule that only answers requests whose `baggage` carries this Scenario run's `hunt.trace` entry. Rules are removed when the Scenario ends. `ctx.stub` returns the Decoy Rule id. It needs Decoy reachable at `DECOY_URL`.

```ts
await ctx.stub({
  host: "api.stripe.com",
  method: "POST",
  path: { exact: "/v1/charges" },
  respond: { status: 402, json: { error: { type: "card_error", code: "card_declined" } } },
});
```

A rule has `host` (required) and either `respond` or `handler`, not both.

| Field | Meaning |
| --- | --- |
| `host` | The third-party host. Registered with Decoy if needed. |
| `method` | A method or a list of methods. |
| `path` | `{ exact }`, `{ prefix }` or `{ glob }`. |
| `headers` | Extra conditions, each `{ name, equals? \| contains? }`. |
| `priority` | Higher wins. Among equals the newest Rule wins. |
| `respond` | A fixed answer: `status`, `headers`, `body`, `body_base64`, `json`, `delay_ms`. |
| `handler` | A module path, or `{ module, env?, mode? }`. `mode` is `"host"` or `"embedded"`. Relative paths resolve from Hunt's working directory. |

`ctx.stubCalls({ host?, method?, path?, path_prefix? })` returns Decoy's recorded calls for this Scenario run, oldest first. Each has `id`, `time`, `host`, `method`, `path`, `query?`, `request`, `response`, `rule_id` and `outcome`, one of `rule`, `fail`, `passthrough`, `default`.

### ctx.clock and ClockDriver

Every call goes to all Clock Drivers at once. A Scenario that used the clock is reset when it ends, even if a Step failed. Durations use Jetlag's syntax: `30d`, `-2h`, `1d12h`, `90m`.

| Method | Meaning |
| --- | --- |
| `shift(offset, { freeze? })` | Move `offset` ahead of real time. |
| `shiftTo(at, { freeze? })` | Move to the instant `at`, an RFC 3339 string or a `Date`. |
| `advance(by)` | Move by `by` from where the clock is now. |
| `freeze(at?)` | Stop the clock now, or at `at`. |
| `reset()` | Back to real time. |
| `drivers` | Names of the drivers a Clock Shift goes to. |

The built-in `jetlag` driver is enabled by `HUNT_JETLAG_URLS`. A product adds its own from a Step file:

```ts
import { ClockDriver } from "@slopkit/hunt";

ClockDriver({
  name: "billing",
  shift: async ({ offset, at, freeze }) => { /* ... */ },
  advance: async (by) => { /* ... */ },
  freeze: async (at) => { /* ... */ },
  reset: async () => { /* ... */ },
});
```

With no driver configured, a `ctx.clock` call fails the Step and names how to add one. The browser's clock is not shifted.

### ctx.db

`ctx.db.query(sql, params?)` returns rows as objects. `ctx.db.source(name).query(...)` reads a named Data Source when `hunt.toml` has more than one. Parameters fill `$1`, `$2` and are sent as text. The SQL must be one `SELECT`, `WITH`, `VALUES` or `TABLE` statement.

Reads are read-only three ways. Each query runs in a read-only transaction that is always rolled back. Hunt refuses a role that is a superuser, belongs to `pg_write_all_data`, `pg_write_server_files` or `pg_execute_server_program`, or holds INSERT, UPDATE, DELETE or TRUNCATE on a table or view, UPDATE on a sequence, or CREATE on a schema or the database. The API has one operation, `query`. A Data Source is not shifted by a Clock Shift.

### Snapshots and Screens

`ctx.expect(value).toMatchSnapshot(name?)`
: Compare the serialized value with `__snapshots__/<feature file>.snap` next to the `.feature` file, in Jest's format. Keys are `<Scenario name> › <Snapshot name>`. Without a name, Snapshots are numbered `<Scenario> 1`, `<Scenario> 2`. Two Scenarios or Outline rows with the same name cannot share a Snapshot.

`ctx.expect(value).toMatchInlineSnapshot(snapshot?)`
: Compare with a template literal. The first run writes it into the Step file. `-u` rewrites it. `await` the call. One call site holds one value, so every Scenario that runs the Step must produce the same value.

`ctx.screen(name, state?, { mask?, full? })`
: Declare that the Scenario reached a Screen, and optionally a Screen State. Hunt records it in `<artifacts>/<run>/screens.json`. With a browser open, it takes the Screen's screenshot as a Snapshot. `mask` is a list of CSS selectors whose text is replaced by a fixed placeholder on a grey box. `full` captures the whole page. It throws on a mismatch. It resolves to `{ screen, key?, outcome, screenshot?, mismatchPercent?, diff? }`.

The `.snap` file stores a screenshot as `image sha256:<hex>`. The same hash matches. A different hash is compared pixel by pixel with the Baseline image and matches when at most `tolerance_percent` of pixels differ. When the Baseline image is not in the media store, the screenshot is reported as unverified and does not fail.

`Serializer({ test, serialize })`
: Add a Serializer. Call it from a Step file. `serialize(value, print, indent)` turns a value into Snapshot text, and `print` serializes nested values. Later Serializers win.

`hideKeys(keys, placeholder?)`
: A Serializer that replaces the values at the given keys, at any depth, with `"[hidden]"`.

```ts
import { Serializer, hideKeys } from "@slopkit/hunt";

Serializer(hideKeys(["id", "created_at"]));
```

Values are serialized to stable text: object keys sorted, two-space indents, top-level strings as they are.

## Step Host protocol

`hunt run` starts a Step Host in the configured runtime. Messages are JSON-RPC 2.0, one JSON object per line: the core writes to the host's stdin and reads its stdout. The host's stderr passes through to the user. The protocol version is `0.1`, as `major.minor`. The core and the host refuse to talk when the major versions differ.

Core to host: `initialize`, `scenario.start`, `step.run`, `scenario.end`, `shutdown`. Host to core: the `log` notification, plus service calls made through `ctx.call()`, which carry `scenarioId`. Unknown methods get error `-32601`. The full tables are in the product's `docs/step-host-protocol.md`.

## Concepts

Feature
: A user-facing capability of the product, described by its Scenarios.

Scenario
: A named, saved example of one behavior of a Feature, written as Given, When and Then Steps.

Step
: One reusable, parameterized Given, When or Then line, backed by a browser or HTTP action or assertion.

Step Host
: The process, in the JavaScript runtime the product chooses, where Step definitions run for Hunt.

Worker
: One parallel lane of a run. Each Worker has its own Step Host and runs one Scenario at a time.

Controlled Scenario
: A Scenario tagged `@controlled` because it holds the whole Environment. It runs alone.

Environment
: A deployed instance of the product under test, provisioned outside Hunt. An Observed Environment is reachable only from outside, through a browser and HTTP. A Controlled Environment cooperates with Hunt and allows Stubs and Clock Shifts. The Reference Environment is the one whose runs may update Snapshots.

Browser Adapter, Browser Host
: The Adapter drives a browser engine behind Hunt's browser API. The Host is where the browser runs, set independently.

Stub
: A stand-in for a third-party service in a Controlled Environment, registered as a Decoy Rule for one Scenario.

Clock Shift, Clock Driver
: A Clock Shift moves the wall-clock time of every part of a Controlled Environment at once and holds the Environment until reset. A Clock Driver applies it to one part. Jetlag is the main driver.

Data Source
: A read-only connection to a product's database.

Screen, Screen State
: A Screen is a named place in the product's experience that a Step declares it reached. A Screen State is a named variant, such as `empty` or `card declined`.

Experience Map
: A browsable atlas of a product's user-facing journeys, built from recorded runs, with coverage and pass or fail on top.

Exploration
: An unsaved run of Steps with a one-off setup. It never changes the Experience Map or the Baseline.

Snapshot, Serializer, Baseline
: A Snapshot is a recorded value that later runs must match. A Serializer turns a value into its stored form. The Baseline is all Snapshots as committed on the main branch. Accept a change by merging the merge request that changes it.

Mapping Run
: A run that records which code each Step touched.

Run Overview
: A single shareable image that sums up one run, with before and after thumbnails of changed Snapshots.

## Related products

Hunt works with Jetlag (Clock Shifts), Decoy (Stubs) and Stalker with rat (Function Coverage in Mapping Runs). Each is a separate product: https://jetlag.slopkit.dev, https://decoy.slopkit.dev, https://stalker.slopkit.dev, https://rat.slopkit.dev.

Source and issues: https://gitlab.techtailors.net/slopkit/hunt. Part of SlopKit: https://slopkit.dev
