# CFP — API Reference

Complete HTTP + wire-surface reference for every service in this monorepo,
transcribed from the deployed source of truth (each service's `src/`, its test
batteries, and `packages/shared/src`).

> **How to read this doc.** Services are documented in the order a request
> travels: customer traffic enters at the **gateway**; serving work crosses the
> **worker rail** to supervisors; fleet bookkeeping lives in the
> **control-plane**; humans drive the **portal** (customer web app) and the
> **ops-dashboard** (operator console). Trust boundaries are noted per
> service. Anything not written here is not part of the contract.

## Service map

| Service | Package | Default listen | Audience | Auth |
|---|---|---|---|---|
| gateway | `@cfp/gateway` | `CFP_HOST:CFP_PORT` (127.0.0.1:8787) | **Customers** (public; Cloudflare terminates TLS in prod) | API key per request |
| gateway (worker rail) | `@cfp/gateway` | `CFP_RAIL_HOST:CFP_RAIL_PORT` (127.0.0.1:8790) | Supervisors | Shared secret + optional mandatory mTLS |
| supervisor | `@cfp/supervisor` | dials OUT to the rail | Internal only | — |
| control-plane | `@cfp/control-plane` | `CFP_HOST:CFP_CP_PORT` (127.0.0.1:8791) | Operators, gateway relays | **None** — bind address is the trust boundary |
| portal | `@cfp/portal` | see §5 | Customers (HTML) + webhooks + admin API + public `/docs` static reference site | Session cookies / webhook secrets / `x-admin-token` / `/docs` is anonymous |
| ops-dashboard | `@cfp/ops-dashboard` | `CFP_OPS_HOST` (falls back to `CFP_HOST`) + `CFP_OPS_PORT` (127.0.0.1:8793); peers via `CFP_CP_URL` / `CFP_PORTAL_URL`; full env list in §4 | Operators (HTML) | CSRF cookie on actions |

> **reconciler** (`@cfp/reconciler`) is currently a placeholder stub
> (`console.log('[reconciler] placeholder')`) — no wire surface exists yet,
> so it has no section here.

Shared vocabularies (model pins, rate card, ledger rows, frame envelope) live
in `packages/shared/src` and are pinned once in §6.

---

## 1. Gateway — customer API

Files: `services/gateway/src/{http-server,anthropic,admission,api-keys,images,config}.ts`

### 1.1 Endpoints

| Method & path | Purpose |
|---|---|
| `POST /v1/messages` | Create a message (text, images, tools, conversation resume). Streaming or JSON. `/v1/messages?beta=true` is accepted identically. |
| `GET /healthz` | Liveness snapshot. No auth. |

Anything else answers `404 not_found_error`. Every error body is Anthropic-shaped:

```json
{ "type": "error", "error": { "type": "<category>", "message": "<human-readable>" } }
```

### 1.2 Authentication

Accepted headers (checked in this order):

```
x-api-key: <key>
Authorization: Bearer <key>
```

Key records live in the shared `api-keys.json`
(`{"keys":[{key, customerId, label?, expiresAt?, balanceMicroUsd?}]}`),
hot-reloaded within ~10 s of the portal editing it — no restarts.

Request-time gates, in order (all refusals charge nothing):

1. Unknown key → `401 authentication_error` — `"missing or invalid API key"`.
2. `expiresAt` in the past → `403 authentication_error` — `"API key expired — renew in the customer portal"`.
3. Credit keys (carrying `balanceMicroUsd`) must hold a **positive effective
   balance to START a turn**: `balanceMicroUsd − Σ(usage-ledger spends of this key)`.
   Zero-or-less → `403 authentication_error`
   (`Credit exhausted ($X.XXXX) — top up in the customer portal`). The ONE admitted
   turn may overshoot a near-zero balance by at most its own final cost
   (deduction is post-turn, honestly visible as a small negative). Ledger unreadable → fail CLOSED `503 overloaded_error`.
4. Legacy keys without `balanceMicroUsd` keep pure time-based semantics.

### 1.3 Request body — `POST /v1/messages`

Validated by `anthropic.parseRequestBody`; malformed input throws helpful
errors naming exact JSON paths. Fields:

| Field | Rule |
|---|---|
| `model` *optional* | String matching `MODEL_PIN_RE` (`sonnet\|opus\|fable\|claude-(sonnet\|opus\|fable)-N-N`). Family aliases resolve to the canonical current generation before billing (`CANONICAL_FAMILY_PIN`: sonnet→`claude-sonnet-5-5`, opus→`claude-opus-5-5`, fable→`claude-fable-5-2`). Omitted → `claude-sonnet-5-5`. RE-valid pins outside today's rate card get an honest `400 invalid_request_error` naming the supported set. The response's `model` field echoes the client-declared value verbatim. |
| `messages` **required** | Non-empty array of `{role, content}`; `role` any string (first message conventionally `user`); `content` a string or an array of typed parts. Content parts: `text {type,text}`, `image {type,source}` (see §1.6), `tool_use {id,name,input?}` (replayed assistant calls round-trip through the taught fenced syntax; results reconcile positionally, ids don't travel through the prompt text), `tool_result {tool_use_id,content,is_error?}` (content string or array of TEXT parts only — inline images inside tool_result aren't supported yet). Unknown part types pass validation untouched and render visibly as `[part:<type>] <JSON>` (forever-green path). Stateless transcripts render `[role]\n<text>` joined `\n\n`; message arrays join text parts with `\n`. |
| `stream` *optional* | `true` → SSE response. Default `false`. |
| `max_tokens` *optional* | Integer ≥ 1. Values above the platform ceiling (`CFP_MAX_OUTPUT_TOKENS`, default 64,000) refuse loudly naming both numbers (never silently clamped below intent). Omitted → served AT the ceiling. Travels per-turn to the real CLI which enforces it natively. |
| `system` *optional* | String or array of `{type:"text",text}` parts (joined with `\n`). Rides the wire as `TurnRequest.systemText` → native CLI `--append-system-prompt`. |
| `tools` *optional* | Array of `{name, description?, input_schema?}`. Names must match `^[a-zA-Z0-9_-]{1,128}$` and be unique within the request. Declared names become THIS turn's scanner gate: fenced call candidates naming anything else degrade to literal text. Tool calls ride a TAUGHT TEXT PROTOCOL: one fenced block per call, opening marker at the beginning of its own line — `` ```tool-use `` newline `{​"name":…,"arguments":{…}}` newline `` ``` ``. In prompts, tool definitions render compactly as `- name: {"description","input_schema"}` under a fixed `[tools]` head (definitions, blank line, usage rules with the fence-syntax example, `tool_choice` ruling LAST — stable ordering maximizes upstream prompt-prefix cache hits). |
| `tool_choice` *optional* | `{type:"auto"\|"any"\|"tool", name?}`. With `"tool"`: `name` REQUIRED and must exist among declared `tools`. Rendered rulings: auto→"Prefer calling a tool whenever doing so beats answering directly.", any→"You MUST answer by calling at least one of the available tools.", tool→`You MUST answer by calling the tool named "<name>".` |
| `metadata.conversation_id` *optional* | String matching `^[A-Za-z0-9][A-Za-z0-9_-]{5,63}$`. Presence switches the turn into CONVERSATION MODE: sticky downstream identity becomes `<customerId>:<conversationId>` (colons legal in `DOWNSTREAM_ID_RE`), only the NEWEST user message renders (the rest live in that CLI session's memory), `resume:true` rides the wire, and only the newest user message's images ride along. Absent = STATELESS: whole transcript, every image, fresh session. Conversation turns require ≥ 1 `user` message. |
| unknown top-level fields | Ignored predictably (forever-green doctrine at the body level too). Requests above the transport cap refuse with both numbers named (see §1.7). |

### 1.4 Routing, holding, and dispatch (request lifecycle)

Admission precedes anything else; **nothing rejected here is ever billed**
(billing happens exclusively post-turn):

1. **Body read** (`readBody`): bodies over `CFP_MAX_BODY_BYTES` abort the
   request with an actionable message naming both numbers.
2. **Image admission** (§1.6) happens BEFORE hold/dispatch/billing, so URL
   sources fetch EXACTLY ONCE and holds can never lose resolution.
3. **Billed-model resolution**: aliases resolve to the canonical pin; pins we
   can't bill → honest 400.
4. **F2 output ceiling**: `max_tokens > CFP_MAX_OUTPUT_TOKENS` → honest 400;
   otherwise resolved ceiling = declared value or platform default.
5. **v1.3.1 admission gates** (pure core, UTC-day ledger buckets):
   per-key concurrency cap counting in-flight AND held turns (default 2);
   optional per-key daily spend ceiling µ$ (default off); global hold-line capacity
   (memory guard). Every rejection is
   `429 rate_limit_error` + integer `Retry-After` computed from state — never
   invented constants:
   | Reason | Meaning | Retry-After |
   |---|---|---|
   | `key_concurrency` | Key already has its cap of simultaneous turns riding | ~5 s |
   | `daily_budget` | Optional daily USD ceiling hit (pacing bound ONLY — prepaid balance untouched) | seconds until UTC midnight |
   | `queue_full` | Global hold line at capacity | ~10 s |
   | `hold_expired` | Waited out the whole hold window without an awake slot | from current fleet ETA |
   | `seat_unresolved` | Seats mode: user exists in the billing world but no routable seat yet (never synced / awaiting account / awaiting worker wiring). INSTANT honest 429 — never parked | poll-honest, floor 5 s |
6. **Routing**: seats mode polls the control-plane `GET /seats/assignments`;
   the seat's assigned account IS the home (cold-start awaits one sync first).
   Legacy mode uses BindingMap stickiness on `<customerId>[:conversation]`.
   The home identity is fixed only at real dispatch time.
7. **Hold line** ("human pacing"): nothing rideable right now → the request
   parks FIFO up to `CFP_HOLD_MAX_MS` (default 60 s) waiting for a waking
   serving slot, re-checked on every fresh supervisor pulse plus a 1 s safety
   tick; expiration answers `429 hold_expired` with a from-truth Retry-After
   ("at-expiry price tag"). Client disconnects during the hold clean up silently.
8. **Dispatch**: PendingTurn registers BEFORE the SSE 200 head writes; the
   watchdog arms ONLY at the real dispatch moment
   (holds never burn turn budget) at `CFP_TURN_TIMEOUT_MS` (default 630 s).

### 1.5 Responses

Streaming (`stream:true`) — SSE (`text/event-stream`,
`cache-control:no-cache`, `connection:keep-alive`), framed `event:` / `data:`.
Event family, with LIVE tool-call parsing through one TurnAssembler/ToolStreamScanner per turn:

| Event | Shape |
|---|---|
| `message_start` | `{"type":"message_start","message":{"id":"msg_gw_…","type":"message","role":"assistant","model":<echo>,"content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}` — followed EAGERLY by `content_block_start` index 0 type text, so plain-text replies stream immediately. |
| `content_block_start` | `{index,content_block:{type:"text"\|"tool_use"}}` — tool_use carries `id:"toolu_gw_…"`,`name`. Follow-up text blocks open lazily at incrementing indexes after each confirmed tool call. |
| `content_block_delta` | `{index,delta:{type:"text_delta",text}}` or `{delta:{type:"input_json_delta",partial_json}}` — ONE frame carries the COMPLETE compact argument JSON per confirmed call (concatenate then parse exactly once). Plain text streams eagerly; candidate fence-tail regions hold back briefly until decided, then flow or resolve into proper multi-block stories. |
| `content_block_stop` | `{index}` — only genuinely-open blocks ever emit a closer; NONE is fabricated after a trailing tool call. |
| `message_delta` | `{"delta":{"stop_reason":"end_turn"\|"tool_use","stop_sequence":null},"usage":<usage-wire>}` — stop_reason derives PURELY from assembled content parts (one scanner verdict drives BOTH transports). |
| `message_stop` | `{"type":"message_stop"}` |
| `error` | `{"type":"error","error":{"type":"api_error"\|"overloaded_error","message":"upstream: <reason>[:detail]"}}` followed by `message_stop`. Failure honesty: any held-back scanner region flushes as literal text BEFORE the error frame; mid-fail the surviving frame ordering is conservation-pinned (nothing vanishes beneath the error). |

Non-streaming — single JSON "message":

```json
{
  "id": "msg_gw_…",            // same namespace as streaming
  "type": "message",
  "role": "assistant",
  "model": "<client-declared model, echoed verbatim>",
  "content": [
    { "type": "text", "text": "…" },
    { "type": "tool_use", "id": "toolu_gw_…", "name": "get_weather",
      "input": { "city": "Oslo" } }
  ],
  "stop_reason": "end_turn",   // or "tool_use" iff ≥1 valid parsed call
  "stop_sequence": null,
  "usage": { … }
}
```

`usage` wire (`usageWire`, always exact upstream-reported counters):
`input_tokens`, `output_tokens`, plus `cache_read_input_tokens` /
`cache_creation_input_tokens` whenever those were reported upstream.

Non-streaming failures answer `502 api_error`
(`{"type":"error","error":{"type":"api_error","message":"upstream: <reason>"}}`)
or `503 overloaded_error` (`rejected_queue_full` / `acquire_timeout`).

### 1.6 Images (v2)

Sources validated by `anthropic.imageOf` against
`RAIL_IMAGE_MEDIA_TYPES` (`image/png`, `image/jpeg`, `image/webp`, `image/gif`):

- `base64`: strict alphabet `A-Za-z0-9+/` + optional `=` padding, SINGLE LINE
  (newlines would break the one-user-message-per-line stdin transport — refused
  at admission where the request charges nothing). Non-empty.
- `url`: http(s) fetched ONCE at admission with its own deadline; identified
  purely BY MAGIC BYTES (an arbitrary remote header never picks our vocabulary).

`resolveImages` laws:

- numeric bounds at admission only, F2 doctrine: violations throw helpful
  indexed errors naming both values/knobs;
- magic-byte sniffing on EVERY payload: mismatch declares itself vs bytes →
  honest refusal listing both values (sniff WINS or refuse; never silent
  rewrite). Sub-sniffing-minimum (<12 byte) payloads may trust the declared type;
- URL sources are always sniffed alone;
- resource honesty: capped incremental reads ABORT mid-stream past the ceiling;
- limits: ≤ `CFP_IMAGE_MAX_COUNT` (8) images per request — beyond → indexed
  refusal; ≤ `CFP_IMAGE_MAX_BYTES` (5 MiB) DECODED binary bytes per image; URL
  fetch deadline `CFP_IMAGE_URL_TIMEOUT_MS` (10 s);
- ownership split riding the parse: STATELESS ships every transcript image in
  appearance order; CONVERSATION ships only the newest user message's slice
  (earlier ones live in that session's memory; resending would duplicate).

### 1.7 Errors and status codes (complete)

| Status | Type | When |
|---|---|---|
| 400 | `invalid_request_error` | Malformed JSON; body-shape violations with exact paths; unsupported model names; `max_tokens` above ceiling (both numbers named); image rule violations (indexed, knobs named); bad `conversation_id`; dangling `tool_choice.name`; tools/tool_choice shape errors |
| 401 | `authentication_error` | Missing/unknown API key |
| 403 | `authentication_error` | Key expired; credit exhausted |
| 404 | `not_found_error` | Unmatched method/path (echoes `<METHOD> <path>`) |
| 429 | `rate_limit_error` | Admission/pacing rejection family — ALWAYS with integer `Retry-After` header (§1.4) |
| 500 | `api_error` | Internal gateway error (logged loudly, uncaught) |
| 502 | `api_error` | Upstream failure mid-turn (non-stream form) |
| 503 | `overloaded_error` | Upstream queue-full/acquire-timeout; billing-store temporarily unreadable (fail-closed paths); gateway restarting (held requests get fast honest 429 Retry-After 1) |

### 1.8 Billing semantics (customer-visible contract)

- Post-turn settlement ONLY: admission guarantees positive balance; whatever
  the turn truly cost lands after it ends, from the SUPERVISOR-reported usage
  numbers, priced at `SALE_RATE_CARD[billedPin]` with `"split"` cache-write
  policy (ephemeral 5m/1h each at their own −50% list rates; sum ⇒ exactly
  Anthropic-list − 50%). See §6.2 for the card.
- One row per settled turn in the append-only gateway-owned usage ledger
  (JSONL; rows never edited/deleted — corrections append compensation rows).
  Effective balance is always `(key.balanceMicroUsd) − Σ(ledger rows of key)`.
- Failed turns bill HONESTLY: IF genuine upstream-reported usage was observed
  before death (`TurnFail.usage`, never estimates) the partial cost bills and
  the row stamps `partialReason`; zero-cost snapshots skip the row entirely.
  Failure-blind failures (queue rejects, warmup not ready, instant death) bill
  nothing — margin absorbs.
- Rejected requests charge nothing (all §1.4 gates).

### 1.9 Environment/configuration (defaults)

Every knob is validated loudly at boot (`intStrict` crashes the process rather
than half-working). Customer-facing subset:

| Env | Default | Meaning |
|---|---|---|
| `CFP_HOST` / `CFP_PORT` | 127.0.0.1 / 8787 | Customer-facing listener (TLS terminates at Cloudflare in prod) |
| `CFP_RAIL_HOST` / `CFP_RAIL_PORT` / `CFP_TLS_CERT/_KEY/_CA` | 127.0.0.1 / 8790 / unset | Dedicated mTLS rail server; unset = lab mode (rail rides main port, secret-only) |
| `CFP_WORKERS_PATH` / `CFP_GATEWAY_SECRET` | /workers / "" | WS upgrade path + shared worker secret |
| `CFP_API_KEYS_FILE` / `CFP_API_KEYS` / `CFP_USAGE_LEDGER_FILE` | null / null / ./usage-ledger.jsonl | Keystore(s) (hot-reloaded) + append-only billing ledger |
| `CFP_MAX_BODY_BYTES` | 32 MiB | Raw pre-parse body cap |
| `CFP_MAX_OUTPUT_TOKENS` | 64,000 | Platform output-token ceiling (§1.3 `max_tokens`) |
| `CFP_IMAGE_MAX_COUNT` / `CFP_IMAGE_MAX_BYTES` / `CFP_IMAGE_URL_TIMEOUT_MS` | 8 / 5 MiB / 10 s | Image admission caps |
| `CFP_TURN_TIMEOUT_MS` / `CFP_HOLD_MAX_MS` / `CFP_QUEUE_CAP` / `CFP_KEY_CONCURRENCY` / `CFP_KEY_DAILY_BUDGET_USD` / `CFP_PULSE_STALE_MS` | 630 s / 60 s / 256 / 2 / 0 (off) / 45 s | Pacing/admission knobs (§1.4) |
| `CFP_ROUTING_MODE` | legacy | `legacy` BindingMap stickiness \| `seats` control-plane seat layer (requires `CFP_CONTROL_PLANE_URL`) |
| `CFP_SEAT_POLL_MS` / `CFP_SEAT_STALE_MS` / `CFP_SEAT_STANDBY_MAX` / `CFP_SEAT_UNFUNDED_GRACE_DAYS` / `CFP_SEAT_SWEEP_INTERVAL_MS` | 2 s / 30 s / 0 (off) / 0 (off) / 300 s | Seats-mode internals; unfunded-grace sweep releases seats whose wallet stayed empty past N days via CP `POST /seats/:seatId/release` (cause `unfunded_grace_expired`) |
| `CFP_CONTROL_PLANE_URL` / `CFP_CONTROL_PLANE_SLOT_ID` / `CFP_CONTROL_PLANE_TIMEOUT_MS` | null / null / 2 s | Quarantine→CHALLENGE relay (§2.3), seat polling, grace sweep dial-out |

---

## 2. Worker rail — gateway ⇄ supervisor WebSocket protocol

Canon: `packages/shared/src/protocol.ts` (`PROTOCOL_VERSION = 1`).

### 2.1 Transport

- Supervisors dial `GET <workersPath>` as a WebSocket upgrade, authenticated
  with `Authorization: Bearer ${CFP_GATEWAY_SECRET}`.
- When ALL of `CFP_TLS_CERT/_KEY/_CA` are set, a DEDICATED HTTPS server owns
  the upgrade with MANDATORY mutual-TLS (`requestCert` + `rejectUnauthorized`);
  customers never touch that port, and its plain-HTTP requests answer
  `404 "rail is websocket-only\n"`. Without TLS material (lab mode) the rail
  rides the main customer port with the bearer secret only.
- Messages are JSON text frames. Every frame is the envelope
  `Frame<K,P> = { v: 1, ts: epochMs, k: K, p: P }`; `decodeFrame` accepts only
  strings parsing to an object with `v === 1` and string `k`, else drops them.

### 2.2 Frame vocabulary (`GatewayFrame`)

Gateway-bound, sent right after connecting:

```ts
Frame<"hello", WorkerHello>          // {workerId, pid, claudeVersion}
```

Supervisor-bound, periodic:

```ts
Frame<"heartbeat", HealthSnapshot>   // v:{...}, phase:"boot"|"warming"|"ready", pool:{inflight,queued,maxConcurrent},
                                      // registry:{customers}, counters:{turnsStarted,turnsCompleted,
                                      // turnsFailed,resumeFallbacks}, warmup report, quarantine?:{detectedAtMs}
Frame<"worker.pulse", WorkerPulse>  // PACER truth (Session v1.3.1 human pacing). ADVISORY scheduling info
                                     // for hold-vs-429 admission + Retry-After honesty; push stays unchanged.
                                     // st:"awake"|"pause"|"sleep", free:N (execution slots RIGHT NOW),
                                     // nxt:null|ms-to-next-event, maxc (current ceiling), pace?:0..100 (info only)
Frame<"worker.quarantine", WorkerQuarantine>
                                     // fired at FIRST QUARANTINE_SIGNATURE sighting (frozen stamp),
                                     // re-emitted verbatim after every reconnect; {detectedAtMs, requestId?,
                                     //  incident?:QuarantineIncident} — treated idempotently per distinct stamp
```

Gateway → supervisor:

```ts
Frame<"turn.request", TurnRequest> // THE unit of customer work. Fields:
                                   // requestId (gw-minted, unique), customerId ("<cust>"|"<cust>:<conv>",
                                   // matches DOWNSTREAM_ID_RE), prompt (rendered §1.3), resume:boolean
                                   // (conversation mode), model:BILLED canonical pin (--model downstream),
                                   // maxOutputTokens:F2 ceiling, images?:RailImage[] (pure-base64,
                                   // media-type-sniffed — never urls/data-url prefixes, pruned when empty
                                   // for wire byte-parity), systemText?:string (native --append-system-prompt;
                                   // null/"" omit entirely), meta?:Record<string,string> (free-form, e.g. key label)
```

Both directions (supervisor → gateway on `turn.event`):

```ts
turn.event p={k:"turn.begin", requestId, ts, claudeSessionId?}
turn.event p={k:"turn.delta",  requestId, ts, text}                 // incremental assistant text
turn.event p={k:"turn.end",     requestId, ts, claudeSessionId, text, usage:TurnUsage, wallMs?}
                                           // text = FULL accumulated authoritative assistant text
turn.event p={k:"turn.fail",    requestId, ts, reason, detail?, retriable?,
              usage?:TurnUsage}             // F1 honesty law: GENUINE upstream-reported numbers observed
                                            // before death ONLY (never estimates); absent = bill nothing
// reason ∈ {rejected_queue_full | acquire_timeout | warmup_not_ready | cli_error | internal_error}
```

`TurnUsage`:
`inputTokens?`, `outputTokens?`, `cacheReadTokens?`, `cacheCreationTokens?`,
`cacheCreation5mTokens?`/`cacheCreation1hTokens?` (exact upstream split as
priced), `costUsd?` (CLI-computed).

Late frames route by `requestId` against the pending map; duplicates and stale
frames are dropped. Late duplicate `turn.end`s can never double-charge
(pending deletion guards).

### 2.3 Quarantine doctrine (milestone D)

Sighting
`QUARANTINE_SIGNATURE = "Your account can't receive replies from Claude"`
in TURN BODY TEXT (not headers) or CLI stderr means: business death. Per-stamp
facts:

- Enforcement is ALWAYS local+rail-only (mark sick link quarantined: complete
  pushed turns gracefully; never dispatch NEW customer work onto it). The supervisor NEVER refuses turns.
- Best-effort phone-homes to the control-plane (owner ruling Nov 18; failure
  logs LOUDLY and never blocks serving), ALL idempotent by `detectedAtMs`:
  1. `POST /slots/${slotId}/state` `{to:"CHALLENGE", note:"gateway auto: quarantine signature sighted upstream (…)"}`
     — expected replay noise `422 illegal transition …` warn-only;
  2. `POST /slots/${slotId}/incidents` carrying the detection-time ban-forensics
     freeze-frame packet (§3.1.6): 201 = new record stored, 200 = stamp replay.
     Deliberately independent of (1): a 422 there must never swallow a fresh incident.
- Plus the SEAT FAILOVER relay (`relaySeatFailover`, seats mode only): for each
  seat homed on the sick worker — truth-first `syncNow()`, then
  `POST /seats/:seatId/detach {cause:"quarantine"}`,
  `POST /seats/claim {userId}` (idempotent rebind honoring MIN_SPARE floors;
  fires even after warned detaches), healed `syncNow()` last.
- Sleep-aware rotation (R4, `CFP_SEAT_STANDBY_MAX > 0` both nodes): rides
  landing on one of the user's RESERVED standby accounts uniformly trigger
  `POST /seats/:seatId/rotate {toAccountId}` — truth-first/post-truth syncNow()
  sandwich, atomic role swap, tolerance-map logging.

---

## 3. Control-plane REST API

File: `services/control-plane/src/{index,types,store,seats}.ts`. Battery:
`api.test.ts`.

Internal operator surface. Bind address is the only trust boundary:
`CFP_HOST` (loopback default), port `CFP_CP_PORT` (8791). There is NO auth
anywhere in this service. Files on disk are the source of truth
(`slots.json` / `incidents.json` / `seats.json` survive kill+restart).

Every endpoint speaks JSON. Path params are URL-decoded regex captures.
Catch-all shapes: unmatched → `404 {"error":"<METHOD> <path-stripped-of-query>"}`;
handler throw → `500 {"error":"internal error"}`.

Config crash-law: knob garbage (negative/non-int) refuses boot
(`config: <NAME> must be a non-negative integer (got '<raw>')`):
`CFP_SLOTS_FILE` / `CFP_INCIDENTS_FILE` / `CFP_SEATS_FILE` (defaults under
`/root/cfp-etc/`), `CFP_SEAT_MIN_SPARE_ABS` (0=off; MIN_SPARE free-account
floor), `CFP_SEAT_STANDBY_MAX` (0 = R4 standby-pack KILL-SWITCH), per-cause
rest cooldowns `CFP_SEAT_REST_MS_QUARANTINE/_EXHAUSTION/_OPS_ROTATION/_MANUAL/
_SLEEP_ROTATION` (all 0 = claimable again immediately).

Identity vocabularies: `SLOT_ID_RE ^[a-z0-9][a-z0-9-_]{0,63}$`;
`STATE_RE ^(UNVERIFIED|VERIFIED_IDLE|PRODUCTION|CHALLENGE|REVERIFY)$`;
`USER_ID_RE` = `DOWNSTREAM_ID_RE` (§6.3). Server mints seat ids as
`seat_<18 hex>`.

### 3.1 Endpoints

#### 3.1.1 `GET /healthz`
`200 {ok:true, service:"control-plane", slots:N, seats:N (incl. terminal audit rows), incidents:N}`.

#### 3.1.2 `GET /slots`
`200 {slots: [SlotRecord…]}`. No query params. Sole supply feed for the ops-dashboard.

#### 3.1.3 `POST /slots` — create a slot

One friend-account persona (account+VM+IP triple). Body:
`{slotId (SLOT_ID_RE), personaLabel (REQUIRED — never real PII),
docsCountry (ISO-2, uppercased: `"fr"`→`"FR"`), vmServerId?, vmIp?, proxyExitIp?, workerId?}`.

Ladder: `400 {"error":"bad slotId"}` → `400 {"error":"personaLabel required"}`
→ `400 {"error":"docsCountry must be ISO-2"}` → `409 {"error":"slotId exists"}`
(registry ids are forever) → `201` returns the created record. New rows always
start `UNVERIFIED` with birth history `{at, from:null, to:"UNVERIFIED", note:"created"}`.

#### 3.1.4 `POST /slots/:id/state` — guarded lifecycle move

Body: `{to: SlotState, note?}`. Ladder: `404 {"error":"unknown slot"}` →
`400 {"error":"bad state '<value>'"}` → `422
{"error":"illegal transition <from> -> <to>","allowedFrom":"<current-state>"}`
→ `200` updated record with the move appended to `stateHistory`
(`{at,from,to,note?}`).

State machine (money guard: no UNVERIFIED account skips verification straight
into PRODUCTION; quarantine loop PRODUCTION→CHALLENGE→REVERIFY→PRODUCTION is legal):

```
UNVERIFIED:    -> VERIFIED_IDLE
VERIFIED_IDLE: -> PRODUCTION, UNVERIFIED, CHALLENGE
PRODUCTION:    -> CHALLENGE, REVERIFY, VERIFIED_IDLE
CHALLENGE:     -> REVERIFY, VERIFIED_IDLE, PRODUCTION
REVERIFY:      -> PRODUCTION, CHALLENGE, VERIFIED_IDLE
```

Ownership law: seat logic READS slot states but never writes them — all moves
flow through this route (ops scripts + gateway quarantine relay).

#### 3.1.5 `GET /incidents?limit=N` — ban timeline

Only bounded-list read: `limit` clamped to 1–1000 (regexp-matched, default
200). `200 {incidents:[IncidentRecord…]}`, ordered newest-first by
`detectedAtMs` (tiebreak receivedAt desc). Record identity is the immutable
`(slotId, detectedAtMs)` pair — the "why did this account die" evidence
timeline. Full packets per slot are stub-compacted beyond 32 (packet dropped,
timeline headline kept forever; nothing deleted).

#### 3.1.6 `GET|POST /slots/:slotId/incidents`

Producer: the gateway/supervisor quarantine relay (§2.3). Body:
`{detectedAtMs: positiveInt REQUIRED (SUPERVISOR clock), workerId?, requestId?,
incident?: QuarantineIncident freeze-frame}`.

- `404 {"error":"unknown slot"}`; `400 {"error":"detectedAtMs must be a
  positive epoch-ms integer"}`.
- Freeze-frame gate: stores `incident` verbatim iff `v===1 && windows` object;
  failing shape STORES AS STUB + loud warn (timeline integrity beats packet purity).
- `201` = new record (returns it); `200` = SAME-STAMP REPLAY — replaces its own
  record, never duplicates. Response records also carry `receivedAt`
  (gateway clock) for drift diagnostics.

#### 3.1.7 `GET /seats`
`200 {seats:[SeatRecord…]}` INCLUDING terminal audit rows (empty store:
`{"seats":[]}`). No query params.

#### 3.1.8 `GET /seats/assignments` — routing-truth poll

THE surface the gateway's SeatTable polls in seats mode. No params.
Deterministic (`userId asc`, tiebreak `seatId asc`):

```json
{
  "revision": 7,
  "mappings": [{
      "userId": "...", "seatId": "seat_...", "accountId": "<slotId>",
      "workerId": "…|null",
      "status": "active",
      "standbys": [{ "accountId": "…", "workerId": "…|null" }]
  }]
}
```

ONLY active open seats appear (awaiting users hold nothing); `workerId`
degrades honestly to `null` if the registry join vanished (drift-honesty —
never invented); `revision` bumps on mutation and survives respawns; frozen
packs are still reported while the standby kill-switch reads 0 (ignored ≠ hidden).
Empty store is exactly `{"revision":0,"mappings":[]}`.

#### 3.1.9 `POST /seats/claim` — idempotent-per-user

Body `{userId}` (`400 {"error":"bad userId"}` on `USER_ID_RE` violation).
Lifetime law DR-1: at most ONE OPEN seat per userId (open = active or
awaiting_account); release is TERMINAL and later claims mint a NEW seatId
(released rows never resurrect, kept forever as audit).
`401`…`409` don't exist here: outcome unions carry semantics —

- `201` — a ROW WAS MINTED: `{ok:true, outcome:"created_active"|"created_awaiting", seat}`
- `200` — NOTHING minted: `{ok:true, outcome:"open_active"|"still_awaiting"|"rebound", seat}`

Claim truths: fresh claims eligible ONLY slots in
CLAIMABLE_SLOT_STATES (`VERIFIED_IDLE`,`PRODUCTION`); AWAITING seats holding
live packs rebound FROM THEIR OWN PACK FIRST (floor-free promotion, outcome
`rebound`); dry/floor-blocked pools persist a waiting row (that's the
`created_awaiting`/`still_awaiting` pair); retries NEVER mint dupes; pool pick
order: longest-rested first (`restUntil ?? 0` asc), oldest createdAt second,
slotId lexicographic final tiebreak.

#### 3.1.10 `POST /seats/reserve` — R4 standby fill

Body `{userId, count?=1}`. Gates FIRST: `400 {"error":"bad userId"}` →
`400 {"error":"count must be a positive integer"}`. Reservations touch NOTHING
on refusal and NEVER mint rows (no 201s — always `200`):

- `{outcome:"no_open_seat"}` (unknown user; no invented `seat` key)
- `{outcome:"standbys_off", seat}` (knob 0 kill-switch — ignored non-destructively)
- `{outcome:"seat_not_active", seat}` ("primaries bind first; dry rows refuse fills")
- `{outcome:"standbys_capped", seat}` (already at ceiling — idempotent; `added/wanted` keys omit)
- `{outcome:"standbys_added", seat, wanted, added:[accountIds], cappedByMax, dry}` — added
  may legitimately be `[]` on starved hunts.

Slots.json untouched by reservations (duty change, not lifecycle movement).
Pack members belong exclusively to their user regardless of state and always
count taken for others' hunts.

#### 3.1.11 `POST /seats/:seatId/(detach|release|rotate|drop-standby)`

Shared top rungs: `404 {"error":"unknown seat"}` → `409
`{"error":"seat is detached_pending (terminal)"}`. Then detach AND rotate add
`409 {"error":"seat holds no account"}` for awaiting rows (release and
drop-standby have NO such rung). Below verbs, request methods/guards/responses
per route:

- **detach** — pull the account from a living seat.
  Body `{cause}` ∈ DETACH_CAUSES `["quarantine","exhaustion","ops_rotation","manual","sleep_rotation"]`
  (else `400 `{"error":"bad cause '<cause>'"}`; cross-family impostors rejected).
  `200 {ok:true, outcome:"detach", seat, freedSlotId}`. Effects: seat →
  `awaiting_account` + `accountId:null`, `swaps+1`, history
  `{at,kind:"detached",cause,accountId}`; freed slot gets belt bookkeeping
  `rotationCount+1` + `restUntil = now + CFP_SEAT_REST_MS_<CAUSE>`
  when that knob is nonzero.
- **release** — TERMINAL end of service.
  Body `{cause}` ∈ RELEASE_CAUSES `["churn","refund","unfunded_grace_expired"]`
  (same 400 ladder). `200 {ok:true, outcome:"release", seat, freedSlotId}`
  (null when releasing an awaiting row — churn between accounts loses nothing).
  Whole-pack wholeness: frees primary AND every reserved standby (one released-history
  entry each; packless gets one plain entry with no invented accountId;
  `standbyAccountIds` leaves the row). RELEASE causes imply HEALTH: freed
  accounts rest-less (no restUntil stamped; rotationCount++ only). Terminal stamps
  `releasedAt` + `releaseCause` land on the seat.
- **rotate** — atomic primary↔standby sleep-role swap.
  Body `{toAccountId}`. Extra rungs IN ORDER:
  `400 `{"error":"bad toAccountId '<v>'"}` (SLOT_ID_RE) → `409 `{"error":"'<id>' not in standby pack"}` →
  `409 {"error":"standby packs disabled"}` (kill-switch sentinel LAST and NON-destructively;
  frozen packs thaw instantly when the knob rises).
  `200 {ok:true, outcome:"rotate", seat, freedToPackSlotId, promotedSlotId}`.
  Role swap, not parting: ex-primary rides INTO the pack tail; promotion isn't
  lifecycle movement (promoted slot keeps rotationCount undefined; belt lands
  on the ex-primary only incl. any `sleep_rotation` rest). History pair made
  atomically detached-before-assigned.
- **drop-standby** — permanent pack shrink (v1 has no replenishment).
  Body `{slotId, cause(DetachCause)}`. Rungs AFTER membership (no active-seat
  requirement — awaiting rows shed dead weight legally): `400
  `{"error":"bad slotId '<v>'"}` → `409 `{"error":"'<slotId>' not in standby pack"}` →
  `400 `{"error":"bad cause '<cause>'"}` → `409 {"error":"standby packs disabled"}` →
  `200 {ok:true, outcome:"drop_standby", seat, droppedSlotId}`. Not a swap: primary + swaps
  untouched; dropped link takes detach-side cooldown on its way out.

### 3.2 Wire record shapes

```jsonc
// SlotRecord — returned by GET /slots, POST /slots (201), POST /slots/:id/state (200)
{
  "slotId": "…", "personaLabel": "…", "docsCountry": "FR",
  "vmServerId": 123, "vmIp": "…", "proxyExitIp": "…", "workerId": "…",
  "state": "UNVERIFIED|VERIFIED_IDLE|PRODUCTION|CHALLENGE|REVERIFY",
  "createdAt": 0, "updatedAt": 0,
  "stateHistory": [{"at":0,"from":null,"to":"UNVERIFIED","note":"created"}],
  "restUntil": 0,        // SEAT LAYER BELT only; key ABSENT on healthy rows (absent ≠ 0)
  "rotationCount": 0     // SEAT LAYER only; key ABSENT on untouched accounts
}

// SeatRecord — embedded wherever responses carry "seat"
{
  "v": 1, "seatId": "seat_18hex", "userId": "<gateway customerId>", 
  "accountId": "<slotId>|null",       // null iff awaiting_account
  "status": "active|awaiting_account|detached_pending",
  "createdAt": 0, "assignedAt": 0, "lastSwapAt": 0, "swaps": 0,
  "standbyAccountIds": ["…"],         // ABSENT on packless/pruned rows — never a fake []
  "releasedAt": 0, "releaseCause": "…", // present iff terminal
  "history": [{"at":0,"kind":"created|assigned|detached|released","cause?":"…","accountId?":"…"}]
}

// IncidentRecord — incident store unit
{
  "v": 1, "slotId": "…", "detectedAtMs": 0,  // identity pair; SUPERVISOR clock
  "receivedAt": 0,                          // gateway clock (drift diagnostics)
  "workerId": "…?", "requestId": "…?",
  "incident": { /* QuarantineIncident freeze-frame, ABSENT = stub */ }
}
```

Optional zeros ride away as ABSENT keys throughout — explicit-undefined discipline.

---

## 4. Ops-dashboard HTTP surface

File: `services/ops-dashboard/src/index.ts`.

Operator console. Returns HTML everywhere except `/healthz`; sets
`cache-control: no-store` + `text/html; charset=utf-8` on all responses;
renders every dynamic value escaped; WRITES NOTHING except its own log lines
(slots arrive over HTTP from the control-plane; queue mutations proxy
through the portal's token-guarded admin API so the PORTAL stays sole writer
of waitlist.json).

Base-path mounting (`CFP_OPS_BASE_PATH`, e.g. `/ops` behind the portal
proxy): bare basePath → `/`; `${basePath}/x` strips the prefix then routes;
anything else → HTML `404 Not found.` page. Unmatched inside mount → `404
"Not found."` page. Handler throw before headers → `500 "Something went
wrong. Retry."` page (logged with url).

Endpoints:

- **`GET /healthz`** — ALWAYS at document root regardless of mounting;
  JSON `{ok:true, service:"ops-dashboard", cpUrl, portalUrl, adminApi:boolean(CFP_ADMIN_TOKEN set?),
  ledgerBytes(-1 missing)}`.
- **`GET [/basePath]/`** — dashboard page, recomputes everything fresh per
  render. Query params honored post-prefix-strip: `?ok=<flash>` success banner,
  `?err=<flash>` error banner (rendered safely escaped).
  Data joins behind the page, each degrading loudly instead of guessing:
  - Supply — `fetch(${cpBaseUrl}/slots)` (3 s timeout); unreachable → honest banner.
  - Demand — read-only mtime-guarded mirrors of the usage-ledger +
    api-keys files.
  - Queue — `fetch(${portalBaseUrl}/admin-api/waitlist)` with
    `x-admin-token: cfg.adminToken` expecting `{entries?:WaitlistEntryRec[]}`;
    unreachable → queue hidden + actions disabled; unset token → degraded notice.
  - Ban forensics — direct read-only file mirror of incidents.json feeding the
    pure compare-accounts layer (constants: flags fire strictly ABOVE ×fleet
    median with min population 2, reliability window floor 20 turns, gap-kind
    honesty flags for orphaned/unattributed/ambiguously-shared workers;
    quarantined ⇔ CHALLENGE state; recent incident ⇔ ≤48 h).
- **`POST[/basePath]/act/:entryId`** — the ONLY mutating surface, forms only
  (`entryId` hex 6–32, form bodies capped 32 KiB).
  Auth: CSRF double-submit cookie `cfp_ops_csrf`
  (`/^[A-Za-z0-9_-]{32}$/`, SameSite=Lax, Max-Age 86400, scoped to base path),
  compared timing-safe against the `_csrf` form field. The admin token NEVER
  reaches the browser — this process attaches it when forwarding:
  `POST ${portalBaseUrl}/admin-api/waitlist/${entryId}/status` with JSON
  `{to:"INVITED"|"ONBOARDED"|"WAITING"|"DECLINED", note:"ops-dashboard:<action>(≤300 chars)"}`.
  Ladder: CSRF mismatch → `400 "Session expired — reload and retry."`;
  unknown action → `400 "Unknown action."`; token unset → `503` degraded page;
  portal fetch failure → `303 /?err=portal unreachable…`; downstream 4xx/5xx →
  `303 ?err=` portalling `body.error ?? \`HTTP ${status}\`\` VERBATIM;
  success → `303 ?ok=<action> ✓ <entryId[:8]>`.

Configuration (`services/ops-dashboard/src/config.ts`, all read from env,
validated loudly at boot):

| Env | Default | Meaning |
|---|---|---|
| `CFP_OPS_HOST` | `CFP_HOST` ?? `127.0.0.1` | listen host |
| `CFP_OPS_PORT` | `8793` | listen port (positive int or throw) |
| `CFP_CP_URL` | `http://127.0.0.1:8791` | control-plane base (slot registry) |
| `CFP_PORTAL_URL` | `http://127.0.0.1:8792` | portal base (waitlist admin API) |
| `CFP_OPS_BASE_PATH` | `""` (root mount) | path prefix; must match `/^[A-Za-z0-9_-]+(\/...)*$/`-style clean segments (`/ops`) or boot throws |
| `CFP_ADMIN_TOKEN` | unset → `null` (DEGRADED mode) | shared secret for portal `/admin-api/*`; same value as portal's `CFP_ADMIN_TOKEN` |
| `CFP_SLOT_CAPACITY_USD` | `@cfp/shared` `DEFAULT_SLOT_MONTHLY_CAPACITY_USD` | operator knob: monthly USD one production account carries |
| `CFP_SLOT_MAX_CONCURRENCY` | `@cfp/shared` `DEFAULT_SLOT_MAX_CONCURRENCY` | concurrent turns per upstream account persona |
| `CFP_USAGE_LEDGER_FILE` | `./usage-ledger.jsonl` | gateway-owned ledger, READ-ONLY here |
| `CFP_INCIDENTS_FILE` | `./incidents.json` | control-plane-owned incident store, READ-ONLY |
| `CFP_API_KEYS_FILE` | `./api-keys.json` | shared auth file, READ-ONLY count of active keys |

---

## 5. Portal service

File: `services/portal/src/index.ts` (with `store.ts`, `auth.ts`, `html.ts`,
`site.ts`,
`stripe.ts`, `erc20.ts`, `trongrid.ts`, `seats-claim.ts`). Batteries:
every `*.test.ts` sibling pins the UI copy quoted below.

Customer web application + payment rails + the public `/docs` static
reference-site mount. HTML everywhere except the JSON endpoints noted
below; every response carries `cache-control: no-store`. Listens on
`CFP_PORTAL_HOST` > `CFP_HOST` > `127.0.0.1`, port `CFP_PORTAL_PORT`
(**8792**) — designed to sit behind a Cloudflare tunnel (trusts
`CF-Connecting-IP` when it matches `/^[0-9a-fA-F.:]{3,45}$/`). Router
dispatches path-before-query (`req.url.split("?")[0]`) except `/pay/:id`
which re-reads raw query (`cancelled=1`). Unhandled throw → `500`
`"Something went wrong on our side. Please retry."`; unmatched path → `404`
`"Page not found."`.

**Important:** there is NO customer-facing JSON/REST inference API here —
the REST-style inference surface is the gateway's `/v1/messages`
(§1). The dashboard advertises exactly that (`curl <apiBase>/v1/messages`
with `x-api-key`). Portal-side customer features are HTML-only.

### 5.1 Auth/session machinery

| Mechanism | Detail |
|---|---|
| Session cookie | **`cfp_sess`** = `b64url(uid|expIso).HMAC-SHA256(secret,"sess|"+payload)`; TTL **30 days**; `Path=/; HttpOnly; SameSite=Lax` (+`Secure` iff `CFP_PORTAL_SECURE_COOKIES=1`). Everything past the router's auth line 303s to `/login` without it |
| CSRF | Double-submit: cookie **`cfp_csrf`** (32-char b64url, Max-Age 86400) vs form field **`_csrf`**, timing-safe compare, on EVERY form POST |
| OTP display carrier | Cookie **`cfp_otpshow`** (`Path=/verify; HttpOnly; Max-Age=900`): `"M"` code mailed \| `"O:<code>"` email rail unconfigured \| `"F:<code>"` provider send failed (values are HMAC'd, opaque); cleared after verify |
| Operator bearer | Header **`X-Admin-Token`** (timing-safe) guards ALL `/admin-api/*`; also exchangeable at `/ops/login` for signed 12 h cookie **`cfp_ops_auth`** (`Path=/ops`). Env unset ⇒ both surfaces refuse honestly |
| Password/OTP | scrypt `$16384,8,1` (`scrypt$<salt>$<key>`); OTP = 6 digits stored HMAC-hashed, TTL **15 min**, **max 5 tries**, resend cooldown **45 s** |
| Rate limits (per IP, in memory) | `/waitlist` `/register` 10/10 min · `/login` 15/10 min · `/resend-code` 5/10 min · `/ops/login` 10/10 min → **429** |

### 5.2 Public pages & flows

- **`GET /healthz`** — JSON (own headers):
  `{ok:true, service:"portal", customers:N, billing:<bool usdtReady‖stripeReady>, billingUsdt, billingStripe, plans:N, mode:"usage-credits", rates:"<RATES_FETCHED_AT_UTC>", waitlist:{file, waiting:N, invited:N, adminApi:bool}, ledgerFile, ledgerBytes}`
- **`GET /`**, **`GET /pricing`** — landing/pricing pages; pricing tables render
  from the SHARED rate cards (§6.2): struck-through official vs bold sale, so
  advertised ≡ billed holds site-wide.
- **`GET`/`HEAD` `/docs`, `/docs/<name>`** — PUBLIC read-only static
  reference-site mount (resolver: `site.ts`; filesystem owner: the router
  block in `index.ts`). Serves ONE FLAT directory — `CFP_SITE_DIR`
  (default `"redesign"`, resolved against the service WorkingDirectory,
  `/root/cfp` in prod) — i.e. the redesign build: self-contained customer
  pages (`api.html` = this doc's §1 rendered in site chrome, plus
  index/pricing/buy/pay/login/register/verify/waitlist/dashboard `.html`)
  and a verbatim copy of this file at **`/docs/API.md`**
  (`text/markdown`; built there by `redesign/build.py`). Contract:
  - `/docs`, `/docs/` → `303 Location: /docs/api.html` — the API reference is
    the front door of the docs surface; html-namespace relative links keep
    every nav inside the mount (`/docs/api.html` → `pricing.html` →
    `/docs/pricing.html`).
  - Name must match `/^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/` (no `%`,
    no hidden/dotfiles, nothing before a leading dot) AND carry an extension
    in the closed whitelist (`html css js mjs svg png json webmanifest md txt`)
    → else uniform HTML `404 "Page not found."`. One flat dir by contract:
    subdirectories (`src/…`), dot-dot, and encoding probes never reach a
    filesystem lookup — classification is pure & total, disk only happens on
    `{kind:"file"}`. No session, no CSRF cookie (pages carry no forms);
    `cache-control: no-store`.
  - Missing file/dir renders the same honest `404` page as any unknown
    route; boot logs a WARN when `CFP_SITE_DIR` doesn't exist so a
    mis-deployed docs dir is visible from second zero without gating
    customer traffic.

- **`GET /waitlist`**, **`POST /waitlist`** — public join form (CSRF +
  RL 10/10m). Fields: `email`, `company?≤100`, `requestedMonthlyUsd`
  (int 1–1,000,000), `peakConcurrency` (int 1–64), `notes?≤600`.
  Violations re-render at `400` preserving input; duplicate OPEN email
  (WAITING\|INVITED, case-insensitive) re-renders showing original position,
  never stacks a row; success appends a
  `WaitlistEntryRec {id,email-lowercase,company?,requestedMonthlyUsd,
  peakConcurrency,notes?,customerId?,status:"WAITING",createdAt,updatedAt,
  statusHistory:[{at,from:null,to:"WAITING",note:"joined"}]}` →
  "You're on the list ✅ Queue position #N".
  Status machine (`ALLOWED_WAITLIST_TRANSITIONS`):
  WAITING→INVITED\|DECLINED · INVITED→ONBOARDED\|DECLINED\|WAITING ·
  ONBOARDED→(terminal) · DECLINED→WAITING.
- **Registration / verification / login**:
  - `GET /register` (session → 302 `/dashboard`); `POST /register` (RL;
    validations: valid email; password ≥ 10 chars; match; existing verified
    account rejected; unverified duplicate re-arms OTP, and updates passHash
    when changed) → success arms a fresh OTP, signs session, attempts Resend
    delivery (Bearer `CFP_EMAIL_API_KEY` matching `^re_[A-Za-z0-9_-]{16,}$`,
    From `CFP_EMAIL_FROM`), degrades to show-code otherwise → `303 /verify`.
  - `GET /verify` (requires session; already verified → `/dashboard`);
    `POST /verify` (`_csrf`,`code`): expired / `tries ≥ 5` / mismatch each
    re-render `400` with pinned copy ("Your code expired — request a new one
    below.", "Too many wrong attempts — request a new code below.",
    "That code doesn't match."); success clears the otpshow cookie →
    `303 /dashboard?new=1`.
  - `GET /resend-code` → `303 /verify` touching nothing (legacy-CSRF
    hardening); `POST /resend-code` (RL 5/10m; inside 45 s cooldown → silent
    `303 /verify`) re-arms + re-delivers.
  - `GET /login` / `POST /login` (RL 15/10m): bad credentials → `401`
    "Invalid email or password." (generic + ~120 ms timing equalizer);
    authenticated-but-unverified → `303 /verify` (OTP re-armed iff cooldown
    passed); success → `303 /dashboard`.
  - any-method **`/logout`**: `303 /` + `cfp_sess=deleted; Max-Age=0`.

### 5.3 Admin JSON API — `/admin-api/*` (consumed by ops-dashboard)

Gate on ANY `/admin-api/*`: missing/unset/mismatched
`X-Admin-Token` → `401 {"error":"missing or invalid X-Admin-Token header"}`
(compared timing-safe after padEnd(64)).

- **`GET /admin-api/waitlist`** → `200 {"v":1,"entries":[WaitlistEntryRec…]}`
  (full records including `statusHistory`).
- **`POST /admin-api/waitlist/{id}/status`** (`id` = `[a-f0-9]{6,32}`, JSON
  ≤ 32 KiB): body
  `{"to":"WAITING"|"INVITED"|"ONBOARDED"|"DECLINED","note?"≤300chars,
    "customerId?" must match ^u_[0-9a-f]{6,64}$ }`.
  `400 {"error":"bad JSON body"\|"bad status '<to>'"\|"bad customerId (expect u_<hex>)"`} ·
  `404 {"error":"unknown waitlist entry"}` ·
  `422 {"error":"illegal transition <from> -> <to>","allowedFrom":"<from>","hint":"see ALLOWED_WAITLIST_TRANSITIONS in @cfp/shared"}`} ·
  `200` returns the BARE updated `WaitlistEntryRec` (unwrapped),
  `statusHistory` appended; `customerId` accepted at ONBOARDED time as the
  audit link to the billing identity.
- Anything else under `/admin-api/*` → `404 {"error":"<METHOD> <url>"}`.

### 5.4 Operator console mount — `/ops*` (token-gated reverse proxy)

Everything `url === "/ops" || startsWith("/ops/")` proxies to
`CFP_OPS_DASHBOARD_URL` (default `http://127.0.0.1:8793`, §4), 10 s timeout,
forwarding method + `content-type` + browser `Cookie` ONLY, echoing upstream
status/headers verbatim with `redirect:"manual"`. `CFP_ADMIN_TOKEN` unset →
any `/ops` path answers `404` "The ops console isn't configured on this
deployment."

- **`GET /ops`** → `303 Location: /ops/`.
- **`POST /ops/login`** (form `_csrf`,`token`; RL 10/10m): CSRF miss →
  `400` "Session expired…"; wrong token → `401` "Wrong token."; success →
  `303 /ops/` + `Set-Cookie cfp_ops_auth=<b64(expMs).b64(hmac)>` (12 h TTL).
- **`POST /ops/logout`** → `303 /ops/`, cookie cleared. No CSRF consumed.
- All other `/ops/*`: unauthenticated → `401` login form; authenticated →
  proxied (upstream keeps its OWN CSRF protecting action POSTs); upstream
  down/timeout → `502` "The ops console is unreachable right now — is the
  ops-dashboard service running?"

### 5.5 Webhook — `POST /webhooks/stripe`

Signature-authenticated over RAW bytes only (route sits before the login gate):

- Stripe not fully configured → `503 {"ok":false,"error":"stripe billing not
  configured"}` (boot also refuses if only ONE of secret/webhook keys is set).
  Raw body > 64 KiB → `413 {"ok":false,"error":"body too large"}`.
- Signature header `stripe-signature` = `t=<sec-or-ms>` + `v1=<64 hex>`
  (multiple v1s supported for secret rotation); digest =
  HMAC-SHA256(`${tRaw}.${rawBody}`); freshness ± 5 min
  (`STRIPE_WEBHOOK_TOLERANCE_MS`). Any verification failure → BARE `400` empty
  body (never parses unauthenticated payloads; flood logs throttled 60/min).
- Only event type **`checkout.session.completed`** can move money; every other
  authenticated envelope acks `200 {"received":true}` (at-least-once safe).
  Settlement trusts OUR records only: `metadata.invoiceId` must match
  `/^[0-9a-f]{24}$/` and name our invoice whose `(method ?? "usdt") ===
  "stripe"` AND `stripeSessionId === session.id`; credit derives ONLY from our
  own `inv.amountUnits` (never client data); money moves only when upstream
  agrees (`payment_status === "paid" && status === "complete"`), flipping the
  invoice pending→paid with note
  `'stripe <csId> checkout.session.completed'`; concurrent redeliveries resolve
  via `alreadyCredited` (never double-credit). Refusal reasons (logged
  internally): `unknown_invoice | not_stripe_invoice | session_mismatch |
  not_paid_yet | unpaid_session | customer_missing | amount_oversized` — but the
  HTTP wire answer is ALWAYS `200 {"received":true}` on authenticated paths.

### 5.6 Customer-authed pages (everything below needs `cfp_sess` + verified account)

No/invalid session → `303 /login`. All forms carry `_csrf`.

- **`GET /dashboard`** — composes from three sources: the shared key record
  (`findSharedKey(activeKeyId)` from shared `CFP_API_KEYS_FILE`), usage totals
  (read-only mtime-guard mirror of the gateway-owned append-only
  `CFP_USAGE_LEDGER_FILE`: `{spentMicroUsd, byDay UTC buckets}`) and this
  customer's last 10 invoices. Renders masked email, active API key
  (`sk-cfp-` + base64url(24 bytes), born at FIRST payment — pill
  "awaiting first payment"), credit balance (credits−spends, 4 dp trimmed,
  negative/zero pill "credit exhausted"), last-7-day burn table, and invoice rows
  `{id [0-9a-f]{24}, planId, amount, status: "pending"|"paid"|"pending_manual",
  createdAt, method: "usdt"|"stripe"}`.
- **`GET|POST /buy`** — denomination (`CFP_PLANS_JSON`, default
  `{"top10":{"priceUsdt":10},"top20":…20,"top50":…50,"top100":…100}`,
  ascending) + method picker. Neither rail ready →
  `H.pageBillingDisabled()`. Unknown plan/rail → `400`
  "Pick one of the listed amounts and a payment method, then try again."
  (strict honesty — never silent defaults).
  - **Stripe rail**: non-cent-exact denominations refused; pre-mints an
    unguessable `[0-9a-f]{24}` invoice id BEFORE calling Stripe
    `POST /v1/checkout/sessions` (`mode:payment`, one
    `$N.NN prepaid credits` line item, `customer_email`, success/cancel back to
    `/pay/<invId>`, 24 h−60 s expiry); failure → `503` "Card payments hiccupped
    on Stripe's side just now — nothing was charged…" with NOTHING persisted;
    success persists `InvoiceRec{amountUnits: cents×10⁴n(base µ$), status:
    "pending", method:"stripe", stripeSessionId, stripeSessionUrl}` → `303` to
    Stripe's hosted URL.
  - **USDT/crypto rail** (`CFP_PAYMENT_CHAIN` ∈ `tron`\|`ethereum`): computes
    `priceUnits` at 6-dec µUSD peg, then picks a globally UNIQUE sub-cent band
    amount under headline price — deterministic slot =
    `HMAC-SHA256(secret,"amt|email|planId")` mod 80, candidate =
    `price − (slot+1)·100µ$` (e.g. **$19.9973**; that EXACT amount identifies
    YOUR payment on-chain among all others); duplicates avoided against all
    open USDT invoices only; exhaustion → `503` retry-later. Persists
    `InvoiceRec{amountUnits, expiresAt: now+48 h, status:"pending"}` →
    `303 /pay/<invId>`.
- **`GET /pay/{24hex}`** — STRICT ownership (`inv.customerId === customer.id`
  else `404 "Invoice not found.").` Stripe variant renders amount
  (cents-exact)/expiry/status, resume-or-cancel link while unpaid+prior to expiry,
  auto-refresh `<meta refresh 8>` ONLY while unpaid, `cancelled=1` notice,
  `pending_manual` "awaiting an operator check — your credit is not lost".
  Crypto variant renders `amountUsdt` at EXACTLY 4 decimals, receive address,
  pay network label (`Ethereum (ERC20)`\|`TRON (TRC20)`), token contract,
  TXID pattern (`^(0x)?[0-9a-fA-F]{64}$`\|hex64).
- **`POST /pay/{24hex}/sync`** — Stripe manual-confirm. Trust anchor is OUR
  stored `stripeSessionId`; outbound session retrieval → settle via the same
  idempotent settlement critical-section as the webhook (so it can never
  double-credit). Codes: `202` "Stripe hasn't marked this checkout complete yet…
  This page keeps checking." · `400` config/disagreement copy ·
  `500` "Session/invoice reference disagreement detected — support has been
  notified." · `503` reachability copy · `303` settled/back-to-page.
- **`POST /pay/{24hex}/verify`** — crypto TXID paste (`_csrf`, `txid`;
  eth: strip `0x`+lowercase; tron: trim). Chain primitives selected by
  `cfg.paymentChain`:
  - TRON (`trongrid.ts`): `POST https://api.trongrid.io/wallet/gettransactionbyid`
    with bounded exp-backoff retries; gates `contractRet === "SUCCESS"`,
    single `TriggerSmartContract` paying the USDT contract, calldata selector
    `transfer(address,uint256)` with decoded recipient + 6-dec amount.
  - Ethereum (`erc20.ts`): public RPC failover chain (publicnode, drpc,
    llamarpc, cloudflare-eth; one batched
    `getTransactionByHash`+`getTransactionReceipt` round-trip); gates receipt
    `status === "0x1"`, PLAIN-DIRECT sends only (`tx.to === USDT contract` —
    aggregator/swaps park for manual confirm), first USDT Transfer log paying
    our address wins.

  Disposition (shared `PaymentCheck.reason`):
  `bad_tx_format\|tx_not_found\|tx_failed\|not_usdt_contract\|wrong_recipient` →
  `400` with reason-specific pinned copy (txid released, nothing touched);
  DUPLICATE TXID → `400` "This transaction ID was already used for a credit."
  (in-memory double-spend ledger — ring capped 10 000 + permanent backstop scan
  over paid invoices' `txHash`); `api_error` → park
  `pending_manual`; `amount_too_low` → flips to `pending_manual` with
  `"amount mismatch: paid <got>, expected <want>"`; OVERPAY →
  `pending_manual` "Payment received (<N> USDT) but this invoice needs exactly
  <N> USDT to auto-confirm…"; EXACT match → credits: first payment births the
  active API key on the spot (`sk-cfp-` + base64url random, upserted into the
  shared `CFP_API_KEYS_FILE` which the gateway hot-reloads within ~10 s),
  credits stack additively (legacy `expiresAt` cleared), invoice flips
  paid+creditedAt → `303` paid confirmation view. Late exact payments arriving
  post-expiry park for manual reconcile.
- **Seats-claim rail (outbound)**: every LANDED payment (both rails)
  synchronously-but-NOT-awaited fires best-effort
  `POST ${CFP_CONTROL_PLANE_URL}/seats/claim {"userId":"u_<customerId>"}`
  (2 s timeout, exactly one re-flight 250 ms later; never throws, bodies
  always drained, give-up logs the two heal paths: next successful payment
  re-fires the idempotent-per-user claim; manual ops claim remains available).
  Env-light-switch: unset `CFP_CONTROL_PLANE_URL` stays dark entirely.

---

## 6. Shared canons (`packages/shared/src`)

### 6.1 Model pins

```js
MODEL_PIN_RE = /^(?:sonnet|opus|fable|claude-(?:sonnet|opus|fable)-[0-9]+-[0-9]+)$/
DEFAULT_MODEL_PIN = "claude-sonnet-5-5"
CANONICAL_FAMILY_PIN = { sonnet: "claude-sonnet-5-5",
                         opus:   "claude-opus-5-5",
                         fable:  "claude-fable-5-2" }
```

Only models present in the sale rate card are served/billed; family aliases
resolve to the CURRENT generation so billed pins never depend on shifting
downstream defaults.

### 6.2 Rate card (billing units: integer MICRO-USD per MTok, $1e-6)

Source of truth `packages/shared/src/rates.ts` transcribed from the evidence
file fetched live 2026-11-17 (sha256 preserved in-source); self-tested at every
gateway boot — money code refuses to run on drift. Sale = official × ½
(integer-exact; advertised ≡ billed):

| Canonical pin | input | output | cache write 5m | cache write 1h | cache read | (ALL per MTok, µ$ shown ×1e6) |
|---|---|---|---|---|---|---|
| `claude-fable-5-2`  | 4,000,000 ($4.00)  | 20,000,000 ($20.00) | 5,000,000 ($5) | 8,000,000 ($8) | 200,000 ($0.20) | — |
| `claude-opus-5-5`   | 2,000,000 ($2.00)  | 10,000,000 ($10.00) | 2,500,000 ($2.50) | 4,000,000 ($4) | 100,000 ($0.10) | — |
| `claude-sonnet-5-5` | 1,000,000 ($1.00)  | 5,000,000 ($5.00)   | 1,250,000 ($1.25) | 2,000,000 ($2) | 50,000 ($0.05) | — |

Cache-write pricing policies: `"split"` (bills each ephemeral kind at its own
−50% rate using the exact upstream 5m/1h counters — total equals precisely
list-minus-50%) or `"legacy_1h"` (merged writes at the pricier 1-hour rate).
Metering helpers: `costMicroUsd(tokens, microPerMTok)` rounds to nearest µ$
(worst-case loss per call half a µ$); `turnCostMicroUsd(usage, rates, policy)`
prices one turn. Refuse-to-boot anchors assert opus $2/$10, sonnet $1/$5,
fable $4/$20, cache-read .10/.05/.20 — transcription drift kills startup.

### 6.3 Identity & misc vocabularies

```js
DOWNSTREAM_ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/   // "<customerId>" | "<customerId>:<conversationId>"
QUARANTINE_SIGNATURE = "Your account can't receive replies from Claude"
PROTOCOL_VERSION = 1
RAIL_IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"]
```

### 6.4 Usage ledger row (`UsageLedgerRow` — one append-only JSONL line)

Billing-relevant keys only are read by any summing code; all other blocks are
additive and eternally back-compat (absent = pre-field era, nothing degrades):

```jsonc
{
  "v": 1, "ts": 0,                       // epoch ms at billing time (gateway clock)
  "key": "sk-cfp-…",                    // raw API key (same security domain as api-keys.json)
  "customerId": "u_…",                  // wire identity prefix
  "pin": "claude-sonnet-5-5",           // canonical billed model (rate-card key)
  "costMicroUsd": 0,                    // billed sale cost of this turn
  "partialReason": "cli_error",        // PRESENT ONLY on partial-billed failed turns
  "inputTokens": 0, "outputTokens": 0,
  "cacheReadTokens": 0, "cacheCreationTokens": 0,
  "cacheCreation5mTokens": 0, "cacheCreation1hTokens": 0,
  // attribution block (ban forensics; NEVER validated into billing math)
  "requestId": "msg_gw_…", "workerId": "…", "identity": "u_x:convY",
  // per-request feature digest (scorecards; display-only; fingerprints are
  // sha256 slices of normalized prompt segments — enrichments, NOT transcripts)
  "f": { "phH16": "…|null", "phM16": "…|null", "phT16": "…|null",
          "msgN": 0, "uCh": 0, "aCh": 0, "sysCh": 0, "imgN": 0, "extractHitsN": 0 }
}
```

Rows are never edited or deleted; corrections append compensation rows.
Effective key balance ≡ `(api-keys.json).balanceMicroUsd − Σ(rows.costMicroUsd)`
— two files, two writers (portal owns credits, gateway owns spends), zero
mutation races.

---

## Appendix — quick endpoint index

| Service | Endpoint | Method | Audience |
|---|---|---|---|
| gateway | `/v1/messages` (`?beta=true` ok) | POST | customers |
| gateway | `/healthz` | GET | monitors |
| gateway rail | `/workers` (WS upgrade; mTLS'd dedicated port when configured) | GET | supervisors |
| control-plane | `/healthz`, `/slots`, `/slots/:id/state`, `/slots/:id/incidents`, `/incidents?limit=` | GET/POST | operators + gateway relays |
| control-plane | `/seats`, `/seats/assignments`, `/seats/claim`, `/seats/reserve`, `/seats/:id/detach|release|rotate|drop-standby` | GET/POST | operators + gateway relays |
| ops-dashboard | `/healthz`, `/` (+`?ok|err=`), `/act/:entryId` | GET/POST | operators (HTML) |
| portal | `/healthz`, `/`, `/pricing`, `/docs`, `/docs/{name}` (flat static dir: `CFP_SITE_DIR`; `303 → /docs/api.html`; closed extension whitelist, else 404), `/waitlist` (+POST), `/register` (+POST), `/verify` (+POST), `/resend-code` (+POST), `/login` (+POST), `/logout` (any) | GET/POST | customers + public (HTML) |
| portal | `/webhooks/stripe` | POST | Stripe (HMAC signature) |
| portal | `/admin-api/waitlist`, `/admin-api/waitlist/{id}/status`; rest → 404 | GET/POST | operators (`X-Admin-Token`) |
| portal | `/ops`, `/ops/login`, `/ops/logout`, `/ops/*` (proxied) | any | operators (12 h HMAC cookie) |
| portal | `/dashboard`, `/buy`, `/pay/{24hex}`, `/pay/{24hex}/sync`, `/pay/{24hex}/verify` | GET/POST | customers (session + CSRF) |
