# Shopfront reading — agent contract

The machine contract for one keyed Shopfront reading: one property's `direct`
route, read once, synchronously. This document is served with the API at
`/api/v1/readings.md` and is versioned with it.

## What one call is

One call sells **one Shopfront reading**: one property × one route (the
`direct` route; a `channel` route is a different subject and is not sold),
the seven `HFD-F01`…`HFD-F07` find facts, the evidence class and provenance of
admission, the disclosure, and the pinned edition. The response is the reading
record itself, not a rendering of it.

The record prints **the level the reading observed, never a grade above Level
1**: a find-only reading cannot exceed Level 1, and Level 1 is ungraded
(`grade: "—"`). It never prints `act`, `confirm` or `recover` claims. It also prints the **rung and egress** that produced it (ADR-0048 §3): a wall met from
the deployment's network is a different fact from the same wall met from an
operator's network, so `egress` reads, for example, `scripted · datacenter`.

A call is synchronous: it holds one HTTP request and runs inside a per-reading
budget. Every response carries the budget as `X-Reading-Budget-Ms`
(`60000`). A reading that outlives it answers `504
reading_budget_exceeded` rather than a partial record.

Only public HTTP(S) property URLs are accepted. Private, loopback, link-local
and metadata targets are refused before any fetch.

## The key

The key is a bearer token shaped `sfl_live_<id>_<secret>`. It is shown once
when it is issued and cannot be recovered; a lost free key is reissued to the
same verified email. Send it on every call:

    Authorization: Bearer sfl_live_<id>_<secret>

A free key is issued to a verified email and carries **two readings a month**
(one scan-and-re-scan loop). A paid credit is one reading. Both are counted in
the deployment's ledger, not in the client. That monthly allowance is the
sandbox — a real property, no card, no fixture — and the keyless teaser below is
the zero-risk try.

A key is issued at `/keys` on this deployment, and credits are bought at
`/credits`. A call with a malformed, revoked or expired key is a `401` whose
`error.signup_url` names that page, so a client can point its human straight at
it. A call with no `Authorization` header at all is not a `401`; it is the
keyless teaser, described below.

A keyless call is allowed, but only as the teaser described below. Every other
call needs a key.

## The call

    POST /api/v1/readings
    Authorization: Bearer sfl_live_<id>_<secret>
    Content-Type: application/json
    Idempotency-Key: <optional, 1-128 characters>

    { "url": "https://www.example-hotel.com/", "route": "direct" }

- `url` is required: an absolute public HTTP(S) URL of the property.
- `route` is optional and defaults to `direct`; `direct` is the only value sold.
- `Idempotency-Key` is optional and makes a retry safe.

## Quickstart

The shortest path from a key to one reading: the endpoint, the key in an
`Authorization` header, and one body. Every example sends the same headers and
the same bytes, and none needs a package.

The first call:

    POST /api/v1/readings
    Authorization: Bearer sfl_live_<id>_<secret>
    Content-Type: application/json
    User-Agent: shopfront-reading/1.0

    {"url": "https://www.example-hotel.com/", "route": "direct"}

A `200` is the record. A refusal is the JSON error shape documented below;
read `code`, not the prose.

Name the caller. Every example sends `User-Agent: shopfront-reading/1.0`, and that header is not decoration: the edge in front of the door
answers some default library tokens (a bare `Python-urllib/3.13`, for one)
before the request reaches the Worker, and that refusal is the edge's, not
the endpoint's, so it is not in the error table below.

### curl

    TARE_ORIGIN="https://<origin>"
    TARE_KEY="sfl_live_<id>_<secret>"

    curl -sS -X POST "$TARE_ORIGIN/api/v1/readings" \
      -H "Authorization: Bearer $TARE_KEY" \
      -H "Content-Type: application/json" \
      -H "User-Agent: shopfront-reading/1.0" \
      -d '{"url": "https://www.example-hotel.com/", "route": "direct"}'

### TypeScript

    const origin = "https://<origin>";
    const key = "sfl_live_<id>_<secret>";
    const body = '{"url": "https://www.example-hotel.com/", "route": "direct"}';

    const response = await fetch(origin + "/api/v1/readings", {
      method: "POST",
      headers: {
        Authorization: "Bearer " + key,
        "Content-Type": "application/json",
        "User-Agent": "shopfront-reading/1.0",
      },
      body,
    });
    const detail = await response.text();
    if (!response.ok) throw new Error("readings: " + response.status + " " + detail);
    const record = JSON.parse(detail);
    console.log(record.readingId, record.outcome, record.egress);

### Python

    import json
    import urllib.error
    import urllib.request

    origin = "https://<origin>"
    key = "sfl_live_<id>_<secret>"
    body = b'{"url": "https://www.example-hotel.com/", "route": "direct"}'

    request = urllib.request.Request(
        origin + "/api/v1/readings",
        data=body,
        method="POST",
        headers={
            "Authorization": "Bearer " + key,
            "Content-Type": "application/json",
            "User-Agent": "shopfront-reading/1.0",
        },
    )
    try:
        with urllib.request.urlopen(request) as response:
            record = json.load(response)
        print(record["readingId"], record["outcome"], record["egress"])
    except urllib.error.HTTPError as refusal:
        # A refusal is the JSON error shape: read `code`, not the prose.
        print(refusal.code, refusal.read().decode())

The record, trimmed to the fields this quickstart reads (the response
section below has the whole shape):

    {
      "kind": "shopfront_reading",
      "readingId": "frc_9c1f4b2e-6a3d-4e8f-b7c5-0d2a6f1e8b94",
      "readingVersion": "find-v3",
      "edition": {
        "kind": "shopfront",
        "name": "Shopfront",
        "version": "v1.0",
        "label": "Shopfront v1.0"
      },
      "property": {
        "url": "https://www.example-hotel.com/",
        "canonicalHost": "example-hotel.com",
        "route": "direct"
      },
      "date": "2026-11-16",
      "observedAt": "2026-11-16T09:00:00.000Z",
      "outcome": "level_1",
      "level": 1,
      "grade": "—",
      "headline": "Level 1 · Grade —",
      "egress": "scripted · datacenter"
    }

`readingId` names the payment that bought the reading: `frc_…` for a free
allowance claim, `crd_…` for a prepaid credit. `egress` is the rung and the
network that produced it; a reading says where it was read from.

## The response

A `200` is the record. The envelope adds three fields the find record does not
carry:

| Field | Meaning |
| --- | --- |
| `kind` | `"shopfront_reading"` — the artifact name, distinct from `readingVersion`. |
| `readingId` | The one credit debit that paid for this record (`crd_…`). The charge identity, never the price. |
| `egress` | `"<rung> · <network>"` for the attempt that produced the record, e.g. `"scripted · datacenter"` (ADR-0048 §3). |

The record itself:

| Field | Meaning |
| --- | --- |
| `readingVersion` | The record shape's version: `"find-v2"` carries the analytics observation, `"find-v3"` names the timeline's instrument per row, and `"find-v1"` predates the field. |
| `edition` | The pinned edition: `{ kind, name, version, label }` (`Shopfront v1.0`). |
| `property` | `{ id?, name?, url, canonicalHost, route, segment? }` — the normalized subject; `route` is `direct`. |
| `date` | The one UTC day the reading is taken on, `YYYY-MM-DD`. |
| `observedAt` | The clock behind `date`, ISO 8601 in UTC. |
| `settleBudgetMs` | The settle budget each browser rung was given, in milliseconds. |
| `jobFamily` | `"find"` — the job family read. |
| `jobs` | The seven find job ids, `HFD-F01`…`HFD-F07`. |
| `outcome` | `level_1` (a level printed), `refused` (a wall), or `nothing_readable` (no level). |
| `level` | `1` or `null`. A refusal and a nothing-readable surface print no level. |
| `grade` | `"—"` at Level 1, or `null` when no level prints. A level is never graded here. |
| `headline` | The one sentence the reading prints: the level and grade pair, or the honest absence of one. |
| `familyHeadline` | The family sentence, always printed beside the headline. |
| `find` | The find profile: `strong`, `partial`, `missing` or `not_captured`. |
| `profile` | `{ find, act, confirm, recover }`; the last three are `not_captured` without consent and a test account. |
| `qualification` | The visitor-layer qualification printed beside the level. |
| `facts` | One row per job: `{ job, status, class, value?, source, firstSeenAt, quote? }`. `status` is `present`, `partial`, `missing` or `not_captured`; `class` is `observable`, `inferred` or `not_captured`; `quote` is verbatim evidence. |
| `admission` | One row per rung tried: `{ rung, layer, status, admitted, mechanism?, http?, at, timeToAdmitMs, pageLoads, egress }`. `rung` is `scripted`, `headless` or `headed`; `layer` is `discovery`, `property_site`, `booking_engine` or `payment_step`; `status` is `admitted`, `admitted_with_terms`, `challenged`, `blocked` or `not_found`; `egress` is `operator_network` or `datacenter`. |
| `ladder` | `{ configured, attempted }` — the rungs this deployment offered and the ones this run tried. A one-rung offering is visible here, never implied. |
| `disclosure` | `{ declared, lines, checkedUrl, at }` — what the surface publishes for agents (an aipref or Content-Signals line), verbatim, and the robots file the reading asked. |
| `substitution` | Set only when the address asked for did not answer at the connection level and the reading continued once at `www.` (#523): `{ requestedUrl, finalUrl, reason }`, where `reason` is `certificate` when a browser rung reported a certificate error, `unreachable` otherwise. The record's `property.url` stays the address asked for. Absent means the reading was taken where requested. |
| `analytics` | The analytics observation: the tags the fetched HTML declares, whether Google Consent Mode appears in it, and the cookies the session wrote before any consent token, with their offsets from navigation start. On a `"find-v3"` record each row carries `timedBy` (`store` or `header`) and `timeline` counts the rows by that field, so the reader can say which measurement produced each offset (#512). When `timeline.untimed` is not zero the timeline is a **lower bound** (#526): `timeline.session` is the number of in-scope cookies the session held, the untimed cookies are named in `timeline.untimedCookies`, and none of them is estimated. On a record whose version observes, absent means the reading did not observe: its rung had no cookie store to read — a scripted fetch, which the print's limits list states because the record cannot — or it had one and could not time the jar, which `notPrinted` says. A `"find-v1"` record predates the field, so its absence says nothing either way. It is never *observed none* (#471, #496, #502). |
| `engine` | Optional `{ name, family, evidence, endpoint?, mechanism? }` — the booking engine observed as a fact of distribution. |
| `cost` | `{ pageLoads, rungsAttempted, moneyGate }` — the standard's cost band: what the attempt took, never what the reading cost. The reading's price is one credit, carried as `readingId`. |
| `http` | `{ statuses: number[] }` — every HTTP status the reading met, in request order. |
| `snapshotHash` | `sha256:…` over the admitted page's extracted text. |
| `refused` | Optional `{ layer, mechanism }` — the wall that ended the reading, when one did. |
| `notPrinted` | What the reading refuses to print, in the run's own words. |
| `cohort` | Present only when the run was given one: the cohort and the segment a property was read under (ADR-0047 §3). Absent on a single keyed read. |

Response headers to read beside the body:

| Header | Meaning |
| --- | --- |
| `X-Reading-Budget-Ms` | The per-reading budget this response was held to. |
| `Cache-Control` | `no-store`: a reading is the keyholder's copy, never a cacheable one. |
| `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` | The key's per-minute window (60 requests a minute). |
| `Retry-After` | Seconds to wait, on `429`, `409`, `502`, `503` and `504`. |
| `WWW-Authenticate` | `Bearer` on a `401`. |

## Retries and Idempotency-Key

Send an `Idempotency-Key` on a call you may retry (a timeout, a dropped
connection, a `5xx`). A retry with the same key, inside **24 hours**, returns
the original reading instead of charging again. The key is opaque; only
equality matters.

- **Same key, same request** → the original reading, byte for byte.
- **Same key, while the original is still running** → `409
  idempotency_in_flight`; retry after `Retry-After`.
- **Same key, a different request** → `409 idempotency_conflict`; use the
  original request or a new key.
- **No key** → no replay promise; a retry is a new reading and a new charge.

A key is 1–128 characters. A key that is empty or too long is `400
invalid_idempotency_key`. A reading that produced no record (a `502`, `503`
or `504`) was not charged, so a retry with the same key is safe.

## The MCP server

The same reading is exposed as one MCP tool over the streamable HTTP transport
at `POST /api/v1/mcp` (JSON-RPC 2.0, `application/json` responses). The
server registers one tool, `shopfront_reading`, with these arguments:

| Argument | Type | Meaning |
| --- | --- | --- |
| `url` | string, required | The property's public HTTP(S) URL. |
| `route` | string, optional | `"direct"` (the only value); defaults to `direct`. |
| `idempotencyKey` | string, optional | Forwarded as the `Idempotency-Key` header. |

Register it in the caller's own client:

    claude mcp add --transport http shopfront <origin>/api/v1/mcp --header "Authorization: Bearer <key>"

The server is stateless: it accepts an `Mcp-Session-Id` header and ignores it,
because the deployment keeps no session state and every call is a complete
reading on its own.

`tools/call` forwards to `POST /api/v1/readings` with the caller's own
`Authorization` header. The endpoint performs the authentication, the ledger,
the throttle and the idempotency; the MCP layer adds no credential and has no
second error shape. A `200` is returned as MCP text content, the record body
verbatim. Any non-`200` is returned byte for byte as error text with
`isError: true` and `_meta.httpStatus` set to the HTTP status, so the codes in
the error table below are the ones to read there too.

## The keyless teaser

A call with **no `Authorization` header at all** is the keyless teaser. It is
meant to let an agent discover the door without a human.

- One call per address per UTC day.
- The response is `{ "kind": "teaser", "outcome": …, "level": … }` — the
  outcome and level only. It never contains `facts`, `readingId` or the
  record.
- It does not draw on the free tier and mints no key.
- Only public HTTP(S) property URLs are accepted. A private, loopback,
  link-local or metadata target is `403 teaser_target_refused` and does not
  burn the day.
- The address's day is spent by a call that produces an outcome; `429
  teaser_limit` carries `Retry-After` to the next UTC midnight.
- `429 teaser_budget_exhausted` means the deployment's own daily pool is spent;
  use a key or wait for the UTC day to roll.

A malformed or wrong `Authorization` is **not** the teaser: it is `401
invalid_key`.

## Terms

A key buys readings of one property on its direct route. These are the terms it comes with, in the order they bind.

### A named reading only on a claim

A reading is taken on one property's public surface, and it is delivered to you, the keyholder. You may show it to that property, or to whoever acts for it, only when the property has claimed the reading.

What you publish about properties that have not claimed their readings is an aggregate: counts, a rate and a method, never a named finding. The rule is the same one the register and the benchmark print.

### No resale and no white-label

The key serves your own loop: read a property, fix its surface, read it again. You may not resell a reading, rebrand it, issue sub-keys, or charge a third party for one.

Delivering one reading to your client, under the client's own claim, is the service this key is sold for. It is not resale.

### One credit is one reading

Credits are prepaid, and one credit pays for one reading. A reading that produced no record — a budget overrun or a failed run — is not charged.

Bought credits expire twelve months after purchase. The free allowance on an address is two readings a month, resets at the start of each UTC month, and is counted against the address rather than against one key.

### What Tare keeps

Tare keeps the request data behind a call for thirty days. You own the copy you pull. A keyed reading is not published, carded or listed anywhere.

Your requests are not used to train models.

### Support is the documentation

Support is the agent contract at /api/v1/readings.md and the closed error taxonomy it documents. In v1 there is no account, no dashboard and no separate support channel: the contract is the support.

The same terms are served to a person at `/shopfront/terms`.

## Errors

Every error has the same shape, and the endpoint is the only author of it:

    { "error": { "code": "credits_empty", "message": "…", "top_up_url": "…" } }

`code` is one of the closed list below. `message` is for a human. `details` is
optional and carries field-level validation detail. `top_up_url` is present on
a `402`, and `signup_url` on a `401`.

The checks run in this order: **401 → 403 → 429 → 402 → 504**, with request
validation in front of all of them (a malformed body cannot spend a credit).

| Code | HTTP | When the endpoint answers it |
| --- | --- | --- |
| `invalid_json` | 400 | The request body was not valid JSON. |
| `invalid_input` | 400 | The body failed shape validation; `url` is missing or not a non-empty string. |
| `invalid_property_url` | 400 | `url` is not a fetchable absolute public HTTP(S) property URL (relative, non-HTTP, malformed, or a private/loopback target on the keyed path). |
| `route_not_sold` | 400 | `route` was anything other than `direct`; a channel route is a different subject and is not sold. |
| `invalid_idempotency_key` | 400 | `Idempotency-Key` was empty or longer than 128 characters. |
| `invalid_key` | 401 | `Authorization` was not `Bearer <token>`, or named an unknown, expired or revoked key. A call with **no** `Authorization` header is the keyless teaser, not this code: it is refused by the teaser's own rules, never with a 401. |
| `auth_throttled` | 429 | Too many refused credentials arrived from one address in one minute. Wait out `Retry-After`; this bounds the 401 surface, not honest traffic. |
| `credits_empty` | 402 | The key has no credits left. The body carries `top_up_url`; one reading costs one credit. |
| `credits_expired` | 402 | The key's credit grant has expired. The body carries `top_up_url`. |
| `free_limit` | 402 | A free key has used its two readings for the month. The body carries the reset time and the same `top_up_url` every 402 carries; the allowance returns at the reset without a purchase. |
| `teaser_target_refused` | 403 | A keyless call named a private, link-local or metadata target; refused before any fetch. |
| `teaser_limit` | 429 | A keyless call exceeded one reading per address per UTC day. `Retry-After` points to the next UTC midnight. |
| `teaser_budget_exhausted` | 429 | The deployment's keyless-teaser pool for the UTC day is spent. Use a key, or wait for the day to roll. |
| `rate_limited` | 429 | The key exceeded its 60 requests in the current minute. `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` and `Retry-After` describe the window. |
| `idempotency_in_flight` | 409 | A retry arrived with this `Idempotency-Key` while the original reading is still running. Retry after `Retry-After`. |
| `idempotency_conflict` | 409 | This `Idempotency-Key` was already used for a different request. Reuse the original request or send a new key. |
| `reading_failed` | 502 | The reading failed before a record existed; the debit was refunded and the call may be retried. |
| `reading_unavailable` | 503 | The deployment has no reading ledger or runner configured, or the reading could not be produced. `Retry-After` is printed; this is not a claim about the property. |
| `reading_budget_exceeded` | 504 | The reading did not finish inside the 60-second per-reading budget. No partial record was delivered and the debit was refunded. |

An error body is passed through the MCP tool unchanged: do not re-wrap it, and
read `code`, not the prose. A `5xx` is retryable; a `4xx` is not, except the
retry rules above.
