# Conformance

`@tineira/apc-conformance` checks an app against the [core](/docs/spec#the-core) of the standard the way an agent or a dock's hub reaches it: JSON-RPC over the app's MCP endpoint, stateless, plus `GET /.well-known/apc.json`. What only the app's page knows (whether a page is open, the view it reports, the pin the person drops, the presence it receives, Revoke in the agent bar) comes through a small **adapter** the app writes.

The 1.x suite checks apps claiming its own major, passing newer patches and minors with a note and checking them by its own rules. It also checks claims from 0.10 to 0.13 as pre-1.0, and fails another major ([versioning and compatibility](/docs/spec#versioning-and-compatibility)). It runs two ways: [from the command line](#run-it-from-the-command-line), against a live app over HTTP (what HTTP alone can reach), or [from code](#run-it-from-code), in your tests, with an adapter for the page (everything).

## What the suite checks

With an adapter (the [code](#run-it-from-code) way), on the profile under test, Direct or Dock:

- **`apc.json`**: served as JSON from the app's own origin, valid, a standard the suite knows, the profile under test listed (both, with `apc_link`), never `"hub"`, the grant's MCP URL covered for the profile under test (under `mcp.path`, or by an entry of `mcp.endpoints` that lists that profile, 0.11), `direct.connect` on the app's origin, and on an app that lists `dock` and claims 0.13 or later (`M13`), `dock_connect` (`https`, same origin, no fragment) whose GET answers HTTP 200 (never 3xx) with `Referrer-Policy: no-referrer` (apps claiming 0.10–0.12 pass with a pre-0.13 note). With `mcp.endpoints`, every entry is one readers use (no key but `path` and `profiles`, an exact path or one ending in `/{secret}`, no `dock` on an exact path), the list is not empty, every profile offered has an entry, and no near-miss key (`endpoint`, or `endpoints` outside `mcp`) stands in for it. An entry that lists a profile the app does not offer right now is fine (M8).
- **The tools**: `get_current_view` and `wait_for_focus` listed; `get_current_view` takes no required argument; `timeout_s` is an optional whole number from 1.
- **The view**: identifiers only (`params` are keys), and no focus before a pin.
- **The pin**: rides as `attention`, in the structured result and in the text, on any result until it is read; `next` with `next_args` reads it; a new pin replaces it, unread again.
- **Nothing but grants under `P/{secret}`** (0.11, an app whose `mcp.endpoints` has a `{secret}` entry): a JSON-RPC POST and a GET to a child of `P/` that fits a secret and names no grant are refused with a 4xx (never a 2xx, a redirect or a 5xx); an unknown grant answers 404, and another 4xx passes with a note.
- **`wait_for_focus`**: returns a pin dropped during the wait, soon after; times out cleanly with a note and no `then`; ends at once when the person has no page open. "Soon" is within 8.7 s of the pin and "on time" within 4 s past `timeout_s`: the spec's [`wait_for_focus`](/docs/spec#wait_for_focus-and-then) names these numbers, which leave room for a poll slower than the reference's 2 s.
- **`then`**: on results only while the person's page is open and the agent was pinned lately; an open page with no pin gives none (of an app that claims 0.8.0 or later).
- **One wait per grant** (0.8.0 or later): a newer wait takes over and the older one returns nothing; a second wait right after the first is refused with `retry_after_s`, and the first still delivers; a wait the client cancels marks nothing seen and frees its place, so a pin dropped after it is still unread.
- **No `then` on a wait with no focus**: the timeout, the wait a newer one took over, the refused wait and a cancelled wait that still answers carry no `then`. Each is checked after a recent pin was read, with the page open, so a `then` that should not ride would.
- **Presence**: one event per read, ids only, naming the target the read touched.
- **Wait events** (0.11.0 or later, Direct, of an app that sends them; any wait event the page gets anywhere in the run counts, one that has sent none passes with a note, and a last check fails the run if one comes after; atomicity is the app's claim, and the suite checks the events, not the store): a wait sends `open` while it runs and `closed` once it returns, `{ v, grant_id, at, kind: "wait", state }` and nothing more; a takeover sends the old wait's `closed` before the new wait's `open`, and nothing more from the old wait; a cancelled wait and a wait cut by a revoke send `closed`; a refused wait and a wait on a revoked grant send nothing. On the Dock profile they are not checked: a page shows no waiting for a dock grant.
- **Revoke**: the revoked grant answers `{ error: "revoked", revoked_by, revoked_at, message }`, `revoked_by` being the app's host as in the grant's MCP URL (with its port, when the URL has one; not a host behind a proxy) and `message` a non-empty string, which is required (403 with a secret URL, 401 with a bearer token), to every request: `initialize`, `tools/list`, `tools/call`, `ping`, `resources/list`, `prompts/list`, a notification, a body that does not parse, a GET and a DELETE; it cannot be pinned; another agent is untouched; a call already running ends `revoked`, with no data: the `RevokedAnswer` in the text and nothing else, and in `structuredContent` too when the app puts it there.

An adapter whose app authenticates agents with a bearer token (OAuth) gives the token in each connection's `headers` (`{ authorization: "Bearer …" }`); the grant's URL may then be `mcp.path` itself.
- **Mobile** (0.6 and later): every agent is shown in the page, the bar cannot be collapsed, a finger pins and the agent reads the pin, and unpin works by touch.
- **The pairing code** (Dock, 0.9 and later; the adapter gives `dock`): a new, well-formed code with every consent, shown only on the app owner's page, and that same code sent raw in `/apc/pair`. The suite reads it from `allow()`'s answer, and also from the consent answer when the adapter supplies `code`; every supplied observation must match the transmitted code. A hub that does not acknowledge the code, redirects, or says yes with HTTP 500 holds no grant (its MCP URL answers 404); five wrong codes, or the code's time running out, give the grant back; the right code pairs.
- **The consent's nonce** (Dock; through `dock.lifecycle.owner`, a note without it): an Allow pairs only with its own consent's nonce, once. One with the nonce left out, a forged one or another agent's sends the hub no `/apc/pair`; the right one does, and the same Allow again does not. The members of `owner.allow.body()` that the drop's body lacks are where the nonce goes; another agent's nonce is checked only when the Allow names its agent.
- **The Dock profile as built** (Dock, 0.10 and later; the adapter gives `dock.lifecycle`, see [below](#the-dock-profile-as-built-10)):
  - **The gate fails closed**: the suite reads the claimed standard from `apc.json` at the adapter's owner origin, which must be a bare origin and the same as the grants' origin. Only an app that provably claims a standard before 0.10.0 skips the checks, with a note, and only once a grant it makes lives at the owner origin (an owner origin pointed at an older deployment fails closed). An `apc.json` the suite cannot read or parse, a missing `dock.lifecycle` (or one of its required members, `restart` included) fails every 0.10 check. After each check the suite gives back (`/apc/revoke`) every grant the stand-in hub paired meanwhile.
  - **The answer table**: in each state the adapter can put a grant into (in flight, handoff, live, dormant for an app that sleeps, ended, revoked), the exact answer to `initialize`, `ping`, `tools/list`, `get_current_view`, `wait_for_focus`, one of the app's own tools, another method (`resources/list`) and two notifications (one with no `id`, and `notifications/cancelled` with an `id`, still a notification), as `dockGrantAnswer` in `@tineira/apc-protocol` says, with each message classified by `dockGrantCallOf`. In flight, ended and revoked, the "any request" row too: a `GET`, a `DELETE` and a `POST` that does not parse answer 404 (in flight, ended) or `RevokedAnswer` (revoked). The `pairing` and `idle` tool errors carry `{ error, message }` in `structuredContent` and in `content[0].text`; the idle shapes carry `idle: true` (and `wait_for_focus` answers at once); no answer in handoff or dormant carries `attention`, `then`, `apc_link` or a presence event; a 404 in flight leaves the state unchanged.
  - **The transitions**: `initialize` commits the move out of handoff, and fails closed (HTTP 500 or JSON-RPC -32603, no result, still in handoff) when its commit cannot persist; `initialize` raced against Cancel, and against a give-back, in both orders, ends by the state that won; Cancel revokes only in handoff before a served call (never a live grant, served or not, nor an ended one); a give-back or `T_ack` while in flight ends the grant for good, even if the acknowledgement comes after; `T_ack` (30 s) ends a grant whose Allow never heard back across a restart of the app, and a late acknowledgement does not bring it back; `T_connect` (10 minutes, or the app's own `connectMs`) ends a grant never connected, and a late introduction does not bring it back; `T_idle` sleeps a live grant, and the page's heartbeat and a confirmed drop wake it; with `dormancyMs`, long dormancy ends a grant asleep that long, and a heartbeat does not bring it back (without it, a note says long dormancy was not checked); agent traffic never wakes a grant or extends it; handoff, revoked and ended each win over dormant (a grant in handoff past `T_idle` is held only while the app's `T_connect` is longer; otherwise a note says so).
  - **The hub call**: M1, tricky hubs (a longer host, userinfo, a path, a query, a fragment, `http:` unless the hub is a local-dev `http:` origin, another port, a trailing dot, a backslash, unparsable) answer `hub_not_allowed` with no consent and no request on the drop, and on an Allow that carries a hub (an app that binds the hub to the consent on the server says so with `allowCarriesHub: false`, and its Allow must call only the drop's hub). Not on the adapter's word: the suite also posts the Allow to `owner.allow` itself with a foreign hub in `hub` and in place of every value that names the drop's hub, whatever its member's name; it must be refused or ignored (no call off the hub's origin, and a yes only with an `/apc/pair` at the stand-in since). M2 to M4 hold on both hub calls, `/apc/pair` after the Allow and `/apc/confirm` on a drop of a grant in handoff, and once on a paired grant (live, or dormant for an app that sleeps). A confirm call that fails is not taken: the drop does not show the old code (it is refused, or a fresh consent starts), its target is not pinned, nothing is made live and a dormant grant is not woken. M2, a redirect, a 3xx, an `opaqueredirect` or a redirected answer holds no grant, and the app's request never reaches the redirect's target (the stand-in logs a fetch that follows as reaching it); M3, one deadline covers the headers and the body: stalled headers, a stalled body, headers then a body each held 60% of the app's deadline (`hubDeadlineMs`, 10 s by default), and headers held 90% of it then a body that never ends, all refused by the deadline plus 30% of it (at least 1 s, at most 2.5 s), so two deadlines that add up past the limit fail (under a declared deadline of about 3.3 s the 1 s floor applies, and a second deadline shorter than it goes unseen) (the stand-in honours the request's `AbortSignal`, so a deadline kept with `AbortSignal.timeout` on the fetch works); M4, a `content-length` over the cap or not digits only, and a body over the cap, are refused, while a `content-length` other than the decoded body's (gzip) is taken; M5, with the hub's answer held, another agent's drop and Allow answer within 2.5 s, a second Allow of the same consent gets `pairing_in_progress`, and a new drop of the same agent either waits for the first or answers `pairing_in_progress` (never a second consent or `/apc/pair`); serialization across instances cannot be seen from one process; M9, a drop whose hub ends in `/` calls `{hub}/apc/pair` and `{hub}/apc/confirm`, not `//apc/…`.
  - **M6**, on all four owner endpoints (the drop, the Allow, the heartbeat, Cancel; a missing one fails): a foreign `Origin` (or `null`, or another scheme), look-alikes of the configured origin (a longer host, another port, a trailing dot, a prefix, the origin cut short, so a `startsWith`, `endsWith` or `includes` comparison fails; the same on the WebSocket handshake, the other scheme included), `Sec-Fetch-Site: cross-site` or `same-site`, a media type other than `application/json`, and no session are refused (4xx); its own `Origin`, and neither header, are taken on the session. The configured origin, not the request's: the suite also sends each request to another host (`https://apc-conformance-internal.example`) with that host as its `Origin`, as the inside of a proxy sees it, and expects a refusal. An app that compares `Origin` with its request URL takes it; one that compares with its configuration, or refuses hosts it does not serve, refuses it. A 4xx passes and a 2xx fails. Any other answer (a redirect, a 5xx, a request that does not get through) is compared with the same request carrying a foreign `Origin`: the same answer is a host or a proxy answering, and the probe is left unchecked with a note; another answer fails, since the app took the request's own host as its origin. A WebSocket heartbeat (`{ websocket: path }`) gets the same probes on its handshake. Every state change is a `POST`: a `GET` with the session and the body's fields as a query may answer anything, but must change nothing (no hub call, no grant revoked, a dormant grant still asleep, and no consent: every token of the GET drop's answer is tried as the nonce of an Allow, in the member(s) `owner.allow.body()` has and the drop's body lacks, and none may make the app send `/apc/pair`). Cancel's `body()` should make its grant during the call, through `dock.hub`; for a grant paired beforehand the suite watches every grant in handoff the stand-in paired, and with none a note says the probe did not run.
  - **M7**: `/apc/revoke` answers the same 200 and the same body to any input (not JSON, a foreign URL, an unknown grant, 1 MiB, a body that never ends, answered within 2.5 s), ends a matching grant in handoff or live (which then answers 404), and leaves a revoked grant revoked and an ended one ended.
  - **M8**: `apc.json` lists `dock` while the app can pair and not with pairing disabled, with a `max-age` of 60 or less.
  - **M10–M12, the binding** (Dock, 0.12 and later): M10 stores the acknowledged pairing binding and never rebinds it; M11 admits handoff only for its own pairing and agent and refuses another binding on live or dormant grants; M12 keeps every non-Dock grant, including Direct grants, at an app implementing Dock or still serving any Dock grant from serving as a Dock grant, regardless of current pairability. An app that does not implement Dock and holds no Dock grant owes no M12 refusal, but MAY refuse anyway. The suite also checks the pre-0.12 unbound window and that no MCP answer or drop outcome exposes the binding.
  - **The code goes only in `/apc/pair`**: never in `/apc/confirm`, a URL the app calls, or an MCP answer on the grant.
  - **Origin-bound first pairing (`M13`, Dock, 0.13 and later)**: `dock_connect` (`https`, same origin, no fragment) answers GET 200 (never 3xx) with `Referrer-Policy: no-referrer`, and a first drop with no link calls `/apc/connect` on the stand-in hub (not `/apc/pair`). The synchronous `<head>` fragment script clearing `#apc_connect` into `sessionStorage` is **reference behaviour** (verified in end-to-end use, not conformance-tested). For claims of 1.0 or later, an exact HTTP 404 `{"error":"not_found"}` from `/apc/connect` refuses the drop without consent, a grant or `/apc/pair`, even with a valid Connect consent nonce. Apps claiming 0.10–0.12 keep passing their existing checks with a pre-0.13 note (the 0.13 first-pairing checks apply only to claims `>= 0.13`, and 1.0 accepts `0.10–0.13` as pre-1.0).
  - **One pending pairing**: a second drop on a pending pairing shows the same code, with no new consent or `/apc/pair`, and its target is the pin once the grant is live; `not_paired` or the app's stored expiry (two minutes, through the time seam) ends the grant and starts a fresh consent. Its Allow answer, raw `/apc/pair`, waiting card and hub approval must all use the new code, different from the ended grant's. `paired` before `initialize` says it is connecting and stays in handoff until `initialize`; a new drop replaces an unallowed consent, and the stale Allow gets `consent_expired`. When the replaced consent supplies `code`, the replacement's code must differ, checked both at consent time when supplied and in its Allow answer. When the replaced consent withholds its code until Allow, its freshness cannot be observed: its stale Allow fails, so the suite cannot compare that code.
- **`apc_link`** (an app with both profiles): the same client on the other path is offered a code once per session and the code links them; a code is refused on the connection that got it, on the same path, on another client, once used, and once expired; another client is offered nothing; Revoke on a linked agent cuts both grants; Unlink gives two agents again.

The suite has no DOM check and cannot prove which code the app renders from its HTTP answers. For 0.9.x adapters without `dock.lifecycle`, it also cannot observe a second drop's waiting card. It does not check how the page draws presence, the agent bar's two-click Revoke in a real browser, or rules that need the dock UI (`CODE-2`'s "never shows" on the dock page, `DROP-1` no secret in the drag, `TM-1` trust-model UI warnings and unverified markings — reference behaviour, not conformance-tested in 1.0; checked by the reference hub's own tests), nor M13's client-side `<head>` fragment script clearing `#apc_connect` into `sessionStorage` (reference behaviour). For a hub's app-visible MUSTs, see [Hub conformance](#hub-conformance) below (`hubConformance`, in-process only). On the Dock profile it does not check the page's heartbeat cadence (`T_idle / 2` while the page is open: the page sends it, and the suite only calls `heartbeat()`), long dormancy for an adapter that gives no `dormancyMs`, Cancel while the hub call is held (the grant's id is not known before the acknowledgement), or serialization across instances (M5). It sees the app's hub calls through `hub.fetch`, and while a check runs it wraps the global `fetch` too: an `/apc/pair`, `/apc/confirm` or `/apc/connect` sent through it past the stand-in counts as a call off the hub's origin and is not sent. A call made with another HTTP client is not seen. After each check the suite gives back the grants it made, waiting 2 s at most for each. The docs' Orders example uses `apcManifest` with the current `APC_STANDARD_VERSION` and passes the suite with no pending checks.

## Run it from the command line

`@tineira/apc-conformance` has a command, `apc-conformance`, that checks a live app over HTTP with no code (the package is published at the standard's version):

```sh
npx @tineira/apc-conformance@1.1.1 https://orders.example --grant https://orders.example/mcp/<secret>
```

```text
apc-conformance <app-origin> [--grant <mcp-url>] [--bearer-env <VAR>] [--revoked <mcp-url>] [--revoked-bearer-env <VAR>] [--profile direct|dock]
                [--json] [--allow-http] [--timeout <s>]
```

| Option | |
|---|---|
| `<app-origin>` | the app's origin |
| `--grant <mcp-url>` | the MCP URL of a live agent connected directly (Direct profile): runs the MCP checks |
| `--bearer-env <VAR>` | for an app whose agents authenticate with OAuth: the name of an environment variable that holds the grant's bearer token. Sent as `Authorization: Bearer`, never printed. Never put a token on the command line |
| `--revoked-bearer-env <VAR>` | the same, for the revoked grant's token |
| `--profile direct\|dock` | the profile the grant URLs are for (default `direct`). `dock` checks a Dock grant's secret URL exactly as a hub pairing it does, and takes no bearer token |
| `--revoked <mcp-url>` | the MCP URL of a grant you revoked in the app: checks the revoked answer |
| `--json` | the report as JSON |
| `--allow-http` | allows `http:` for a dev server on the host `localhost`, `127.0.0.1` or `[::1]` only (not `*.localhost`) |
| `--timeout <s>` | seconds per request (15 by default) |

It checks what HTTP reaches:

- **`apc.json`**: served with HTTP 200, no redirect, as JSON of at most 16 KiB; the standard's shape, naming the origin it is served from; a standard the checks know (0.5.0 up to the package's, or a newer patch of it, with a note; from 1.0, a newer minor of its major too); an app's profiles, with a Direct app's connect page on its origin, and on an app that offers `dock` and claims 0.13 or later (`apc-json-dock-connect`), `dock_connect` (`https`, same origin, no fragment) answering GET 200 (never 3xx) with `Referrer-Policy: no-referrer` (apps claiming 0.10–0.12 pass with a pre-0.13 note).
- **With `--grant`**: the grant's MCP URL is covered for `--profile` by the origin's `apc.json` (under `mcp.path`, or by an entry of `mcp.endpoints`, which the note names); `initialize` answers as an MCP server with tools; the core tools are listed with their arguments; `get_current_view` answers in the core's format, with `attention` and `then` the same in the structured result and the text; `wait_for_focus({ timeout_s: 1 })` with no pin times out at 1 s (900 to 5000 ms), or ends at once when no page is open, with a note and no `then`; an unknown grant answers HTTP 404 (skipped with `--bearer-env`: there the URL is shared, and an unknown token is the auth's own 401).
- **`mcp.endpoints` with a `{secret}` entry** (0.11): a child of `P/` that fits a secret and names no grant is refused with a 4xx, to a JSON-RPC POST and a GET (404 expected; another 4xx passes with a note).
- **With `--revoked`**: the revoked grant answers `{ error: "revoked", revoked_by, revoked_at, message }`, `revoked_by` being the host of the `--revoked` URL (with its port, when it has one) and `message` required, to every request: `initialize`, `tools/list`, `tools/call`, `ping`, `resources/list`, `prompts/list`, a notification, a body that does not parse, a GET and a DELETE: HTTP 403, or 401 with `--revoked-bearer-env`.

**A Dock grant on localhost.** The command line has no hub of its own: `--profile dock` checks the MCP URL of a grant some hub paired. To get one while you build, run the reference dock on your machine and allow it with `localDevHubs`, or pair through `standInHub` in your own process: both are in [A Dock grant on localhost](/docs/integrate#a-dock-grant-on-localhost). Then run with `--profile dock --allow-http` against your app on `http://localhost:<port>`. The checks that need the person's page and the hub's side (pairing, the lifecycle, the conformance-covered duties within M1 to M13) run only [from code](#run-it-from-code).

**The revoked check, in order.** The revoked grant must be revoked before the run that names it, and it must not be the live one: `--grant` needs a grant that stays live. So: make two agents in your app (two grants), revoke one of them in your page, then run once with the live one as `--grant` and the revoked one as `--revoked`. With a bearer token, the URL may be the same for both: the tokens tell them apart (`--bearer-env` and `--revoked-bearer-env` each name an environment variable holding the raw token, without `Bearer `; the command adds it). [The complete Direct app](/docs/integrate#a-complete-direct-app-with-a-bearer-token) shows that run.

It prints `PASS`, `FAIL` or `SKIP` per check, and exits 0 when nothing failed, 1 when a check failed and 2 on a usage error. What needs the person's page is reported `SKIP`, with why: a pin dropped (attention, `next`, a pin during a wait), the page opened or closed, presence, Revoke pressed (and a call running when it is), a phone's touch, and `apc_link`. Run those with the adapter below, in your own tests.

Under the pass and fail counts it says what the run covered: `N of M checks ran (H of the T reachable over HTTP); K skipped, because:`, then each reason with how many checks it skipped, and that the in-process checks run only from code (`coverage` in `--json`: `ran`, `total`, `skipped`, `skipped_why`, `in_process`, `http_ran`, `http_total`, `mostly_skipped`). When more than half of the checks reachable over HTTP were skipped (no `--grant`, no `--revoked`) it prints a warning that the run is not a conformance pass: exit status 0 then means only that nothing that ran failed. A run with `--grant` and `--revoked` gets no warning; the in-process checks never count toward it.

It reads only that origin, over https, never follows a redirect, caps every answer's size, times out every request, and prints no grant secret, whatever an answer echoes: a grant URL shows with its last segment as `<secret>`.

## Run it from code

`apcConformance(adapter)` returns named checks for any test runner; `runConformance(adapter)` runs them all and reports. The blocks below are excerpts from [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts), the adapter for the Orders app of the [integration guide](/docs/integrate). They leave out the file's surrounding harness (`ORIGIN`, `HUB`, `SESSION`, the `ordersUnderTest` wrapper with `skew`, `config`, `app`, `call` and its `return`, plus `ordersChecks`), and `dock.lifecycle` is shown in its own section below rather than inline inside `ordersUnderTest`. It runs everything in one process: the app's `fetch` is called directly, the person's page is the app's own event stream, and on the Dock profile the suite's stand-in hub answers pairing.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
import { apcConformance, runConformance, standInHub, type AgentConnection, type ApcAppAdapter, type ApcDockDropOutcome, type ApcDockLifecycleAdapter } from "@tineira/apc-conformance";
import { APC_AGENT_TYPE, LONG_DORMANCY_RECOMMENDED_MS, T_IDLE_RECOMMENDED_MS, agentDragPayload, decodeApcConnect, formatPairingCode, type ApcProfile, type FocusTarget, type PresenceMessage } from "@tineira/apc-protocol";
import { barCanCollapse, createTapPin, type BarAgent } from "@tineira/apc-web";
import { OrdersApp, newOrdersStore, type OrdersAppOptions } from "./orders-app.ts";
```

A dock's hub for the Dock profile: `standInHub` from the suite, a hub in your own process that needs no network and no `localDevHubs`: give it an `https:` origin that is never resolved, put that origin in the app's `hubs`, and give the app `hub.fetch` as the `fetch` its `pairWithHub` and `confirmWithHub` calls use. It makes tickets, keeps the pairing code the app sends, asks for it to approve, gives the grant back after five wrong codes or when the code expires, and can play a broken hub (no acknowledgement, a redirect, a 500) for the checks that the app fails closed:

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/**
 * A dock's hub, from the suite: it takes a first drop's Connect request (`/apc/connect`, APC 0.13) and, once its
 * owner approves (`hub.approveConnect`), opens the app's `dock_connect` page with a connect ticket; it takes pairings
 * (`/apc/pair`) and keeps their pairing codes, confirms them (`/apc/confirm`), and calls the app back
 * (`/apc/revoke`, and `initialize` once approved) through `app`.
 */
// Its clock starts on the day 0.12.0 was tagged, inside the window the suite checks for hubs before 0.12.
const started = Date.now();
const hub = standInHub({ origin: HUB, app: (request) => app.fetch(request), now: () => Date.parse("2026-11-14T12:00:00Z") + (Date.now() - started) });
```

The default stand-in follows APC 0.13 H9: `hub.ticket(agent)` is a drop ticket for `/apc/connect`, never `/apc/pair`. After `hub.approveConnect`, use the connect ticket from the returned URL with its bound app origin and agent. Direct drop-ticket pairing answers HTTP 400 `ticket_not_for_pairing`; a connect ticket for another origin or agent answers HTTP 400 `ticket_origin_mismatch`. Both refusals leave the ticket usable on its intended path. For a test that needs a pre-0.13 hub, explicitly create `standInHub({ legacy: "0.12", … })`: `/apc/connect` then answers exactly HTTP 404 `{"error":"not_found"}` and `/apc/pair` accepts drop tickets. This legacy option is separate from the broken-answer `mode`.

The stand-in checks app Connect input before looking up tickets, refuses a live connect ticket on `/apc/connect` and `/apc/confirm` as `ticket_not_for_pairing`, and rechecks the drop ticket after awaiting `apc.json` so concurrent requests cannot spend it twice. A missing `dock_connect` is `apc_json_invalid`. `/apc/pair` checks the trimmed app name, ticket kind, expiry and origin/agent binding, then the code; omitted codes are `pairing_code_required` by default, including in legacy 0.12 mode. Pre-0.9 tests must explicitly opt into `pairingCode: "when_sent"`. Malformed or missing codes preserve the ticket; after code validation the ticket is spent before the MCP URL's origin and HTTPS checks, as in the reference hub. HTTP loopback app origins need `development: true`.

This is an app-test stand-in, not the full reference hub's trust policy, limits or manifest enforcement. In particular, it deliberately permits an uncovered same-origin `mcp_url` so M12 can test whether an app implementing Dock or still serving any Dock grant refuses a Direct grant presented as Dock; the reference hub rejects such URLs as `mcp_url_not_declared`. Simulated `/apc/connect` faults (redirects, errors, missing acknowledgement, invalid lengths and stalls) create no Connect request and leave the drop ticket unspent. Ordinary acknowledgements and the accepted `length_mismatch` and `ack_with_length` modes spend it.

M9 drives a trailing-slash hub through the first drop and, on 0.13, the `#apc_connect` payload passed to `connectDock`, then Allow and a second drop. It checks the canonical `/apc/connect`, `/apc/pair` and `/apc/confirm` URLs. In-process adapters forward that decoded test payload to the Connect server route without normalizing the hub, so the probe reaches server validation independently of the production page's stricter fragment decoder. Pulse and Signals' double-clicked Allow tests also use the 0.13 Connect route; explicit old-standard fixtures retain their legacy path.

`connect` makes a new agent with full access, the way each profile makes one: on Direct the person makes an agent on the page; on Dock the person drops one from the dock, is asked, and allows it (from 0.13 a first drop asks the hub to connect: `hub.approveConnect` plays the dock owner, and the person is asked on the app's `dock_connect` page with the connect ticket from its `#apc_connect` fragment). An app whose agents use a bearer token returns it in the connection's `headers` (`{ grantId, mcpUrl, headers: { authorization: "Bearer …" } }`), and `mcpUrl` may then be the URL every grant shares: see [the complete Direct app](/docs/integrate#a-complete-direct-app-with-a-bearer-token).

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/**
 * A first drop asks the hub to connect (APC 0.13): the dock's owner approves, and the dock opens Orders'
 * `dock_connect` page with `#apc_connect=...`; its script asks the person there (`/api/connect/dock`) with the
 * connect ticket. A missing Connect route refuses the drop; the Allow runs only on the Connect page.
 */
async function ask(first: { hub: string; agent: string; ticket: string; target?: unknown }) {
  let drop = first;
  let route = "/api/drop";
  let asked = await call(route, drop);
  if (asked.ok === true && asked.status === "connect_requested") {
    const approved = await hub.approveConnect(first.agent);
    const opened = approved.url ? decodeApcConnect(new URL(approved.url).hash) : null;
    if (!opened) throw new Error(`the dock opened no #apc_connect URL: ${JSON.stringify(approved)}`);
    drop = opened;
    route = "/api/connect/dock";
    asked = await call(route, drop);
  }
  if (asked.error !== "consent_required") throw new Error(`expected consent_required, got ${JSON.stringify(asked)}`);
  return { asked, route, drop };
}
let drops = 0;
/** A new agent with full access, made the way each profile makes one. */
async function connect(path: ApcProfile): Promise<AgentConnection> {
  if (path === "direct") {
    // The person makes an agent on the page and pastes its URL into the agent.
    const made = await call("/api/agents");
    return { grantId: made.id as string, mcpUrl: made.url as string };
  }
  // The person drops an agent from a dock: the app asks first, and the Allow brings the nonce back.
  drops++;
  const agent = `ag_${drops}`;
  const { asked, route, drop } = await ask({ hub: HUB, agent, ticket: hub.ticket(agent), target: { kind: "order", id: "ord_1001" } });
  const paired = await call(route, { ...drop, consent: asked.consent });
  if (!paired.ok) throw new Error(`pairing failed: ${JSON.stringify(paired)}`);
  // The person types the code in their dock: the hub approves and connects (its initialize makes the grant live).
  const pairing = hub.pairings.filter((p) => p.agent === agent).at(-1)!;
  const approved = await hub.decide(pairing.id, "approve", (paired.pairing as { code: string }).code);
  if (!approved.ok) throw new Error(`the dock did not approve: ${JSON.stringify(approved)}`);
  const grantId = paired.grant_id as string;
  await call(`/api/agents/${grantId}/unpin`); // the suite starts from no pin
  return { grantId, mcpUrl: pairing.mcp_url };
}
```

The pairing code (Dock): `drop(agent, ticket)` returns `{ code?, allow() }`; `allow()` returns `{ ok, error?, grantId?, code? }`. On success, the Allow answer supplies the owner's pairing code, formatted or raw. If the consent displays a code, supply it as the optional consent `code` too; an app withholding it until Allow omits that field. Read these codes from the app's responses to the page or the page itself, never from storage or the hub's copy. The suite requires every supplied code to be well-formed and equal the raw `/apc/pair` code, checks freshness across consents, and plays the dock owner typing the code. Whether the page displays the code at consent (as Orders does) or only after Allow in `<apc-handoff>` (as Pulse and Signals do) is the app's choice, not a rule: both conform. The suite has no DOM check: an adapter reading HTTP responses cannot prove what the app renders.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/**
 * What the page shows for an answer of the drop (`/api/drop`) or of the dock_connect page (`/api/connect/dock`):
 * the consent and its Allow, then the waiting card with its code, connecting, or a refusal.
 */
function shownFor(r: Record<string, unknown>, route: string, drop: Record<string, unknown>): ApcDockDropOutcome {
  if (r.error === "consent_required") {
    return {
      page: "consent",
      code: formatPairingCode(r.pairing_code as string),
      allow: async (over) => {
        const a = await call(route, { ...drop, ...(over?.hub !== undefined ? { hub: over.hub } : {}), consent: r.consent });
        return { ok: a.ok === true, ...(typeof a.error === "string" ? { error: a.error } : {}), ...(typeof a.grant_id === "string" ? { grantId: a.grant_id } : {}), ...(a.ok === true && a.pairing ? { code: formatPairingCode((a.pairing as { code: string }).code) } : {}) };
      },
    };
  }
  if (r.ok === true && r.status === "pending") return { page: "waiting", code: formatPairingCode((r.pairing as { code: string }).code) };
  // The dock took the code and is connecting (APC 0.10), or it will open dock_connect for a first drop (APC 0.13).
  if (r.ok === true && (r.status === "connecting" || r.status === "connect_requested")) return { page: "connecting" };
  if (r.ok === true) return { page: "pinned" };
  return { page: "refused", error: String(r.error) };
}
async function dropAgent(d: { agent: string; ticket: string; hub: string; target?: FocusTarget }): Promise<ApcDockDropOutcome> {
  const drop = { hub: d.hub, agent: d.agent, ticket: d.ticket, target: d.target ?? { kind: "order", id: "ord_1001" } };
  return shownFor(await call("/api/drop", drop), "/api/drop", drop);
}
/** The dock opens dock_connect with `#apc_connect=...` (APC 0.13): the page asks the person with the connect ticket. */
async function connectDock(url: string): Promise<ApcDockDropOutcome> {
  // Forward the suite's payload verbatim: M9 probes server validation, even if a page would reject the fragment.
  const opened = JSON.parse(atob(new URL(url).hash.slice(13).replace(/-/g, "+").replace(/_/g, "/"))) as { hub: string; agent: string; ticket: string };
  const drop = { ...opened };
  return shownFor(await call("/api/connect/dock", drop), "/api/connect/dock", drop);
}

/** The pairing code: Orders displays it at consent time and also returns it from Allow. */
async function dropOnPage(agent: string, ticket: string) {
  const { asked, route, drop } = await ask({ hub: HUB, agent, ticket, target: { kind: "order", id: "ord_1001" } });
  const shown = shownFor(asked, route, drop);
  if (shown.page !== "consent") throw new Error(`expected the consent, got ${JSON.stringify(shown)}`);
  return { code: shown.code, allow: () => shown.allow() };
}
```

The person's page: open while its event stream is, which also carries presence.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/** The person's page: open is an open event stream, which also carries presence. */
let page: { reader: ReadableStreamDefaultReader<Uint8Array>; done: Promise<void> } | null = null;
const presence: PresenceMessage[] = [];
async function setOpen(open: boolean): Promise<void> {
  if (open && !page) {
    const response = await app.fetch(new Request(`${ORIGIN}/api/events`, { headers: SESSION }));
    const reader = response.body!.getReader();
    const decoder = new TextDecoder();
    const done = (async () => {
      let buffer = "";
      for (;;) {
        const { value, done } = await reader.read().catch(() => ({ value: undefined, done: true }));
        if (done) return;
        buffer += decoder.decode(value, { stream: true });
        let end: number;
        while ((end = buffer.indexOf("\n\n")) >= 0) {
          const message = JSON.parse(buffer.slice(6, end)) as { type: string; event?: PresenceMessage };
          buffer = buffer.slice(end + 2);
          if (message.type === "presence" && message.event) presence.push(message.event);
        }
      }
    })();
    page = { reader, done };
  } else if (!open && page) {
    await page.reader.cancel();
    await page.done;
    page = null;
  }
}
```

The adapter: the app's name and profile, its `fetch`, two targets a full-access agent may be pinned to, one of the app's own read tools (`probe`, on which `attention` must ride), the page, the page on a phone, on the Dock profile the pairing code (`dock`), and with both profiles the `apc_link` hooks.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
const targets: [FocusTarget, FocusTarget] = [
  { kind: "order", id: "ord_1001", part: null, params: null },
  { kind: "order", id: "ord_1002", part: "total", params: null },
];
const adapter: ApcAppAdapter = {
  name: "Orders",
  profile,
  fetch: (request) => app.fetch(request),
  connect: () => connect(profile),
  targets,
  probe: { tool: "list_orders", args: {} },
  page: {
    setOpen,
    showView: async () => void (await call("/api/view", { screen: "orders", params: { status: "open" }, selection: { kind: "order", id: "ord_1001" } })),
    pin: async (grantId, target) => (await call(`/api/agents/${grantId}/pin`, { target })).ok === true,
    takePresence: () => presence.splice(0),
    revoke: async (grantId) => (await call(`/api/agents/${grantId}/revoke`)).ok === true,
    // The page on a phone (APC 0.6), modelled with @tineira/apc-web's own pieces: the agent bar's collapse rule and
    // the tap-to-pin controller that enablePinning runs. A browser with touch emulation is the real check.
    mobile: {
      async agentBar() {
        const bar: BarAgent[] = app.agents().map((a) => ({ id: a.id, name: a.name, state: "idle", paths: a.paths }));
        return { visible: app.agents().flatMap((a) => a.grants), collapsible: barCanCollapse(bar, true) };
      },
      async pinByTouch(grantId, target) {
        const pins: Array<Promise<Record<string, unknown>>> = [];
        const tap = createTapPin({ onPin: (id, t) => void pins.push(call(`/api/agents/${id}/pin`, { target: t })) });
        tap.toggle(grantId);
        return tap.tap({ element: {} as Element, target }) === "pinned" && (await pins[0]!).ok === true;
      },
      unpinByTouch: async (grantId) => (await call(`/api/agents/${grantId}/unpin`)).ok === true,
    },
  },
  ...(profile === "dock" ? { dock: { hub, drop: dropOnPage, lifecycle } } : {}),
  ...(options.link
    ? {
        link: {
          connect,
          agents: async () => app.agents().map((a) => ({ grants: a.grants })),
          unlink: async (grantId) => (await call(`/api/agents/${grantId}/unlink`)).ok === true,
          // The app's clock moves past a link code's two minutes.
          expireCodes: async () => void (skew += 121_000),
        },
      }
    : {}),
};
```

Then run it, under `node --test` (`for (const c of apcConformance(adapter)) test(c.name, c.run)`) or as a script:

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/** Every check, with a line per check: what a CI job or a script prints. */
export async function checkOrders(): Promise<boolean> {
  let ok = true;
  for (const profile of ["direct", "dock"] as const) {
    const { adapter } = ordersUnderTest(profile, { link: profile === "direct" });
    const report = await runConformance(adapter);
    for (const r of report.results) console.log(`${r.ok ? "PASS" : "FAIL"} ${r.name}${r.error ? `: ${r.error}` : ""}`);
    ok &&= report.failed === 0;
  }
  return ok;
}
```

### Automating drops in Chromium

`enablePinning` defaults `trusted` to `(event) => event.isTrusted === true` (and `<apc-agents>`, `<apc-pets>` and `<apc-pin>` check `event.isTrusted` on their buttons), so a script running on the page cannot dispatch a synthetic `click()` or `PointerEvent` to arm or point an agent at data. In browser tests, synthetic `dispatchEvent` calls have `isTrusted: false` and are ignored:

- **In-page mark drags** (`<apc-agents>`, `<apc-pets>`, `<apc-pin>`): marks use pointer events (not HTML5 `draggable`), so drive real pointer input from the mark's centre to the target's centre (`page.mouse` in Playwright, or `Input.dispatchMouseEvent` over CDP; `Input.dispatchTouchEvent` for touch taps on mobile).
- **Dock drops**: send real HTML5 drag events over CDP (`Input.dispatchDragEvent`: `dragEnter`, `dragOver`, `drop`) with `APC_AGENT_TYPE` (`"application/x-apc-agent"`) and `agentDragPayload(agent, { hub, ticket })`.
- **Unit or DOM tests without real browser input**: pass `trusted: () => true` in `enablePinning` (test-only; never in production), or use `createTapPin` directly as `orders-conformance.ts` does in `page.mobile`.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/**
 * Automate a drop in Chromium over the Chrome DevTools Protocol (CDP — Playwright's `cdp.send` or a DevTools
 * WebSocket). `enablePinning` defaults to `event.isTrusted === true` (and `<apc-agents>`, `<apc-pets>` and
 * `<apc-pin>` check `event.isTrusted` on their buttons) so a page script cannot point an agent at data.
 * Synthetic `dispatchEvent(...)` calls have `isTrusted: false` and are ignored; drive real browser input
 * instead (or pass `trusted: () => true` in a non-production DOM test).
 */
export type CdpSend = (method: string, params: Record<string, unknown>) => Promise<unknown>;

/** Drag an in-page mark (`<apc-agents>`, `<apc-pets>`, `<apc-pin>`) to a `[data-focus]` target using pointer events. */
export async function cdpPinMark(cdp: CdpSend, from: { x: number; y: number }, to: { x: number; y: number }): Promise<void> {
  await cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x: from.x, y: from.y });
  await cdp("Input.dispatchMouseEvent", { type: "mousePressed", x: from.x, y: from.y, button: "left", clickCount: 1 });
  await cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x: to.x, y: to.y, button: "left", buttons: 1 });
  await cdp("Input.dispatchMouseEvent", { type: "mouseReleased", x: to.x, y: to.y, button: "left", clickCount: 1 });
}

/** Drop a dock agent onto a `[data-focus]` target at `(x, y)` using HTML5 drag events carrying `application/x-apc-agent`. */
export async function cdpDropFromDock(
  cdp: CdpSend,
  at: { x: number; y: number },
  drop: { agent: string; hub: string; ticket: string },
): Promise<void> {
  const data = { items: [{ mimeType: APC_AGENT_TYPE, data: agentDragPayload(drop.agent, { hub: drop.hub, ticket: drop.ticket }) }], dragOperationsMask: 2 };
  for (const type of ["dragEnter", "dragOver", "drop"]) {
    await cdp("Input.dispatchDragEvent", { type, x: at.x, y: at.y, data });
  }
}
```

### The Dock profile as built (1.0)

An app that claims 0.10.0 or later on the Dock profile also gives `dock.lifecycle` (`ApcDockLifecycleAdapter`), so the suite can put a grant into each state and reach the owner's endpoints. Without it, every Dock lifecycle check applicable to the claimed standard fails and says so.

| Member | |
|---|---|
| `dropAgent({ agent, ticket, hub, target })` | the person drops an agent, with the drag's `hub` string as the page read it, on `target` (one of `targets` when left out): what the page shows (`consent` with `allow()` and optional `code` when displayed there, `waiting` with the code, `connecting`, `pinned`, or `refused` with the error). A successful Allow returns `{ ok: true, grantId, code }`, read from the app's answer to the page. Every supplied code must match `/apc/pair`. `allow({ hub })` sends it with another hub, as a tampered page would |
| `readDropResponse(response, body)` | required when claiming 1.0 or later: read a response from `owner.drop` using the same outcome mapping as `dropAgent`, without sending another request or giving consent. The suite supplies the request body and uses this for a drop carrying a valid Connect consent nonce. Report `refused` only if no consent, code or grant was created; the private HTTP status and response format are the app's choice. The suite independently verifies that no `/apc/pair` was called |
| `connectDock(url, target)` (optional) | for APC 0.13 apps whose first drop sends `/apc/connect`: opens the `dock_connect` URL (with `#apc_connect=...`) returned by `hub.approveConnect` and returns the same consent outcome, including optional `code` when displayed there; a successful `allow()` supplies the code too |
| `allowCarriesHub` | whether the page's Allow carries the hub (true), or the server binds it to the consent (false) |
| `cancel(grantId)` | Cancel on the waiting card |
| `heartbeat()` | the page's heartbeat, a wake action |
| `advance(ms)` | the time seam: the app's clock moves forward, for `T_ack`, `T_connect`, `T_idle` and the stored expiry. Not for the hub call's deadline (M3), which runs on the real clock |
| `failCommits(fail)` | while true, the app's storage fails every write |
| `restart()` | the app's process dies with its calls open and comes back on the same storage |
| `idleMs` (optional) | the app's `T_idle`; left out, the app does not sleep and the dormant checks say so |
| `connectMs` (optional) | the app's `T_connect`, when shorter than the standard's 10 minutes (the default); the T_connect check holds the app to it |
| `dormancyMs` (optional) | long dormancy, for an app that sleeps: how long a grant stays dormant, counted from when it fell asleep, before it ends; left out, long dormancy is not checked |
| `hubDeadlineMs` (optional) | the app's deadline on a hub call, at most 10 000 ms (the default) |
| `owner` | the configured public origin (bare), the headers of the owner's session, and the four owner endpoints `drop`, `allow`, `heartbeat` (or `{ websocket: path }`) and `cancel`, each with a fresh body the app takes with a 2xx (Cancel's body pairs a new grant through `dock.hub` during the call) |
| `pairingDisabled()` | the same app with its dock configuration missing: its `fetch`, for `apc.json` |

#### Wiring dock.lifecycle

The three members that reach inside the app need it built for them from the start; each is a few lines once it is:

- **`advance(ms)`, the time seam.** Give the app one clock, `now: () => number`, and read every time limit of a Dock grant through it: `T_ack`, `T_connect`, `T_idle`, long dormancy, the pairing code's stored expiry, and the `now` of `DockConsent` and `ApcLinks`. The adapter keeps a skew and passes `now: () => Date.now() + skew`; `advance` adds to it. A time limit read from `Date.now()` directly cannot be moved, and its check fails.
- **`failCommits(fail)`.** The write that moves a grant out of handoff on the hub's `initialize` must be able to fail, and the app must then answer it with no result (HTTP 500 or JSON-RPC -32603) and stay in handoff. With a database, wrap the store so its writes throw while the flag is on; Orders, in memory, swaps its one commit for a function that throws.
- **`restart()`.** The process dies with its calls open and comes back on the same storage: close the page's streams, and build a new app instance on the same store. Everything a Dock grant needs (its state, its times, its code, the revoked hashes, the consents) must live in that store, not in the instance; what dies with the process (open waits, calls in flight) may live in memory.

The rest is the app's own routes: `dropAgent` and `cancel` call the person's endpoints as the page does, `heartbeat` is the page's heartbeat, `owner` names the four endpoints with a fresh body each, and `pairingDisabled()` is the same app built with no hub on its allowlist. [The minimum for the Dock profile](/docs/integrate#the-minimum-for-the-dock-profile) lists those routes.

Orders gives it like this: its clock is the app's `now`, a restart is a new app on the same store, its T_idle is the standard's 30 minutes, and a grant asleep 30 days ends.

From [orders-conformance.ts](https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/examples/orders-conformance.ts):

```ts
/** A grant in handoff, for an endpoint's body: dropped and allowed, the dock has not connected. */
async function waitingGrant(): Promise<string> {
  const agent = `ag_owner_${++drops}`;
  const { asked, route, drop } = await ask({ hub: HUB, agent, ticket: hub.ticket(agent), target: { kind: "order", id: "ord_1001" } });
  return (await call(route, { ...drop, consent: asked.consent })).grant_id as string;
}
/**
 * The Dock profile as built (APC 0.10): how the suite puts a grant into each state (the drop, Cancel, the
 * heartbeat, the clock, a failing store, a restart) and reaches the person's endpoints.
 */
const lifecycle: ApcDockLifecycleAdapter = {
  dropAgent,
  readDropResponse: async (response, body) => shownFor(await response.json() as Record<string, unknown>, "/api/drop", body),
  connectDock,
  // The page's Allow sends the drop again with the nonce, hub included: the app checks it against its allowlist again (M1).
  allowCarriesHub: true,
  cancel: async (grantId) => (await call("/api/cancel", { grant_id: grantId })).ok === true,
  heartbeat: async () => void (await call("/api/heartbeat")),
  advance: async (ms) => void (skew += ms),
  // Orders keeps its grants in memory, so a store that fails is its one write on `initialize` throwing.
  failCommits(fail) {
    const store = app as unknown as { commitConnection?: () => boolean };
    if (fail) {
      store.commitConnection = () => {
        throw new Error("the store is down");
      };
    } else delete store.commitConnection;
  },
  // The process dies and comes back on the same store.
  async restart() {
    await setOpen(false);
    app = new OrdersApp(config);
  },
  idleMs: T_IDLE_RECOMMENDED_MS,
  // A grant asleep 30 days ends (long dormancy).
  dormancyMs: LONG_DORMANCY_RECOMMENDED_MS,
  owner: {
    origin: ORIGIN,
    session: SESSION,
    drop: { path: "/api/drop", body: () => ({ hub: HUB, agent: `ag_owner_${++drops}`, ticket: hub.ticket(`ag_owner_${drops}`) }) },
    // A first drop's consent is asked on the dock_connect page (APC 0.13), so its Allow goes there.
    allow: {
      path: "/api/connect/dock",
      body: async () => {
        const { asked, drop } = await ask({ hub: HUB, agent: `ag_owner_${++drops}`, ticket: hub.ticket(`ag_owner_${drops}`) });
        return { ...drop, consent: asked.consent };
      },
    },
    heartbeat: { path: "/api/heartbeat", body: () => ({}) },
    cancel: { path: "/api/cancel", body: async () => ({ grant_id: await waitingGrant() }) },
  },
  // The same app with no hub to pair with: its apc.json must not list dock.
  pairingDisabled: async () => {
    const off = new OrdersApp({ ...config, hubs: [], store: newOrdersStore() });
    return (request) => off.fetch(request);
  },
  // A Direct agent (APC 0.12): the suite hands its URL to the hub's /apc/pair and checks it never goes live.
  directGrant: () => connect("direct"),
};
```

The stand-in hub plays the hub's side: it can hold `/apc/pair` (the grant is in flight), break the answer of `/apc/pair` (`mode`) or `/apc/confirm` (`confirmMode`) (redirects, a stalled body, the byte cap), forget a pairing (`/apc/confirm` then says `not_paired`), and approve without introducing itself.

### Apps on Cloudflare Durable Objects

`@tineira/apc-conformance/workers` runs a Durable Object on Node's SQLite, with fake pages for the person's WebSockets (`installWorkersStandIn`, `durableObjectRoom`), so the suite runs against your object with no network and no `workerd`. The reference apps do exactly that: [Pulse](https://github.com/tineira/agent-pointed-context/blob/main/apps/demo/test/conformance.test.ts) and [Signals](https://github.com/tineira/agent-pointed-context/blob/main/apps/signals/test/conformance.test.ts).

## Hub conformance

`hubConformance(adapter)` and `runHubConformance(adapter)` check a hub's app-visible MUSTs in process (no CLI) using `standInApp()` against an `ApcHubAdapter` (`fetch`, `ticket(agent)`, `pairingTicket(agent, origin)`, `approve(id, code?)`, `deny(id)`, `advance(ms)`, plus `pendingConnects()`, `approveConnect(id)`, `connectApproveEndpoint(id)`, `ownerFetch(input, init?)`, and `observeState()` required for H10; optional `exerciseAgent(agent)`, `requiresPairingCode`, `idle()`, and `reset()`). In APC 0.13, `pairingTicket(agent, origin)` issues a connect ticket via `/apc/connect` and owner approval (`pendingConnects`/`approveConnect`). It checks:

- **`apc.json` validation and H7**: missing, redirected, invalid, over-sized, cross-origin, dockless, or uncovered `mcp_url` manifests (via `mcp.path` and `mcp.endpoints`) are refused with HTTP 400; after 60 s an unreachable or 5xx `apc.json` re-fetches and never falls back to a stale cached copy (`apc_json_unreachable`).
- **Malformed bodies and ticket preservation**: malformed `/apc/pair` bodies are refused before spending the ticket or fetching `apc.json`; an invalid ticket fetches no `apc.json`; a valid connect ticket works once.
- **H9 (`/apc/pair` ticket rules)**: a drop ticket (`ticket(agent)`) sent directly to `/apc/pair` is refused with HTTP 400 `ticket_not_for_pairing` and left unspent (still accepted on `/apc/connect`); a connect ticket used with another `app.origin` or another `agent` is refused with HTTP 400 `ticket_origin_mismatch` and left unspent (still works for its bound `(agent, origin)`).
- **H10 (connect ticket containment)**: every string in the unauthenticated `/apc/connect` response (nested objects and arrays included, plus tickets decoded from `#apc_connect=...` fragments) is tried against `/apc/pair` before approval and must be refused. Unauthenticated approve calls are refused. `ownerFetch` adds a valid owner session while preserving the supplied headers: hostile `Origin` and `Sec-Fetch-Site` are checked independently, and the same transport must then succeed with same-origin headers. Missing either owner-route probe fails H10. The owner's approval returns the connect ticket inside the `dock_connect` URL; hub state and broadcasts (`observeState()`) never expose it, and a second approval fails. The fixture tests must catch removal of only the CSRF guard and independent pre-approval ticket leaks in alternate fields, nested fields, and fragments.
- **Pairing code (`PAIR-2`, `CODE-2` never echoed)**: normalizes submitted and owner codes (hyphens, spaces, case, and Crockford `O`/`I`/`L` aliases), acknowledges with `pairing_code: "required"`, refuses codeless `/apc/pair` when `requiresPairingCode` is set (recording a declared policy note otherwise; the reference hub requires codes), leaves attempt counts untouched on missing/malformed `approve` codes, and never echoes the code in `/apc/pair`, pending or paired `/apc/confirm`, `approve`, or app requests.
- **Give-back (`PAIR-2`)**: a 5th wrong code, pending expiry, or deny sends `/apc/revoke` for the grant URL.
- **H1**: no MCP calls (`initialize`, `tools/list`, `tools/call`) before owner approval with the code or during the in-flight `approving` window (including agent calls when `exerciseAgent` is provided, and extra wrong codes while approving); `initialize` is first after approval.
- **H2**: `/apc/confirm` expires overdue pending requests before answering `not_paired`, leaves the ticket unspent, and gives the grant back.
- **H3**: `/apc/pair` replaces an unapproved pending request for `(agent, origin)`, resets its wrong-code count to 0, gives back only a different URL asynchronously, and never replaces an approving or paired pairing.
- **H5**: HTTP 404 on `initialize` (and post-approval agent calls when `exerciseAgent` is provided) ends the pairing with a `pairing_ended` tombstone, answers `not_paired` on `/apc/confirm`, and allows re-pairing.
- **Redirects**: the hub never follows a 3xx redirect on `apc.json`, MCP `initialize`, or `/apc/revoke` (whether using `redirect: "manual"` or `"error"`).

Rules that need the dock UI (`CODE-2`'s "never shows" in dock state or page sockets, `DROP-1` no secret in the drag, and `TM-1` trust-model UI warnings and unverified markings), pairing-cap accounting in `H3`/`H5`, and agent-tool relays (`H4`, `H5` agent `relay()` errors, `H6`, plus post-approval agent gating/404 if an adapter omits `exerciseAgent`) are **reference behaviour, not conformance-tested in 1.0** (proven by `apps/dock/test`).

`ApcHubAdapter` still supplies hub actions, not an app-code reader. Its code normalization, never-echoed and codeless checks submit codes with `/apc/pair` before testing approval or confirmation. The `requiresPairingCode` policy is unchanged: true requires codeless pairing to fail; otherwise acceptance records the declared policy note.

## What passing means

Passing says your app speaks the core the way agents and hubs expect, on the profile you ran. It says nothing about your data, your access rules or your page beyond the adapter's answers: write the adapter against the real thing (your page's real handlers, your real storage), not a model of what it should do.

---

The APC standard is at 1.1.1, frozen and changing only by the versioning and compatibility policy (/docs/spec#versioning-and-compatibility). This page as HTML: /docs/conformance. Text CC BY 4.0, code MIT. Source: https://github.com/tineira/agent-pointed-context/blob/main/apps/dock/src/docs/pages/conformance.md
