# Model relay, inference and gateway

Scope: the model relay and its journal, the hub's own inference and its slots, OmniRoute and in-process model routes. Read before editing `src/models/`, `src/hub/inference.ts` or `src/omniroute/`.

- The model relay journals per-request identity (`RelayRequestRecord`): a request's served model comes only from its own gateway header, its own generation SSE event (#137 heartbeat classification), or the locally validated MLX configuration. A backend's mutable last-served label is never a request's evidence, HTTP 200 plus the requested alias identifies nothing, and a request cancelled before identification stays explicitly unidentified (`identified: false`, `outcome: "cancelled"`). Journal records carry no prompts, tools, keys or Access headers.
- Inference is optional and fail-open: it returns its input or `undefined` on any failure and backs off, so a delivery never waits on a dead model twice. Its output is only ever capped text or a value checked against a closed list.
- The PII screen (`screenPii`, #198) is the exception: it fails closed. Every failure (timeout, no or off-campus model, an answer outside `clear` / `pii <category>`, text over `SCREEN_MAX_BYTES` UTF-8 bytes, since a token is at least a byte) is `unknown`, which `Tasks` handles as PII. It never goes through the inference backoff, asks the gateway only after `onCampus()` and with `onCampusOnly`, takes the on-device generation slot under its own deadline (`acquire(abort.signal, 0)` first, one look and `MlxBusyError` when all are taken: a taken slot sends it to the campus gateway, and only off campus does it wait; on campus a failing or still-loading device hands over to the gateway after 60% of the deadline), sends temperature 0 and `reasoning_effort: "none"` on both paths so a reasoning model cannot spend its 32 tokens thinking, and never puts the text in a log line, an error or an event.
- An `Inference.complete` call that carries PII text (`ahub ask` over PII evidence or a PII question, a private intake `split`) passes `onCampusOnly`: the model is pinned from `fixedModel()` before any gateway await and the transport refuses the Access endpoint. Its `allowed` predicate is read before the call, after the gateway probe and after the answer; `false` or a throw returns `undefined`. The intake split's JSON is never trusted by `Inference`; its caller validates it (`parseIntakeSplit`).
- Secrets stay inside `OmniRoute`: never put the key or Access values in a log line, an error message, a return value or routing configuration.
- Keep model selection in process in the hub-owned route implementation, with optional adec model/effort choices. Read `docs/design/model-routes.md` before changing stage evidence, fallback, input sizing or switch contracts. Keep stage-only evidence separate from generic decision evidence v1. Treat legacy routing tables as retired and never rewrite operator files during load.
- Shared inference slots must recover after a hub process dies, without evicting a live owner. Cancellation has to reach slot acquisition from the relay caller, not just exist in the helper signature.
- Stay/switch (#197): `hub/auto` and local stage routes apply `stay_switch` only through `planStageSwitch` (`src/models/route/stage-fallback.ts`), never at a call site; `shadow` must not change a routing decision (the recorded-decision golden test in `test/route-relay.test.ts`). No route summarizes, trims or rewrites the forwarded conversation: a tier that cannot fit is filtered out. A PII route's planner never sees the conversation size (no prefill bound) and its event omits `prefillTokens`.
- A change to the model-routing keys of `templates/routing.toml` (`hub_routes`, `local`, `fixed_model`, `stay_switch`, the `[pi]` windows) carries a model-routing receipt (#637 part 2): `bun scripts/benchmarks/model-routing-gate.ts --receipt`, plus `--live` by hand when an alias or a judge moves. The corpus drives the real `HubRouteRuntime`; see "Model-routing promotion rule" in `docs/agent-notes/benchmarks.md`.
- Load and cooldowns (#199) only reorder a `hub/auto` request's candidates (the route's own backend, then its fallback, as on main), in one ordering step in the relay's fetch handler; a fixed alias is never reordered. Never remove a candidate. A candidate goes first only while it is neither cooling nor `failing` (any failure, an error status or a failed stream included, for `model_relay.cooldown_s` (default 30 s) or until a success; separate from the cooldown streak). Load and pin moves are opt-in (`efficientWaitMs` absent: none) until #199 AC5 measures them. Their attempt is bounded only up to its response headers (`MOVE_FIRST_BYTE_MS`, after `omni.base()`); a cut there marks `failing` without counting toward a cooldown, and a stream that fails after the headers cannot fall back, so do not claim a move never fails a request MLX would have served. None happens while the request runs under an execution budget (`underBudget`, a read that admits nothing; a throw counts as a budget). The selector only names `prefer`; it never picks a moved backend itself. They never consider PII because the relay serves only Pi, which refuses PII work before any model call (`selectModel` in `daemon.ts`); a relay caller that can carry PII must not get a reorder toward DGX without a positive `onCampus()`. Count a cooldown failure only for a transport or startup failure outside a cooldown that was neither cancelled, refused admission, a busy MLX slot (`MlxBusyError`: load, never failure), nor a deadline the relay cut itself (`journalEntry.cut`: `"budget"` for the execution budget's, `"move"` for a moved attempt's first byte, which only marks `failing`); any HTTP answer, whatever its status, ends the streak and the cooldown (`answered`).
- Relay cooldown policy and journal size (`model_relay.*`, read through `modelOperationalReaders`, #984) are passed only when a relay is constructed, and `inference.backoff_min` only when `Inference` is constructed. Both are restart-bound: a reload never rewrites a running relay's cooldowns or journal, or an existing backoff deadline.
- MLX owner and generation identity read `ps lstart` with LC_ALL=C/TZ=UTC pinned (#177): unpinned, a record written under one environment reads as a foreign process under another, and the fail-closed paths would refuse the hub's own server.

- Optional adec `decision` routes (#554) default off and support shadow only; reject enforce at load with the #554 follow-up and do not keep an application or gateway effort path. Shadow must preserve the recorded stage model, effort and conversation. Send only bounded host-screened evidence after positive campus admission for sensitive turns; sensitive evidence is dimensions only, and remote/review-observer-excluded turns skip the service. Re-read current board/turn privacy and observer facts across awaits and before service HTTP effects and route metadata emission; changed or unavailable authority refuses the stale turn, never a model fallback around that refusal. Keep one opaque user-turn id through the tool loop; let adec recheck its pins and hard rules, rather than caching valid picks in the hub. Validate returned pairs against the route list, retain the heuristic on client failures/no_candidate, and keep evidence, arguments, secrets and service error prose out of route events. Never route PII screening, pure peer assignment or escalation authority through this service. A stage route asks it only through `ambiguousStage` (`classifier = "decision"`, `ambiguous_band` default `0.05`, `abs(score - confidence_threshold) <= band`): membership decides only whether the question is asked, the answer is recorded and changes no tier, the two tiers with effort `none` are the only options, and `ambiguous_band = 0` asks nothing.
- R2 host model/effort choices for `plan_execute`, `advisor` and `escalation` remain default-off and shadow-only. They are suggestions only: keep the plan phase, advisor/escalation trigger and verdict, privacy/currentness fences, and actual fallback execution in the hub; do not add effort application, authority transfer, or phase/purpose event fields. Judge-choice route metadata uses only the checked `decisionTarget: "judge"` marker and remains outside executor label/progress/usage accounting. The ADEc templates are placeholders with `onPrem: false` until a person verifies the serving location; no live or gain claim follows from fixtures.
- The offline triage evaluation (`scripts/decision-eval.ts`, #554 AC5) is a person-run leg, never CI. It serializes `hub.db` from a read-only connection into one consistent image and reads that copy (never separate `hub.db`/`-wal`/`-shm` copies, which a checkpointing writer can leave on different WAL generations), keeps only planner-classified non-PII rows (no `triaged` or `class defaulted` history, no `pii`/`pii_path` signal, public text), and compares `Inference.triage` against a loopback adec `/v1/route` or `/v1/systemone`, each adec turn id carrying a fresh per-run id so no earlier pin is reused. It is evidence for D5 only: wiring a decider into `Tasks.triage`, `assign()` or the PII screen is a separate decision, and a change here never touches them.
