Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
test(model-hub): add hermetic pytest E2E suites (#1812)
Max0487cd727388
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.mdnew file mode 100644index 000000000..a87f8edaa--- /dev/null+++ b/docs/plans/model-hub-e2e-test-plan.md@@ -0,0 +1,274 @@+# Model Hub E2E Test Plan++Status: draft, 2026-09-01. Baseline code: `master @ fbb4c532`.+Companion inventories (kept in session, summarized here): capability list C1–C81 and issue list B1–B17 produced during the 2026-09-01 survey.++## 1. Goals and ground rules++1. Exercise the **shipped surface end to end** over real HTTP: browser-visible API (`/api/models/*`) and the per-turn gateway, against a **mock upstream provider**, never real vendor credentials.+2. Assert **current behavior as baseline** where the owner has ruled (cross-vendor fidelity ruling 2026-08-08; "user owns the order" contract in `docs/plans/model-hub.md` §4.2), and mark scenarios **fix-first** or **expected-fail** where the survey found unintended drift (see §5 open decisions).+3. Every scenario names the feature ids (C#) it covers and the evidence layer it lives in: `e2e-auto` (this suite), `unit/contract` (existing), `manual` (Incus regression).++Out of scope (documented, not dropped silently):+- Real-vendor OAuth completion (Anthropic/OpenAI login dance) — needs real accounts; covered by `manual` in Incus regression. Flow lifecycle (start/status/cancel/expire/nonce replay) **is** in scope via the hub OAuth endpoints up to the auth URL.+- OpenCode provenance (by design never written; `model-hub-l3-correlation.md`).+- Protocol-conversion fidelity beyond the functional floor (owner ruling: converted supply is functionally usable while its reasoning chain may degrade — expected, not a defect). E2E asserts: turn completes, tool call ids correlate on the final turn, stream terminates with a well-formed terminal frame. It does **not** assert reasoning/system-prompt fidelity.++## 2. Environment and fixtures++- Runtime: hermetic `AVIBE_HOME` under the test dir; `VIBE_MODEL_HUB_ENABLED=1`. Docker `tests/e2e` service with `command: ["full"]` (controller + UI in one process pair) or an equivalent local hermetic run; whichever the implementing lane proves stable first.+- Engine binary: no GitHub egress in CI. Use `VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH` / `VIBE_MODEL_HUB_ENGINE_OFFLINE` (`vibe/model_hub_runtime/installer.py:105-109`) with the pinned cliproxyapi v7.2.95 assets vendored per platform (linux-amd64/arm64, darwin-arm64/x64).+- **Mock upstream provider** (new test fixture, `tests/e2e/drivers/mock_llm_upstream.py`): implements, per protocol — `POST /v1/messages`, `POST /v1/responses`, `POST /v1/chat/completions`, `GET /v1/models` — with:+ - configurable model inventory (ids only, plus Anthropic-style `display_name` and relay-style `context_length` extensions to prove they are dropped, B-list);+ - auth modes: accept / 401 / 403(banned-pattern) / 402 / 429 / quota-message / 5xx;+ - stream modes: healthy SSE per protocol, and interrupt-after-first-model-output;+ - request capture (last N bodies) so tests assert what the upstream **received** (effort stripping, model prefix, header survival).+- Auth/roles: two API tokens (owner, member) for the permission matrix.++## 3. Suites++### A. Gating and runtime lifecycle (C1,C2,C5,C9–C15)+| ID | Steps | Expect | Status |+|---|---|---|---|+| A1 | flag off | `/api/models/*` → 404 `feature_disabled`; UI redirects to `/settings/backends` | assert |+| A2 | install → start → stop happy path; status polling transitions | `installing/starting/active/stopped`; engine config regenerated with hardened values (`request-retry: 0`, `disable-cooling: true`, `usage-statistics-enabled: false` …) — conservation check on CPA upgrade | assert |+| A3 | agent in hub mode → stop runtime | 409 `runtime_in_use` with `data.backends`; **and** UI surfaces the blocking backends (B4 fix-first; baseline: generic toast) | fix-first |+| A4 | agents read fails while runtime on | toggle must not silently disable (B5) | fix-first |+| A5 | controller restart mid OAuth poll | poll reports `engine_down` copy, never a fake materialization failure (B10) | assert |++### B. API-key sources (C16–C29)+| ID | Steps | Expect | Status |+|---|---|---|---|+| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract v6 | assert |+| B2 | manual protocol ≠ actual | create refused with matching proof error | assert |+| B3 | pull models (mock returns `display_name`, `context_length`, `pricing`) | persisted model has only the 6 schema fields; `display_name:null`, `reasoning_efforts:[]` — documents the drop, not a pass/fail of intent | assert-current |+| B4 | discovery fails | 422 `inventory_unavailable` unless `accept_unavailable_inventory:true`; then source commits with `state.status=error` | assert |+| B5 | replay create with same `client_nonce` | idempotent, no duplicate source | assert |+| B6 | replace key happy + rollback; rename; patch base URL | C22/C23 contracts | assert |+| B7 | delete source in a chain → guard 409 → echo plan → force | hop removed, impact report lists interrupted agents; malformed echo rejected | assert |+| B8 | force transport asymmetry (`?force=` vs body) | document current split (B6 issue); decide normalization | baseline |+| B9 | refetch after upstream inventory change | added/removed diff; **`discovered_at` preserved for pre-existing models** (currently overwritten — fix-first, see B-list) | fix-first |+| B10 | add/edit/delete custom model; edit tiers | `source_model_managed_upstream` for discovered rows; free-text tiers accepted | assert |+| B11 | trigger each of: `mapping_target_unavailable`, `runtime_in_use`, `source_nonce_conflict`, `reauth_confirmation_required`, `turn_not_found` | UI renders human copy, never the raw `modelHub.errors.*` string (B1 — fix-first; baseline expected-fail) | fix-first |++### C. OAuth lifecycle (C30–C40, partial by §1)+| ID | Steps | Expect | Status |+|---|---|---|---|+| C1 | start hub OAuth (anthropic/openai) | auth-url presentation per vendor; status polling; cancel | assert |+| C2 | flow expiry + nonce replay | `flow_expired`; replayed nonce resumes, no duplicate flow | assert |+| C3 | native channel start-failure copy | `native_subscription_exists`, `native_login_in_progress` | assert |+| C4 | full login → materialize → adoption note | manual (Incus, real accounts) | manual |++### D. Per-turn routing, fallback, capability behavior (C41–C50, C74–C81)+| ID | Steps | Expect | Status |+|---|---|---|---|+| D1 | add api_key source first, subscription-class source second | **current**: appended at tail (key burns first). Baseline assert-current; expected value flips with decision D-1 | baseline |+| D2 | turn with hop0 healthy | served; provenance records hop; usage metered | assert |+| D3 | hop0 → 429 before first output | same-turn failover to hop1; `switch` event; hop0 cooldown 60s; chat copy unchanged (silent) | assert |+| D4 | hop0 → quota (`insufficient_quota`) | fallback, cooldown 300s | assert |+| D5 | hop0 → 401 (api_key, non-refreshable) | `credential_revoked` needs_action; UI shows repair action; no mid-turn refresh attempt | assert |+| D6 | hop0 → 5xx | fallback 30s cooldown; retry-after header **ignored** (document; decide with D-4 whether to keep) | baseline |+| D7 | stream interrupt after first output | terminal frame injected per protocol; **no replay/failover**; source still settles; next turn resolves hop1 (takeover pill visible) | assert |+| D8 | cooldown `retry_at` elapses | next resolve recovers source, chain returns to hop0, `recover` event | assert |+| D9 | all hops failing | 503 `mapping_target_unavailable` + waiting copy with retry_at | assert |+| D10 | chat selects effort `high`; hop model tiers `[]` | upstream capture shows **no** `reasoning_effort` key (silent strip by design); UI note visible | assert-current |+| D11 | `POST /{backend}/v1/messages/count_tokens` | currently 404 `not_found_error` (D-2 decision: fix or document impact on Claude Code auto-compact) | baseline |+| D12 | env/catalog injection for claude/codex/opencode | `ANTHROPIC_BASE_URL/TOKEN` only for claude; codex catalog neutralized 4 keys; opencode overlay model projection shape | assert |+| D13 | member role matrix | member can PUT chains/PATCH mode; cannot create/delete source, start runtime, read usage (B15) — assert the dead-ends are at least *visible* errors, not silent UI | assert |++### E. Usage and events (C54–C60)+| ID | Steps | Expect | Status |+|---|---|---|---|+| E1 | run metered turns (mock emits usage incl. cache tokens) | totals/by-source/by-model/by-day consistent; `token_reports` shortfall honest | assert |+| E2 | `?days=` boundary: 1, 62, garbage, 100000 | 1/62 ok; garbage clamps; 100000 must not pass unbounded (B14) | fix-first |+| E3 | event feed pagination + redaction | no credential substring anywhere in events payload | assert |++### F. Migration (C61–C67)+| ID | Steps | Expect | Status |+|---|---|---|---|+| F1 | seed hermetic HOME with native claude/codex/opencode configs; scan | correct action matrix; opencode unsupported ids noted | assert |+| F2 | apply selection | copy-only import; native login committed before imported keys (one-time sort); original files untouched | assert |+| F3 | first open `/settings/models` after upgrade with importable items | banner visible (B2 — currently only in wizard: expected-fail until mounted) | fix-first |++### G. Guards and contract hygiene (C51–C53, B3,B7,B13,B16)+| ID | Steps | Expect | Status |+|---|---|---|---|+| G1 | guard echo with a gap missing `agents` | no confirm-loop (B7) — fix-first; baseline documents | fix-first |+| G2 | `PUT /agents/{backend}/sources` vs `POST .../chains/reorder` divergence | decide: delete orphan endpoint or unify (B3) | baseline |+| G3 | malformed JSON on mode/chain routes | error code distinguishable from business refusals (B13) | fix-first |++### H. Cross-protocol functional floor (owner ruling baseline)+| ID | Steps | Expect | Status |+|---|---|---|---|+| H1 | claude-protocol turn served by openai_chat source (mock) | completes; tool call↔result tuple correlates on final turn | assert |+| H2 | same with parallel tools | passes (M0 matrix failed 5/8 — if still failing, recorded as known relay behavior per ruling, surfaced in release notes, not a gate) | baseline |+| H3 | image block passthrough | behavior documented (currently untested anywhere); at minimum: no crash, terminal frame well-formed | probe |++## 4. Mapping to existing coverage++Unit/contract suites already cover: config validation, guard structure, classification tables, oauth registry, usage ledger, runtime injection. E2E must **not** duplicate them; it owns the seams those can't see: double-observe cost, cooldown-vs-next-turn timing, UI copy on live errors, guard echo round-trip, engine config conservation, member-role dead-ends.++## 5. Open decisions (owner)++- **D-1 subscription-first placement.** Restore "subscription before API key" at placement time (surgical change in `_apply_source_placement`, reuse dead `recommended_source_order`), incl. one-time re-sort of existing configs? Current shipped contract says append-at-tail. Affects D1.+- **D-2 `count_tokens` 404.** Serve it (proxy to upstream tokenizers or estimate) or document Claude Code context-estimation degradation in hub mode? Affects D11.+- **D-3 missing `modelHub.*` browser i18n keys + absent Python-bundle codes.** Fix now (makes B11 pass) or baseline as expected-fail for this round?+- **D-4 Retry-After honoring.** Keep flat cooldowns (simple, predictable) or honor upstream reset headers? Affects D6.++## 5a. Cross-lane contracts (frozen 2026-09-01)++Two implementation lanes build the suites in parallel. These contracts are the+interface between them; deviations route through the orchestrator, never+lane-to-lane.++### Mock upstream provider (owned by the pytest lane)++- Path: `tests/e2e/drivers/mock_llm_upstream.py`. **Stdlib-only** (http.server ++ threading or asyncio): it must run standalone on a bare Python 3.11+ with no+ repo install.+- Runs standalone: `python3 tests/e2e/drivers/mock_llm_upstream.py --port N+ [--host 127.0.0.1]`; also importable as a pytest fixture in `tests/e2e/`.+- Serving surface (per configured protocol correctness):+ - `GET /v1/models` — configurable inventory; supports Anthropic-style+ (`data[].id`, `display_name`, `type`) and OpenAI-style (`data[].id`,+ `created`, `owned_by`) plus relay extension fields (`context_length`,+ `pricing`) so drop-behavior can be asserted.+ - `POST /v1/messages` | `/v1/responses` | `/v1/chat/completions` — protocol-+ correct non-stream and SSE-stream responses, including the shape evidence+ auto-detect needs (`type: "message"` / `object: "response"` /+ `object: "chat.completion*"`, and family-distinctive `error.param` bodies+ for invalid probes).+- Control plane (all under `/__control/`, never proxied):+ - `POST /__control/config` — set behavior JSON: `{auth: ok|401|403_banned|402|+ 429|quota_message|5xx, stream: healthy|interrupt_after_first_output,+ models: [...], protocol: anthropic|openai_responses|openai_chat,+ models_endpoint: ok|http_404|http_500|timeout|malformed_json}`.+ - `models_endpoint` (default `ok`) applies ONLY to `GET /v1/models`;+ inference endpoints are unaffected. Evaluation order per request:+ `auth` applies first to every endpoint (including `/v1/models`); only+ when `auth: ok` does `models_endpoint` apply. An empty `models` array+ with `auth: ok` and `models_endpoint: ok` is a SUCCESSFUL empty+ inventory, distinct from discovery failure. Scenario B4 (protocol proven,+ discovery failed → 422 `inventory_unavailable` → `accept_unavailable_+ inventory` commit path) is produced by `auth: ok` ++ `models_endpoint: http_500` (or `http_404`/`timeout`/`malformed_json`).+ *(Contract amendment 2026-09-02, orchestrator ruling on the pytest lane's+ B4 blocker.)*+ - `GET /__control/requests` — returns an OBJECT `{"requests": [...]}` (not+ a bare array; extensible envelope), each record carrying method, path,+ headers subset, parsed body; `DELETE /__control/requests` resets.+ *(Shape frozen 2026-09-02.)*+- The Playwright lane consumes this ONLY over HTTP via env+ `VIBE_E2E_MOCK_UPSTREAM_URL`; it never imports the Python module. Mock-+ dependent specs skip with a clear message when the env is absent.++### Environment variables (shared vocabulary)++- `VIBE_E2E_BASE_URL` — target Avibe UI origin (default `http://127.0.0.1:5123`).+- `VIBE_E2E_MOCK_UPSTREAM_URL` — running mock upstream origin.+- `VIBE_MODEL_HUB_ENABLED=1` — required for all scenarios.+- `VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH` — offline engine manifest override for+ hermetic engine install; engine-dependent pytest scenarios must skip (not+ fail) with a clear reason when neither this nor GitHub egress is available.++### Suite conventions++- pytest: files `tests/e2e/test_model_hub_*.py`, marker `e2e_model_hub`,+ NOT part of default CI in these PRs. Scenario IDs from §3 (A1…H3) appear in+ test names or docstrings.+- Playwright: lives in `ui/e2e/`, config `ui/playwright.config.ts`, dependency+ added explicitly to `ui/package.json` devDependencies, scripts+ `npm run e2e` / `npm run e2e:headed`. Chromium only. Not wired into CI in+ this PR.+- Baseline discipline: scenarios marked `baseline` in §3 assert CURRENT+ behavior with a comment naming the open decision (D-1…D-4); `fix-first`+ scenarios land as `xfail` (pytest) / `test.fixme` (Playwright) with the+ issue reference, never as red tests.+- **Discipline tightening (orchestrator ruling 2026-09-02, post circuit+ breaker on PR #1812):**+ - *Skip policy:* only ENVIRONMENTAL preconditions may `skip` (engine binary+ unavailable BEFORE an install attempt, mock upstream absent, credentials+ required but not provisioned). Once a precondition has passed, any+ subsequent product-side failure (installer error after manifest accepted,+ OAuth-start HTTP error after engine confirmed up, etc.) is a test+ FAILURE. Every skip site states the precondition it guards.+ - *xfail granularity:* an `xfail`/`fixme` wraps ONLY the assertion known to+ be broken (e.g. the human-readable error copy). All currently enforceable+ assertions (structured API guards, state transitions, status codes) live+ in separate passing tests. A broad xfail over a mixed test is forbidden.+ - *Skip vs gap (round 5):* `skip` = this layer CANNOT execute the scenario+ (state the blocking precondition and the owning layer); `gap` = executable+ but not yet implemented (actionable; must surface in coverage+ next_priority). Never use `skip` for "not written yet."+ - *Self-audit before push (round 5):* before every push, the lane audits+ EACH spec invariant (skip policy, xfail granularity, layer honesty,+ ownership, catalog single resolver) across ALL call sites in the diff —+ invariants bind at their extensions, not at the site a review last named.+ The report lists the checklist outcome.+ - *Environment ownership invariant (orchestrator ruling 2026-09-02, round 4):*+ the harness owns every process it starts, by invariant, not by leak-list.+ Cleanup must PROVE ABSENCE: after teardown, scan the process table for any+ process whose argv references this test's unique hermetic marker (its+ `AVIBE_HOME` path) and terminate it, including detached / separately-+ sessioned engine children whose controller leader already exited. Never+ trust the recorded leader alone. Scoped strictly to the unique marker —+ no broad host-process killing — on the SUPPORTED MATRIX (macOS + Linux);+ on other platforms the opt-in subprocess harness skips with a platform+ precondition. Regression tests must cover the detached-child escape.+ SOUND ABSENCE PROOF (round 7): "absence" means no RUNNING process (state+ != zombie) references the marker. Direct children are reaped via waitpid;+ detached PIDs are polled until gone or zombie (use the process-status API,+ e.g. psutil which the product already depends on — never argv-scan alone,+ and never kill(pid,0) as an existence proof). A zombie holds no resources+ and cannot be reaped by a non-parent: a persistent zombie after the poll+ window is a logged warning, not a failure.+ STOP CONDITION (refined 2026-09-02, round 7): its substance is a RUNNING+ product process (controller, UI, managed engine) holding resources after+ teardown on a supported platform, surviving a reviewed head. If that+ happens, DO NOT patch again — reduce the owned surface: keep the+ controller+UI pair under one setsid-owned process group with pgid kill ++ waitpid, move engine-lifecycle scenarios (A2/A5/D2–D6) to skip rows owned+ by a dedicated future suite. Evidence-soundness refinements (like the+ zombie corner) and test-owned mock resources are fixed normally and do+ not trigger it.+ - *Catalog single resolver (round 4):* scenario references (top-level tests+ AND `partial_evidence.test`, AND skip-row references) resolve through ONE+ resolver shared by the checker and the metadata; the checker may not hold+ a second notion of "what a scenario references." Skip rows without a+ top-level test remain valid but their refs still resolve.+ - *Layer honesty:* a scenario this layer cannot execute is a catalog `skip`+ row with a reason and a pointer to the layer that owns it (unit suite or+ the Playwright lane) — never an `xfail` and never an unconditional-fail+ sentinel (sentinels are forbidden: they neither detect a regression nor a+ fix). Partial evidence is fine when labeled partial: a passing test that+ covers a subset of a scenario must say so in its docstring, and the+ scenario's catalog row names the covered subset.+ - *B6 rollback evidence boundary:* the pending-revocation journal at+ `$AVIBE_HOME/state/model_hub_pending_revocations.json` inside the+ test-owned hermetic home is the public evidence surface for rejected+ credential material. Tests may read it; they must NOT read engine-private+ credential blobs. If the product writes neither journal entry nor+ observable removal on failed replacement, B6 narrows to an xfail with a+ product-gap finding — never private-storage inspection.++### Playwright scope (this round)++Core flows against a live instance: capability gate redirect, runtime+install/start/stop toggle incl. blocked-stop copy, add-API-key dialog full+branches (auto-detect / manual protocol / pull models / empty-inventory+add-anyway / replace key) against the mock upstream, guard refusal → confirm+→ impact report (incl. B7 echo probe as fixme), source detail+rename/refetch/tier edit, route chain dialog add/remove/keyboard reorder,+global priority drawer, usage & logs tabs render with real metered data,+error-copy assertions (fixme where copy is known-missing per B1/D-3),+member-role dead-ends (second auth context).++## 6. Execution plan++1. Lane 1 (fixtures): mock upstream driver + offline engine manifest packaging + full-mode e2e bootstrap. No product code changes.+2. Lane 2 (scenarios A/B/E/F/G): API-level e2e against fixtures.+3. Lane 3 (scenarios D/H): turn-level e2e incl. stream capture and capture-based upstream assertions.+4. Manual C4 + native-channel D-variants folded into the next Incus regression run.+5. Fix-first items ship as separate small PRs *before* their scenario is flipped from baseline to assert.++Each lane follows `pr-delivery-loop`; suites land under `tests/e2e/test_model_hub_*.py` reusing `tests/e2e/conftest.py` and `drivers/`.diff --git a/pyproject.toml b/pyproject.tomlindex c5fa97aa1..c98de13cd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -152,6 +152,7 @@ extend-ignore = ["E501"][tool.pytest.ini_options]asyncio_mode = "auto"markers = [+ "e2e_model_hub: opt-in hermetic Model Hub HTTP and gateway scenarios","integration: tests excluded from the unit shards because they need external infrastructure (Docker + platform tokens) or minutes of real filesystem work","uses_real_paths: opt out of the autouse home/config isolation so the test can exercise real path resolvers (must remain read-only)","no_sqlite_template: opt out of the pre-migrated SQLite template for migration/bootstrap tests",diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.pyindex 22e0c9a03..fb0d2002e 100644--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@ -3,12 +3,20 @@import osimport shutilimport subprocess+import sys+import tempfileimport time+from contextlib import contextmanager+from pathlib import Path+from typing import Callable, Iterator, Mappingimport pytestimport urllib.requestimport urllib.error+from tests.e2e.drivers.model_hub_app import ModelHubTestApp+from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+# E2E tests connect to the Vibe container on this portE2E_PORT = int(os.environ.get("VIBE_E2E_PORT", "15123"))E2E_BASE_URL = f"http://127.0.0.1:{E2E_PORT}"@@ -18,6 +26,98 @@ COMPOSE_FILE = os.path.join(os.path.dirname(__file__), "..", "..", "docker-compo# When true, skip container teardown (set by run_e2e.sh --keep)KEEP_CONTAINER = os.environ.get("VIBE_E2E_KEEP", "false").lower() == "true"+_MODEL_HUB_SUPPORTED_PLATFORMS = frozenset({"darwin", "linux"})+++def pytest_collection_modifyitems(+ config: pytest.Config,+ items: list[pytest.Item],+) -> None:+ """Keep the macOS/Linux Model Hub process suites opt-in."""++ model_hub_items = [+ item+ for item in items+ if item.get_closest_marker("e2e_model_hub") is not None+ ]+ if sys.platform not in _MODEL_HUB_SUPPORTED_PLATFORMS:+ skip = pytest.mark.skip(+ reason=(+ "Model Hub E2E subprocess harness supports macOS and Linux; "+ f"host platform is {sys.platform}"+ )+ )+ for item in model_hub_items:+ item.add_marker(skip)+ return++ if "e2e_model_hub" in (config.option.markexpr or ""):+ return+ skip = pytest.mark.skip(+ reason="Model Hub E2E is opt-in; run with -m e2e_model_hub"+ )+ for item in model_hub_items:+ item.add_marker(skip)+++def mock_llm_upstream(monkeypatch):+ """Run the frozen Model Hub upstream contract on loopback."""++ with MockLLMUpstream() as upstream:+ monkeypatch.setenv("VIBE_E2E_MOCK_UPSTREAM_URL", upstream.url)+ yield upstream+++def model_hub_app_factory():+ """Build macOS/Linux runtimes, optionally seeding native HOME."""++ repo_root = Path(__file__).resolve().parents[2]++ @contextmanager+ def launch(+ *,+ enabled: bool = True,+ extra_env: Mapping[str, str] | None = None,+ before_start: Callable[[ModelHubTestApp], None] | None = None,+ ) -> Iterator[ModelHubTestApp]:+ prefix = (+ "avibe-model-hub-e2e-"+ if enabled+ else "avibe-model-hub-disabled-e2e-"+ )+ with tempfile.TemporaryDirectory(+ prefix=prefix, dir="/tmp"+ ) as runtime_root:+ runtime = ModelHubTestApp(+ repo_root,+ Path(runtime_root),+ enabled=enabled,+ extra_env=extra_env,+ )+ if before_start is not None:+ before_start(runtime)+ with runtime:+ yield runtime++ return launch+++def model_hub_app(model_hub_app_factory):+ """Run feature-enabled Avibe over real HTTP and controller IPC."""++ with model_hub_app_factory() as runtime:+ yield runtime+++def disabled_model_hub_app(model_hub_app_factory):+ """Run feature-disabled Avibe against isolated state."""++ with model_hub_app_factory(enabled=False) as runtime:+ yield runtimedef _docker_available() -> bool:diff --git a/tests/e2e/drivers/mock_llm_upstream.py b/tests/e2e/drivers/mock_llm_upstream.pynew file mode 100644index 000000000..df0e7d8aa--- /dev/null+++ b/tests/e2e/drivers/mock_llm_upstream.py@@ -0,0 +1,923 @@+"""Deterministic, stdlib-only LLM upstream for Model Hub E2E tests.++The server has no Avibe or pytest imports, so another test lane can start it+with a bare Python 3.11+ interpreter. Pytest owns only the lifecycle fixture in+tests/e2e/conftest.py.+"""++from __future__ import annotations++import argparse+import copy+import json+import threading+import time+from collections import deque+from http import HTTPStatus+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any, Mapping, Sequence+from urllib.parse import urlsplit+++AUTH_BEHAVIORS = frozenset(+ {"ok", "401", "403_banned", "402", "429", "quota_message", "5xx"}+)+STREAM_BEHAVIORS = frozenset({"healthy", "interrupt_after_first_output"})+PROTOCOLS = frozenset({"anthropic", "openai_responses", "openai_chat"})+MODELS_ENDPOINT_BEHAVIORS = frozenset(+ {"ok", "http_404", "http_500", "timeout", "malformed_json"}+)+PROTOCOL_PATHS = {+ "anthropic": "/v1/messages",+ "openai_responses": "/v1/responses",+ "openai_chat": "/v1/chat/completions",+}+CAPTURED_HEADER_NAMES = (+ "accept",+ "anthropic-beta",+ "anthropic-version",+ "authorization",+ "content-type",+ "openai-beta",+ "user-agent",+ "x-api-key",+)+DEFAULT_MODELS: tuple[dict[str, Any], ...] = (+ {+ "id": "mock-model",+ "display_name": "Mock Model",+ "context_length": 128_000,+ "pricing": {"input": "0.001", "output": "0.002"},+ },+)+MAX_CAPTURED_REQUESTS = 200+MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024+FIXED_CREATED_AT = 1_700_000_000+MODELS_ENDPOINT_TIMEOUT_SECONDS = 30+++class ConfigurationError(ValueError):+ """The control plane received an invalid behavior config."""+++class MockUpstreamState:+ """Thread-safe behavior and request-capture owner."""++ def __init__(self) -> None:+ self._lock = threading.RLock()+ self._config: dict[str, Any] = {+ "auth": "ok",+ "stream": "healthy",+ "models": [copy.deepcopy(model) for model in DEFAULT_MODELS],+ "protocol": "openai_chat",+ "models_endpoint": "ok",+ }+ self._requests: deque[dict[str, Any]] = deque(+ maxlen=MAX_CAPTURED_REQUESTS+ )++ def config(self) -> dict[str, Any]:+ with self._lock:+ return copy.deepcopy(self._config)++ def configure(self, update: Mapping[str, Any]) -> dict[str, Any]:+ unknown = set(update) - {+ "auth",+ "stream",+ "models",+ "protocol",+ "models_endpoint",+ }+ if unknown:+ raise ConfigurationError(+ f"unknown behavior fields: {', '.join(sorted(unknown))}"+ )+ candidate = self.config()+ candidate.update(copy.deepcopy(dict(update)))+ if candidate["auth"] not in AUTH_BEHAVIORS:+ raise ConfigurationError("unsupported auth behavior")+ if candidate["stream"] not in STREAM_BEHAVIORS:+ raise ConfigurationError("unsupported stream behavior")+ if candidate["protocol"] not in PROTOCOLS:+ raise ConfigurationError("unsupported protocol")+ if candidate["models_endpoint"] not in MODELS_ENDPOINT_BEHAVIORS:+ raise ConfigurationError("unsupported models endpoint behavior")+ candidate["models"] = _validated_models(candidate["models"])+ with self._lock:+ self._config = candidate+ return copy.deepcopy(self._config)++ def capture(self, record: Mapping[str, Any]) -> None:+ with self._lock:+ self._requests.append(copy.deepcopy(dict(record)))++ def requests(self) -> list[dict[str, Any]]:+ with self._lock:+ return copy.deepcopy(list(self._requests))++ def reset_requests(self) -> None:+ with self._lock:+ self._requests.clear()+++def _validated_models(value: object) -> list[dict[str, Any]]:+ if not isinstance(value, list):+ raise ConfigurationError("models must be an array")+ models: list[dict[str, Any]] = []+ for item in value:+ if isinstance(item, str):+ model = {"id": item}+ elif isinstance(item, dict):+ model = copy.deepcopy(item)+ else:+ raise ConfigurationError(+ "models entries must be strings or objects"+ )+ model_id = model.get("id")+ if not isinstance(model_id, str) or not model_id.strip():+ raise ConfigurationError("every model must have a non-empty id")+ model["id"] = model_id.strip()+ models.append(model)+ return models+++class MockLLMUpstreamHandler(BaseHTTPRequestHandler):+ """Serve the frozen Model Hub mock-upstream contract."""++ protocol_version = "HTTP/1.1"+ server_version = "AvibeMockLLM/1"++ @property+ def state(self) -> MockUpstreamState:+ return self.server.mock_state # type: ignore[attr-defined]++ def do_GET(self) -> None:+ path = urlsplit(self.path).path+ if path == "/__control/requests":+ self._write_json(+ HTTPStatus.OK, {"requests": self.state.requests()}+ )+ return+ if path == "/v1/models":+ self._capture(path, None)+ config = self.state.config()+ if config["auth"] != "ok":+ self._write_behavior_error(config)+ return+ if config["models_endpoint"] != "ok":+ self._write_models_endpoint_failure(+ config["models_endpoint"]+ )+ return+ self._write_json(+ HTTPStatus.OK,+ _models_payload(config["protocol"], config["models"]),+ )+ return+ self._write_json(HTTPStatus.NOT_FOUND, _not_found_payload())++ def do_DELETE(self) -> None:+ path = urlsplit(self.path).path+ if path == "/__control/requests":+ self.state.reset_requests()+ self._write_json(HTTPStatus.OK, {"ok": True})+ return+ self._write_json(HTTPStatus.NOT_FOUND, _not_found_payload())++ def do_POST(self) -> None:+ path = urlsplit(self.path).path+ try:+ body = self._read_json_body()+ except ValueError as exc:+ self._write_json(+ HTTPStatus.BAD_REQUEST,+ {+ "error": {+ "type": "invalid_request_error",+ "message": str(exc),+ }+ },+ )+ return++ if path == "/__control/config":+ self._configure(body)+ return+ if path not in PROTOCOL_PATHS.values():+ self._write_json(HTTPStatus.NOT_FOUND, _not_found_payload())+ return++ self._capture(path, body)+ config = self.state.config()+ protocol = config["protocol"]+ if config["auth"] != "ok":+ self._write_behavior_error(config)+ return+ if path != PROTOCOL_PATHS[protocol]:+ self._write_json(+ HTTPStatus.BAD_REQUEST,+ _invalid_probe_payload(protocol),+ )+ return+ if _is_observation_probe(protocol, body):+ self._write_json(+ HTTPStatus.BAD_REQUEST,+ _invalid_probe_payload(protocol),+ )+ return+ if isinstance(body, dict) and body.get("stream") is True:+ self._write_stream(protocol, body, config["stream"])+ return+ self._write_json(+ HTTPStatus.OK,+ _buffered_response(protocol, body),+ )++ def _configure(self, body: object) -> None:+ if not isinstance(body, dict):+ self._write_json(+ HTTPStatus.BAD_REQUEST,+ {"ok": False, "error": "config_must_be_an_object"},+ )+ return+ try:+ config = self.state.configure(body)+ except ConfigurationError as exc:+ self._write_json(+ HTTPStatus.BAD_REQUEST,+ {"ok": False, "error": str(exc)},+ )+ return+ self._write_json(+ HTTPStatus.OK, {"ok": True, "config": config}+ )++ def _read_json_body(self) -> object:+ raw_length = self.headers.get("Content-Length", "0")+ try:+ length = int(raw_length)+ except ValueError:+ raise ValueError("invalid Content-Length") from None+ if length < 0 or length > MAX_REQUEST_BODY_BYTES:+ raise ValueError("request body is too large")+ raw = self.rfile.read(length)+ if not raw:+ return None+ try:+ return json.loads(raw.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError):+ raise ValueError("request body must be valid JSON") from None++ def _capture(self, path: str, body: object) -> None:+ headers = {+ name: self.headers[name]+ for name in CAPTURED_HEADER_NAMES+ if self.headers.get(name) is not None+ }+ self.state.capture(+ {+ "method": self.command,+ "path": path,+ "headers": headers,+ "body": body,+ }+ )++ def _write_behavior_error(+ self, config: Mapping[str, Any]+ ) -> None:+ status, error_type, message, retry_after = _behavior_error(+ config["auth"]+ )+ if config["protocol"] == "anthropic":+ payload = {+ "type": "error",+ "error": {"type": error_type, "message": message},+ }+ else:+ payload = {+ "error": {+ "type": error_type,+ "code": error_type,+ "param": None,+ "message": message,+ }+ }+ headers = (+ {"Retry-After": retry_after}+ if retry_after is not None+ else None+ )+ self._write_json(status, payload, extra_headers=headers)++ def _write_models_endpoint_failure(self, behavior: str) -> None:+ if behavior == "timeout":+ self.server.shutdown_event.wait( # type: ignore[attr-defined]+ MODELS_ENDPOINT_TIMEOUT_SECONDS+ )+ return+ if behavior == "malformed_json":+ self._write_bytes(+ HTTPStatus.OK,+ b'{"object":"list","data":',+ content_type="application/json; charset=utf-8",+ )+ return+ status = (+ HTTPStatus.NOT_FOUND+ if behavior == "http_404"+ else HTTPStatus.INTERNAL_SERVER_ERROR+ )+ self._write_json(status, _not_found_payload())++ def _write_stream(+ self,+ protocol: str,+ body: Mapping[str, Any],+ stream_behavior: str,+ ) -> None:+ self.send_response(HTTPStatus.OK)+ self.send_header(+ "Content-Type", "text/event-stream; charset=utf-8"+ )+ self.send_header("Cache-Control", "no-cache")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ frames = _stream_frames(protocol, body)+ limit = len(frames)+ if stream_behavior == "interrupt_after_first_output":+ limit = 3 if protocol == "anthropic" else 2+ try:+ for frame in frames[:limit]:+ self.wfile.write(frame)+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ return++ def _write_json(+ self,+ status: int | HTTPStatus,+ payload: object,+ *,+ extra_headers: Mapping[str, str] | None = None,+ ) -> None:+ encoded = json.dumps(+ payload, separators=(",", ":"), ensure_ascii=False+ ).encode("utf-8")+ self._write_bytes(+ status,+ encoded,+ content_type="application/json; charset=utf-8",+ extra_headers=extra_headers,+ )++ def _write_bytes(+ self,+ status: int | HTTPStatus,+ body: bytes,+ *,+ content_type: str,+ extra_headers: Mapping[str, str] | None = None,+ ) -> None:+ self.send_response(int(status))+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(body)))+ for name, value in (extra_headers or {}).items():+ self.send_header(name, value)+ self.end_headers()+ try:+ self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError):+ return++ def log_message(+ self, _format: str, *_args: object+ ) -> None:+ return+++class MockLLMUpstream:+ """Background-thread lifecycle wrapper used by pytest and local probes."""++ def __init__(+ self, host: str = "127.0.0.1", port: int = 0+ ) -> None:+ self.host = host+ self.port = port+ self.state = MockUpstreamState()+ self._server: _MockThreadingHTTPServer | None = None+ self._thread: threading.Thread | None = None++ @property+ def url(self) -> str:+ if self._server is None:+ raise RuntimeError("mock upstream is not running")+ host, port = self._server.server_address[:2]+ return f"http://{host}:{port}"++ def start(self) -> "MockLLMUpstream":+ if self._server is not None:+ return self+ server = _create_server(self.host, self.port, self.state)+ thread = threading.Thread(+ target=server.serve_forever,+ name="model-hub-mock-upstream",+ daemon=True,+ )+ thread.start()+ self._server = server+ self._thread = thread+ return self++ def stop(self) -> None:+ server, thread = self._server, self._thread+ if server is None:+ return+ server.shutdown_event.set()+ try:+ server.shutdown()+ if thread is not None:+ thread.join(timeout=5)+ server.join_handler_threads(timeout=5)+ if thread is not None and thread.is_alive():+ raise RuntimeError("mock upstream serving thread did not stop")+ finally:+ server.server_close()+ self._server = None+ self._thread = None++ def active_handler_threads(self) -> tuple[threading.Thread, ...]:+ """Return live request handlers owned by this running server."""++ if self._server is None:+ return ()+ return self._server.active_handler_threads()++ def configure(self, **update: Any) -> dict[str, Any]:+ return self.state.configure(update)++ def requests(self) -> list[dict[str, Any]]:+ return self.state.requests()++ def reset_requests(self) -> None:+ self.state.reset_requests()++ def __enter__(self) -> "MockLLMUpstream":+ return self.start()++ def __exit__(self, *_exc_info: object) -> None:+ self.stop()+++class _MockThreadingHTTPServer(ThreadingHTTPServer):+ daemon_threads = False+ allow_reuse_address = True++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self.shutdown_event = threading.Event()+ self._handler_threads: set[threading.Thread] = set()+ self._handler_threads_lock = threading.Lock()+ super().__init__(*args, **kwargs)++ def process_request(+ self, request: Any, client_address: Any+ ) -> None:+ thread = threading.Thread(+ target=self._run_owned_request,+ args=(request, client_address),+ name="model-hub-mock-handler",+ daemon=False,+ )+ try:+ with self._handler_threads_lock:+ self._handler_threads.add(thread)+ thread.start()+ except BaseException:+ with self._handler_threads_lock:+ self._handler_threads.discard(thread)+ self.shutdown_request(request)+ raise++ def _run_owned_request(+ self, request: Any, client_address: Any+ ) -> None:+ self.process_request_thread(request, client_address)++ def active_handler_threads(self) -> tuple[threading.Thread, ...]:+ with self._handler_threads_lock:+ active = tuple(+ thread+ for thread in self._handler_threads+ if thread.is_alive()+ )+ self._handler_threads.intersection_update(active)+ return active++ def join_handler_threads(self, *, timeout: float) -> None:+ deadline = time.monotonic() + timeout+ while True:+ threads = self.active_handler_threads()+ if not threads:+ return+ for thread in threads:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ names = ", ".join(+ item.name for item in self.active_handler_threads()+ )+ raise RuntimeError(+ "mock upstream handler threads did not stop: "+ f"{names}"+ )+ thread.join(timeout=remaining)+++def _create_server(+ host: str,+ port: int,+ state: MockUpstreamState | None = None,+) -> _MockThreadingHTTPServer:+ server = _MockThreadingHTTPServer(+ (host, port), MockLLMUpstreamHandler+ )+ server.mock_state = state or MockUpstreamState() # type: ignore[attr-defined]+ return server+++def _models_payload(+ protocol: str, models: Sequence[Mapping[str, Any]]+) -> dict[str, Any]:+ data: list[dict[str, Any]] = []+ for raw_model in models:+ model = copy.deepcopy(dict(raw_model))+ if protocol == "anthropic":+ model.setdefault("display_name", model["id"])+ model.setdefault("type", "model")+ else:+ model.pop("display_name", None)+ model.setdefault("object", "model")+ model.setdefault("created", 0)+ model.setdefault("owned_by", "avibe-mock")+ data.append(model)+ return {"object": "list", "data": data, "has_more": False}+++def _is_observation_probe(protocol: str, body: object) -> bool:+ if not isinstance(body, dict):+ return True+ if protocol == "anthropic":+ return (+ not isinstance(body.get("model"), str)+ or body.get("max_tokens") == 0+ )+ if protocol == "openai_responses":+ return "input" not in body+ return "messages" not in body+++def _invalid_probe_payload(protocol: str) -> dict[str, Any]:+ if protocol == "anthropic":+ return {+ "type": "error",+ "error": {+ "type": "invalid_request_error",+ "message": "model is required",+ },+ }+ parameter = (+ "input" if protocol == "openai_responses" else "messages"+ )+ return {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_parameter",+ "param": parameter,+ "message": f"{parameter} is required",+ }+ }+++def _behavior_error(+ auth: str,+) -> tuple[int, str, str, str | None]:+ rows = {+ "401": (401, "authentication_error", "invalid API key", None),+ "403_banned": (403, "account_banned", "account banned", None),+ "402": (402, "billing_error", "payment required", None),+ "429": (429, "rate_limit_error", "rate limit exceeded", "120"),+ "quota_message": (+ 429,+ "insufficient_quota",+ "insufficient quota",+ "300",+ ),+ "5xx": (503, "server_error", "upstream unavailable", "600"),+ }+ return rows[auth]+++def _requested_model(body: object) -> str:+ if (+ isinstance(body, dict)+ and isinstance(body.get("model"), str)+ ):+ return body["model"]+ return "mock-model"+++def _buffered_response(+ protocol: str, body: object+) -> dict[str, Any]:+ model = _requested_model(body)+ if protocol == "anthropic":+ return {+ "id": "msg_mock_001",+ "type": "message",+ "role": "assistant",+ "model": model,+ "content": [{"type": "text", "text": "mock response"}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {+ "input_tokens": 12,+ "cache_read_input_tokens": 3,+ "cache_creation_input_tokens": 0,+ "output_tokens": 5,+ },+ }+ if protocol == "openai_responses":+ return {+ "id": "resp_mock_001",+ "object": "response",+ "created_at": FIXED_CREATED_AT,+ "status": "completed",+ "model": model,+ "output": [+ {+ "id": "msg_mock_001",+ "type": "message",+ "status": "completed",+ "role": "assistant",+ "content": [+ {+ "type": "output_text",+ "text": "mock response",+ "annotations": [],+ }+ ],+ }+ ],+ "usage": {+ "input_tokens": 12,+ "input_tokens_details": {"cached_tokens": 3},+ "output_tokens": 5,+ "total_tokens": 17,+ },+ }+ return {+ "id": "chatcmpl_mock_001",+ "object": "chat.completion",+ "created": FIXED_CREATED_AT,+ "model": model,+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "mock response",+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {+ "prompt_tokens": 12,+ "prompt_tokens_details": {"cached_tokens": 3},+ "completion_tokens": 5,+ "total_tokens": 17,+ },+ }+++def _sse(+ event_name: str | None, payload: object+) -> bytes:+ lines: list[str] = []+ if event_name is not None:+ lines.append(f"event: {event_name}")+ data = (+ payload+ if isinstance(payload, str)+ else json.dumps(payload, separators=(",", ":"))+ )+ lines.append(f"data: {data}")+ return ("\n".join(lines) + "\n\n").encode("utf-8")+++def _stream_frames(+ protocol: str, body: Mapping[str, Any]+) -> list[bytes]:+ model = _requested_model(body)+ if protocol == "anthropic":+ return _anthropic_stream_frames(model)+ if protocol == "openai_responses":+ return _responses_stream_frames(model)+ return _chat_stream_frames(model)+++def _anthropic_stream_frames(model: str) -> list[bytes]:+ return [+ _sse(+ "message_start",+ {+ "type": "message_start",+ "message": {+ "id": "msg_mock_001",+ "type": "message",+ "role": "assistant",+ "model": model,+ "content": [],+ "usage": {+ "input_tokens": 12,+ "cache_read_input_tokens": 3,+ "cache_creation_input_tokens": 0,+ "output_tokens": 0,+ },+ },+ },+ ),+ _sse(+ "content_block_start",+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""},+ },+ ),+ _sse(+ "content_block_delta",+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "mock response",+ },+ },+ ),+ _sse(+ "content_block_stop",+ {"type": "content_block_stop", "index": 0},+ ),+ _sse(+ "message_delta",+ {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": None,+ },+ "usage": {"output_tokens": 5},+ },+ ),+ _sse("message_stop", {"type": "message_stop"}),+ ]+++def _responses_stream_frames(model: str) -> list[bytes]:+ return [+ _sse(+ "response.created",+ {+ "type": "response.created",+ "sequence_number": 0,+ "response": {+ "id": "resp_mock_001",+ "object": "response",+ "status": "in_progress",+ "model": model,+ },+ },+ ),+ _sse(+ "response.output_text.delta",+ {+ "type": "response.output_text.delta",+ "sequence_number": 1,+ "item_id": "msg_mock_001",+ "output_index": 0,+ "content_index": 0,+ "delta": "mock response",+ },+ ),+ _sse(+ "response.completed",+ {+ "type": "response.completed",+ "sequence_number": 2,+ "response": {+ "id": "resp_mock_001",+ "object": "response",+ "status": "completed",+ "model": model,+ "usage": {+ "input_tokens": 12,+ "input_tokens_details": {+ "cached_tokens": 3+ },+ "output_tokens": 5,+ "total_tokens": 17,+ },+ },+ },+ ),+ ]+++def _chat_stream_frames(model: str) -> list[bytes]:+ common = {+ "id": "chatcmpl_mock_001",+ "object": "chat.completion.chunk",+ "created": FIXED_CREATED_AT,+ "model": model,+ }+ return [+ _sse(+ None,+ {+ **common,+ "choices": [+ {+ "index": 0,+ "delta": {"role": "assistant"},+ "finish_reason": None,+ }+ ],+ },+ ),+ _sse(+ None,+ {+ **common,+ "choices": [+ {+ "index": 0,+ "delta": {"content": "mock response"},+ "finish_reason": None,+ }+ ],+ },+ ),+ _sse(+ None,+ {+ **common,+ "choices": [],+ "usage": {+ "prompt_tokens": 12,+ "prompt_tokens_details": {+ "cached_tokens": 3+ },+ "completion_tokens": 5,+ "total_tokens": 17,+ },+ },+ ),+ _sse(None, "[DONE]"),+ ]+++def _not_found_payload() -> dict[str, Any]:+ return {+ "error": {+ "type": "not_found_error",+ "code": "not_found_error",+ "message": "not found",+ }+ }+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--host", default="127.0.0.1")+ parser.add_argument("--port", type=int, required=True)+ args = parser.parse_args(argv)+ server = _create_server(args.host, args.port)+ host, port = server.server_address[:2]+ print(+ f"Mock LLM upstream listening at http://{host}:{port}",+ flush=True,+ )+ try:+ server.serve_forever()+ except KeyboardInterrupt:+ pass+ finally:+ server.shutdown_event.set()+ server.join_handler_threads(timeout=5)+ server.server_close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/e2e/drivers/model_hub_app.py b/tests/e2e/drivers/model_hub_app.pynew file mode 100644index 000000000..1c560c9f2--- /dev/null+++ b/tests/e2e/drivers/model_hub_app.py@@ -0,0 +1,651 @@+"""Hermetic real-HTTP Avibe runtime for Model Hub E2E scenarios."""++from __future__ import annotations++import http.cookiejar+import json+import logging+import os+import signal+import socket+import subprocess+import sys+import time+from collections.abc import Iterable+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Mapping+from urllib.error import HTTPError, URLError+from urllib.request import (+ HTTPCookieProcessor,+ ProxyHandler,+ Request,+ build_opener,+)++import psutil+++_MISSING = object()+_MUTATION_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})+_SAFE_INHERITED_ENV = (+ "LANG",+ "LC_ALL",+ "LC_CTYPE",+ "SSL_CERT_DIR",+ "SSL_CERT_FILE",+ "TZ",+)+_UI_PORT_START_ATTEMPTS = 3+_OWNED_PROCESS_GRACE_SECONDS = 3.0+_OWNED_PROCESS_KILL_SECONDS = 2.0+_OWNED_PROCESS_POLL_SECONDS = 0.05+_DEAD_PROCESS_STATUSES = frozenset(+ status+ for status in (+ psutil.STATUS_ZOMBIE,+ getattr(psutil, "STATUS_DEAD", None),+ )+ if status is not None+)+logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class HTTPResult:+ """One complete HTTP response, including non-2xx responses."""++ status: int+ headers: Mapping[str, str]+ body: bytes++ def json(self) -> Any:+ try:+ return json.loads(self.body.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ preview = self.body[:500].decode("utf-8", errors="replace")+ raise AssertionError(+ f"HTTP {self.status} did not return JSON: {preview!r}"+ ) from exc+++@dataclass(frozen=True)+class _OwnedProcess:+ """Stable identity for one running process owned by the harness."""++ pid: int+ process_group: int+ create_time: float+ argv: str+++class ModelHubHTTPClient:+ """Cookie- and CSRF-aware client for the browser-visible API."""++ def __init__(self, base_url: str) -> None:+ self.base_url = base_url.rstrip("/")+ self._cookies = http.cookiejar.CookieJar()+ self._opener = build_opener(+ ProxyHandler({}),+ HTTPCookieProcessor(self._cookies),+ )+ self._csrf_token: str | None = None++ def request(+ self,+ method: str,+ path: str,+ *,+ json_body: object = _MISSING,+ raw_body: bytes | None = None,+ headers: Mapping[str, str] | None = None,+ timeout: float = 20,+ ) -> HTTPResult:+ method = method.upper()+ if json_body is not _MISSING and raw_body is not None:+ raise ValueError("json_body and raw_body are mutually exclusive")+ request_headers = dict(headers or {})+ body = raw_body+ if json_body is not _MISSING:+ body = json.dumps(+ json_body,+ separators=(",", ":"),+ ensure_ascii=False,+ ).encode("utf-8")+ request_headers.setdefault("Content-Type", "application/json")+ if method in _MUTATION_METHODS:+ request_headers.setdefault("Origin", self.base_url)+ request_headers.setdefault(+ "X-Vibe-CSRF-Token", self._csrf()+ )+ request = Request(+ f"{self.base_url}{path}",+ data=body,+ headers=request_headers,+ method=method,+ )+ try:+ response = self._opener.open(request, timeout=timeout)+ except HTTPError as exc:+ response = exc+ with response:+ return HTTPResult(+ status=response.status,+ headers=dict(response.headers),+ body=response.read(),+ )++ def get(self, path: str, *, timeout: float = 20) -> HTTPResult:+ return self.request("GET", path, timeout=timeout)++ def post(+ self, path: str, json_body: object = _MISSING+ ) -> HTTPResult:+ return self.request("POST", path, json_body=json_body)++ def put(+ self, path: str, json_body: object = _MISSING+ ) -> HTTPResult:+ return self.request("PUT", path, json_body=json_body)++ def patch(+ self, path: str, json_body: object = _MISSING+ ) -> HTTPResult:+ return self.request("PATCH", path, json_body=json_body)++ def delete(+ self, path: str, json_body: object = _MISSING+ ) -> HTTPResult:+ return self.request("DELETE", path, json_body=json_body)++ def _csrf(self) -> str:+ if self._csrf_token is None:+ response = self.get("/api/csrf-token")+ if response.status != 200:+ raise RuntimeError(+ f"CSRF bootstrap returned HTTP {response.status}"+ )+ payload = response.json()+ token = payload.get("csrf_token")+ if not isinstance(token, str) or not token:+ raise RuntimeError("CSRF bootstrap returned no token")+ self._csrf_token = token+ return self._csrf_token+++class ModelHubTestApp:+ """Start isolated controller and UI processes on macOS or Linux."""++ def __init__(+ self,+ repo_root: Path,+ runtime_root: Path,+ *,+ enabled: bool = True,+ extra_env: Mapping[str, str] | None = None,+ ) -> None:+ self.repo_root = repo_root.resolve()+ self.runtime_root = runtime_root.resolve()+ self.enabled = enabled+ self.port = _ephemeral_port()+ self.base_url = f"http://127.0.0.1:{self.port}"+ self.client = ModelHubHTTPClient(self.base_url)+ self.home = self.runtime_root / "home"+ self.avibe_home = self.runtime_root / "avibe-home"+ self.logs = self.runtime_root / "process-logs"+ self.env = self._environment(extra_env or {})+ self._controller: subprocess.Popen[bytes] | None = None+ self._ui: subprocess.Popen[bytes] | None = None+ self._controller_log = None+ self._ui_log = None+ self._ui_log_offset = 0++ def _environment(+ self, extra_env: Mapping[str, str]+ ) -> dict[str, str]:+ env = {+ name: os.environ[name]+ for name in _SAFE_INHERITED_ENV+ if os.environ.get(name)+ }+ env.update(+ {+ "PATH": os.pathsep.join(+ dict.fromkeys(+ (+ str(Path(sys.executable).resolve().parent),+ *os.defpath.split(os.pathsep),+ )+ )+ ),+ "HOME": str(self.home),+ "AVIBE_HOME": str(self.avibe_home),+ "XDG_CONFIG_HOME": str(self.home / ".config"),+ "XDG_CACHE_HOME": str(self.home / ".cache"),+ "XDG_DATA_HOME": str(self.home / ".local" / "share"),+ "TMPDIR": str(self.runtime_root / "tmp"),+ "TMP": str(self.runtime_root / "tmp"),+ "TEMP": str(self.runtime_root / "tmp"),+ "CODEX_HOME": str(self.home / ".codex"),+ "CLAUDE_CONFIG_DIR": str(self.home / ".claude"),+ "VIBE_MODEL_HUB_ENABLED": "1" if self.enabled else "0",+ "VIBE_MODEL_HUB_ENGINE_OFFLINE": "1",+ "VIBE_MEMORY_OFFLINE": "1",+ "VIBE_SHOW_RUNTIME_OFFLINE": "1",+ "VIBE_TMUX_OFFLINE": "1",+ "VIBE_GIT_OFFLINE": "1",+ "VIBE_STARTUP_DEPENDENCY_RECONCILE": "0",+ "VIBE_INSTALL_SKIP_ASKILL": "1",+ "VIBE_ASKILL_AUTO_UPDATE": "0",+ "VIBE_DISABLE_STDOUT_LOGGING": "1",+ "VIBE_INTERNAL_DISPATCH_SOCKET": str(+ self.runtime_root / "dispatch.sock"+ ),+ "VIBE_SENTRY_DSN": "",+ "NO_PROXY": "127.0.0.1,localhost",+ "no_proxy": "127.0.0.1,localhost",+ }+ )+ env.update(extra_env)+ return env++ def start(self) -> "ModelHubTestApp":+ try:+ self.home.mkdir(parents=True, exist_ok=True)+ self.avibe_home.mkdir(parents=True, exist_ok=True)+ self.logs.mkdir(parents=True, exist_ok=True)+ (self.runtime_root / "tmp").mkdir(+ parents=True, exist_ok=True+ )+ self._initialize_config()+ self._start_controller()+ self._start_ui_with_port_retry()+ except BaseException as exc:+ self.stop()+ if not isinstance(exc, Exception):+ raise+ details = self.diagnostics()+ raise RuntimeError(+ f"hermetic Model Hub app failed to start\n{details}"+ ) from exc+ return self++ def _initialize_config(self) -> None:+ config_path = self.avibe_home / "config" / "config.json"+ if config_path.exists():+ return+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ "from config.v2_config import V2Config; "+ "config = V2Config.default(); "+ "config.update.auto_update = False; "+ "config.update.check_interval_minutes = 0; "+ "config.save()",+ ],+ cwd=self.repo_root,+ env=self.env,+ capture_output=True,+ timeout=20,+ )+ if result.returncode != 0:+ output = (result.stdout + result.stderr).decode(+ "utf-8", errors="replace"+ )+ raise RuntimeError(+ f"could not initialize hermetic config: {output}"+ )++ def _start_controller(self) -> None:+ if self._controller is not None:+ raise RuntimeError("controller is already running")+ self._controller_log = (self.logs / "controller.log").open("ab")+ self._controller = subprocess.Popen(+ [sys.executable, "main.py", str(self.avibe_home)],+ cwd=self.repo_root,+ env=self.env,+ stdout=self._controller_log,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )++ def _start_ui(self) -> None:+ if self._ui is not None:+ raise RuntimeError("UI is already running")+ log_path = self.logs / "ui.log"+ self._ui_log_offset = (+ log_path.stat().st_size if log_path.exists() else 0+ )+ self._ui_log = log_path.open("ab")+ expression = (+ "from vibe.ui_server import run_ui_server; "+ f"run_ui_server('127.0.0.1', {self.port})"+ )+ self._ui = subprocess.Popen(+ [sys.executable, "-c", expression, str(self.avibe_home)],+ cwd=self.repo_root,+ env=self.env,+ stdout=self._ui_log,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )++ def _start_ui_with_port_retry(self) -> None:+ for attempt in range(_UI_PORT_START_ATTEMPTS):+ self._start_ui()+ try:+ self.wait_ready()+ except RuntimeError:+ exhausted = attempt + 1 >= _UI_PORT_START_ATTEMPTS+ if exhausted or not self._ui_lost_address_in_use_race():+ raise+ self._stop_ui()+ self.port = _ephemeral_port()+ self.base_url = f"http://127.0.0.1:{self.port}"+ self.client = ModelHubHTTPClient(self.base_url)+ else:+ return+ raise AssertionError("UI port retry loop exhausted without a result")++ def _ui_lost_address_in_use_race(self) -> bool:+ if (+ self._controller is None+ or self._controller.poll() is not None+ or self._ui is None+ or self._ui.poll() is None+ ):+ return False+ try:+ output = (self.logs / "ui.log").read_bytes()[+ self._ui_log_offset :+ ].lower()+ except OSError:+ return False+ return any(+ marker in output+ for marker in (+ b"address already in use",+ b"errno 48",+ b"errno 98",+ )+ )++ def wait_ready(self, *, timeout: float = 40) -> None:+ deadline = time.monotonic() + timeout+ latest: str | None = None+ while time.monotonic() < deadline:+ self._assert_processes_alive()+ try:+ response = self.client.get(+ "/api/models/sources", timeout=1+ )+ payload = response.json()+ if self.enabled:+ if response.status == 200 and payload.get("ok") is True:+ return+ elif (+ response.status == 404+ and payload.get("error") == "feature_disabled"+ ):+ return+ latest = f"HTTP {response.status}: {payload!r}"+ except (AssertionError, OSError, URLError) as exc:+ latest = repr(exc)+ time.sleep(0.1)+ raise TimeoutError(+ "Model Hub HTTP/IPC readiness timed out"+ + (f": {latest}" if latest else "")+ )++ def restart_controller(self) -> None:+ self._stop_process(self._controller)+ self._controller = None+ if self._controller_log is not None:+ self._controller_log.close()+ self._controller_log = None+ self._start_controller()+ self.wait_ready()++ def _assert_processes_alive(self) -> None:+ for label, process in (+ ("controller", self._controller),+ ("UI", self._ui),+ ):+ if process is None or process.poll() is not None:+ code = None if process is None else process.returncode+ raise RuntimeError(f"{label} exited with status {code}")++ def diagnostics(self) -> str:+ sections = []+ for label, path in (+ ("controller", self.logs / "controller.log"),+ ("ui", self.logs / "ui.log"),+ ("service", self.avibe_home / "logs" / "vibe_remote.log"),+ ):+ try:+ content = path.read_text(+ encoding="utf-8", errors="replace"+ )[-12_000:]+ except OSError:+ continue+ sections.append(f"--- {label} ---\n{content}")+ return "\n".join(sections)++ def stop(self) -> None:+ self._stop_ui()+ self._stop_process(self._controller)+ self._controller = None+ if self._controller_log is not None:+ self._controller_log.close()+ self._controller_log = None+ self._terminate_owned_process_groups()++ def _stop_ui(self) -> None:+ self._stop_process(self._ui)+ self._ui = None+ if self._ui_log is not None:+ self._ui_log.close()+ self._ui_log = None++ @staticmethod+ def _stop_process(process: subprocess.Popen[bytes] | None) -> None:+ if process is None:+ return+ if process.poll() is not None:+ process.wait(timeout=0)+ return+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ process.wait(timeout=5)+ return+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ process.wait(timeout=5)++ def _terminate_owned_process_groups(self) -> None:+ """Prove no running process still references the runtime marker."""++ owned = self._owned_process_groups()+ if not owned:+ return+ tracked = {+ process.pid: process+ for processes in owned.values()+ for process in processes+ }+ self._signal_process_groups(owned, signal.SIGTERM)+ running, zombies = self._wait_for_owned_processes(+ tracked,+ _OWNED_PROCESS_GRACE_SECONDS+ )+ if running:+ self._signal_process_groups(+ self._group_processes(running.values()),+ signal.SIGKILL,+ )+ running, zombies = self._wait_for_owned_processes(+ tracked,+ _OWNED_PROCESS_KILL_SECONDS+ )+ self._log_persistent_zombies(zombies)+ if running:+ details = "; ".join(+ f"pid={process.pid} pgid={process.process_group} "+ f"argv={process.argv!r}"+ for process in sorted(+ running.values(), key=lambda item: item.pid+ )+ )+ raise RuntimeError(+ "hermetic Model Hub cleanup left running owned processes: "+ f"{details}"+ )++ def _owned_process_groups(+ self,+ ) -> dict[int, list[_OwnedProcess]]:+ marker = str(self.avibe_home)+ try:+ candidates = psutil.process_iter(+ attrs=["pid", "cmdline", "create_time", "status"],+ ad_value=None,+ )+ except psutil.Error as exc:+ raise RuntimeError(+ "could not scan the process table for hermetic children"+ ) from exc++ current_group = os.getpgrp()+ owned: dict[int, list[_OwnedProcess]] = {}+ for candidate in candidates:+ info = candidate.info+ status = info.get("status")+ if status in _DEAD_PROCESS_STATUSES:+ continue+ cmdline = info.get("cmdline")+ if not isinstance(cmdline, list):+ continue+ argv = " ".join(str(part) for part in cmdline)+ if marker not in argv:+ continue+ try:+ pid = int(info["pid"])+ process_group = os.getpgid(pid)+ create_time = float(info["create_time"])+ except (KeyError, TypeError, ValueError, ProcessLookupError):+ continue+ if process_group == current_group:+ raise RuntimeError(+ "hermetic child shares the pytest process group; "+ f"refusing to signal pgid {current_group}"+ )+ owned.setdefault(process_group, []).append(+ _OwnedProcess(+ pid=pid,+ process_group=process_group,+ create_time=create_time,+ argv=argv,+ )+ )+ return owned++ @staticmethod+ def _group_processes(+ processes: Iterable[_OwnedProcess],+ ) -> dict[int, list[_OwnedProcess]]:+ grouped: dict[int, list[_OwnedProcess]] = {}+ for process in processes:+ grouped.setdefault(process.process_group, []).append(process)+ return grouped++ @staticmethod+ def _signal_process_groups(+ owned: Mapping[int, list[_OwnedProcess]],+ signum: signal.Signals,+ ) -> None:+ for process_group in owned:+ try:+ os.killpg(process_group, signum)+ except ProcessLookupError:+ pass++ def _wait_for_owned_processes(+ self,+ tracked: dict[int, _OwnedProcess],+ timeout: float,+ ) -> tuple[dict[int, _OwnedProcess], dict[int, _OwnedProcess]]:+ deadline = time.monotonic() + timeout+ while True:+ for processes in self._owned_process_groups().values():+ for process in processes:+ previous = tracked.get(process.pid)+ if (+ previous is None+ or previous.create_time != process.create_time+ ):+ tracked[process.pid] = process+ running: dict[int, _OwnedProcess] = {}+ zombies: dict[int, _OwnedProcess] = {}+ for pid, process in tracked.items():+ state = self._tracked_process_state(process)+ if state == "running":+ running[pid] = process+ elif state == "zombie":+ zombies[pid] = process+ if not running or time.monotonic() >= deadline:+ return running, zombies+ time.sleep(_OWNED_PROCESS_POLL_SECONDS)++ @staticmethod+ def _tracked_process_state(process: _OwnedProcess) -> str:+ try:+ candidate = psutil.Process(process.pid)+ if candidate.create_time() != process.create_time:+ return "gone"+ status = candidate.status()+ except psutil.ZombieProcess:+ return "zombie"+ except psutil.NoSuchProcess:+ return "gone"+ except psutil.Error as exc:+ raise RuntimeError(+ "could not read the status of an owned process: "+ f"pid={process.pid}"+ ) from exc+ if status in _DEAD_PROCESS_STATUSES:+ return "zombie"+ return "running"++ @staticmethod+ def _log_persistent_zombies(+ zombies: Mapping[int, _OwnedProcess],+ ) -> None:+ for process in zombies.values():+ if ModelHubTestApp._tracked_process_state(process) != "zombie":+ continue+ logger.warning(+ "hermetic Model Hub child is a harmless zombie awaiting its "+ "parent and holds no resources: pid=%s pgid=%s argv=%r",+ process.pid,+ process.process_group,+ process.argv,+ )++ def __enter__(self) -> "ModelHubTestApp":+ return self.start()++ def __exit__(self, *_exc_info: object) -> None:+ self.stop()+++def _ephemeral_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])diff --git a/tests/e2e/test_model_hub_guards.py b/tests/e2e/test_model_hub_guards.pynew file mode 100644index 000000000..ed034ca47--- /dev/null+++ b/tests/e2e/test_model_hub_guards.py@@ -0,0 +1,175 @@+"""Model Hub guard round-trip and route-contract E2E scenarios."""++from __future__ import annotations++import pytest++from tests.e2e.test_model_hub_sources import (+ MENU_MODEL,+ _configure_protocol,+ _create_source,+)+++pytestmark = pytest.mark.e2e_model_hub+++def _two_source_chain(app, upstream):+ _configure_protocol(+ upstream,+ "anthropic",+ models=[{"id": MENU_MODEL}],+ )+ first, _ = _create_source(+ app,+ upstream,+ nonce="scn_g000000000000001",+ vendor="anthropic",+ display_name="First guard source",+ )+ second, _ = _create_source(+ app,+ upstream,+ nonce="scn_g000000000000002",+ vendor="anthropic",+ display_name="Second guard source",+ )+ mode = app.client.patch(+ "/api/models/agents/claude/mode", {"mode": "hub"}+ )+ assert mode.status == 200, mode.json()+ hops = [+ {"source_id": first["id"], "model_id": MENU_MODEL},+ {"source_id": second["id"], "model_id": MENU_MODEL},+ ]+ chain = app.client.put(+ f"/api/models/agents/claude/chain?model={MENU_MODEL}",+ {"hops": hops},+ )+ assert chain.status == 200, chain.json()+ return first, second, hops+++def test_g1_guard_echo_missing_agents_does_not_loop(+ mock_llm_upstream,+ model_hub_app,+) -> None:+ """G1: a legacy guard echo without agents remains confirmable."""++ first, _, _ = _two_source_chain(model_hub_app, mock_llm_upstream)+ endpoint = f"/api/models/sources/{first['id']}"+ refused = model_hub_app.client.delete(endpoint, {})+ refusal = refused.json()+ assert refused.status == 409, refusal+ echo_without_agents = [+ {+ key: value+ for key, value in interruption.items()+ if key != "agents"+ }+ for interruption in refusal["would_interrupt"]+ ]+ committed = model_hub_app.client.delete(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": echo_without_agents,+ },+ )+ assert committed.status == 200, committed.json()+++def test_g2_source_order_write_and_chain_reorder_are_divergent(+ mock_llm_upstream,+ model_hub_app,+) -> None:+ """G2: the orphan order endpoint persists order without applying it."""++ # Open decisions D-1..D-4 do not assign the B3 endpoint-divergence+ # decision; this baseline records the current split without inventing one.+ first, second, original_hops = _two_source_chain(+ model_hub_app, mock_llm_upstream+ )+ reversed_order = [second["id"], first["id"]]+ order_write = model_hub_app.client.put(+ "/api/models/agents/claude/sources",+ {"order": reversed_order},+ )+ assert order_write.status == 200, order_write.json()+ assert order_write.json()["agent"]["sources"]["order"] == reversed_order++ chain_before = model_hub_app.client.get(+ f"/api/models/agents/claude/chain?model={MENU_MODEL}"+ )+ assert chain_before.status == 200, chain_before.json()+ assert [+ {+ "source_id": hop["source_id"],+ "model_id": hop["model_id"],+ }+ for hop in chain_before.json()["chain"]["chain"]+ ] == original_hops++ applied = model_hub_app.client.post(+ "/api/models/agents/claude/chains/reorder"+ )+ assert applied.status == 200, applied.json()+ chain_after = model_hub_app.client.get(+ f"/api/models/agents/claude/chain?model={MENU_MODEL}"+ )+ assert chain_after.status == 200, chain_after.json()+ assert [+ hop["source_id"] for hop in chain_after.json()["chain"]["chain"]+ ] == reversed_order+++def test_g3_malformed_json_and_business_refusals_are_client_errors(+ model_hub_app,+) -> None:+ """G3: malformed JSON and parsed business refusals remain client errors."""++ headers = {"Content-Type": "application/json"}+ malformed_mode = model_hub_app.client.request(+ "PATCH",+ "/api/models/agents/claude/mode",+ raw_body=b'{"mode":',+ headers=headers,+ )+ malformed_chain = model_hub_app.client.request(+ "POST",+ "/api/models/agents/claude/chains/reorder",+ raw_body=b'{"order":',+ headers=headers,+ )+ business_refusal = model_hub_app.client.post(+ "/api/models/agents/claude/chains/reorder",+ {"order": None},+ )+ assert malformed_mode.status == malformed_chain.status == 400+ # B13/D-3 remains open. The mode route currently returns the framework's+ # unlocalized malformed-JSON shape while the chain route folds it into a+ # Model Hub business refusal.+ assert malformed_mode.json() == {"error": "Malformed JSON"}+ assert business_refusal.status == 400+ assert business_refusal.json()["error"] == "invalid_source_order"+++ reason=(+ "G3/B13 fix-first: malformed chain JSON is currently folded into the "+ "same invalid_source_order code as a parsed business refusal"+ )+)+def test_g3_malformed_json_is_distinct_from_business_refusals(+ model_hub_app,+) -> None:+ """G3: malformed chain JSON has a code distinct from domain errors."""++ headers = {"Content-Type": "application/json"}+ malformed_chain = model_hub_app.client.request(+ "POST",+ "/api/models/agents/claude/chains/reorder",+ raw_body=b'{"order":',+ headers=headers,+ )+ assert malformed_chain.json()["error"] == "malformed_json"diff --git a/tests/e2e/test_model_hub_migration.py b/tests/e2e/test_model_hub_migration.pynew file mode 100644index 000000000..f427455a1--- /dev/null+++ b/tests/e2e/test_model_hub_migration.py@@ -0,0 +1,229 @@+"""Model Hub native-config migration scenarios over real HTTP and IPC."""++from __future__ import annotations++import hashlib+import json+from pathlib import Path++import pytest++from tests.e2e.test_model_hub_sources import _configure_protocol+++pytestmark = pytest.mark.e2e_model_hub+++def _write(path: Path, content: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+++def _seed_native_configs(app, upstream_url: str) -> list[Path]:+ home = app.home+ paths = [+ home / ".claude" / "settings.json",+ home / ".codex" / "auth.json",+ home / ".codex" / "config.toml",+ home / ".config" / "opencode" / "opencode.json",+ home / ".local" / "share" / "opencode" / "auth.json",+ home / ".cache" / "opencode" / "models.json",+ ]+ _write(+ paths[0],+ json.dumps(+ {+ "env": {+ "ANTHROPIC_API_KEY": "sk-ant-e2e-copy-only-123456",+ "ANTHROPIC_BASE_URL": upstream_url,+ },+ "permissions": {"allow": ["Read"]},+ },+ indent=2,+ )+ + "\n",+ )+ _write(+ paths[1],+ json.dumps(+ {+ "auth_mode": "chatgpt",+ "tokens": {"access_token": "codex-oauth-e2e-123456"},+ }+ ),+ )+ _write(paths[2], 'cli_auth_credentials_store = "file"\n')+ _write(+ paths[3],+ json.dumps(+ {+ "provider": {+ "alibaba-cn": {+ "options": {+ "apiKey": "sk-unsupported-e2e-123456",+ "baseURL": upstream_url,+ }+ }+ }+ }+ ),+ )+ _write(+ paths[4],+ json.dumps(+ {+ "alibaba-cn": {+ "type": "api",+ "key": "sk-unsupported-e2e-123456",+ }+ }+ ),+ )+ _write(+ paths[5],+ json.dumps(+ {+ "alibaba-cn": {+ "id": "alibaba-cn",+ "npm": "@ai-sdk/openai-compatible",+ "api": upstream_url,+ }+ }+ ),+ )+ return paths+++def _launch_seeded_app(model_hub_app_factory, mock_llm_upstream):+ seeded_paths: list[Path] = []++ def seed(app) -> None:+ seeded_paths.extend(+ _seed_native_configs(app, mock_llm_upstream.url)+ )++ return model_hub_app_factory(before_start=seed), seeded_paths+++def test_f1_native_scan_returns_the_copy_only_action_matrix(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """F1: Claude key and Codex login map to import/keep-native actions."""++ launch, _ = _launch_seeded_app(+ model_hub_app_factory, mock_llm_upstream+ )+ with launch as app:+ response = app.client.post("/api/models/migration/scan", {})+ body = response.json()+ assert response.status == 200, body+ items = body["scan"]["items"]+ assert [+ (item["backend"], item["kind"], item["proposed_action"])+ for item in items+ ] == [+ ("claude", "api_key", "import"),+ ("codex", "oauth_native", "keep_native"),+ ]+ assert all(item["selected"] is True for item in items)+ serialized = json.dumps(items)+ for secret in (+ "sk-ant-e2e-copy-only-123456",+ "codex-oauth-e2e-123456",+ "sk-unsupported-e2e-123456",+ ):+ assert secret not in serialized+++ reason=(+ "F1 product/contract gap: unsupported OpenCode provider ids are silently "+ "dropped and migration-scan.schema.json has no notice field"+ )+)+def test_f1_unsupported_opencode_provider_ids_are_noted(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """F1: an unsupported native OpenCode provider must be visible as a note."""++ launch, _ = _launch_seeded_app(+ model_hub_app_factory, mock_llm_upstream+ )+ with launch as app:+ response = app.client.post("/api/models/migration/scan", {})+ assert any(+ item["backend"] == "opencode"+ and item.get("notes_key")+ for item in response.json()["scan"]["items"]+ )+++def test_f2_apply_is_copy_only_and_places_native_login_before_keys(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """F2: apply copies selected material and performs the one-time sort."""++ seeded_api_key = "sk-ant-e2e-copy-only-123456"+ seeded_api_key_digest = hashlib.sha256(+ seeded_api_key.encode("utf-8")+ ).hexdigest()+ _configure_protocol(+ mock_llm_upstream,+ "anthropic",+ models=[{"id": "claude-sonnet-4-6"}],+ )+ launch, seeded_paths = _launch_seeded_app(+ model_hub_app_factory, mock_llm_upstream+ )+ with launch as app:+ before = {path: path.read_bytes() for path in seeded_paths}+ scan = app.client.post("/api/models/migration/scan", {})+ scan_body = scan.json()+ assert scan.status == 200, scan_body+ item_ids = [item["id"] for item in scan_body["scan"]["items"]]+ mock_llm_upstream.reset_requests()++ applied = app.client.post(+ "/api/models/migration/apply", {"item_ids": item_ids}+ )+ body = applied.json()+ assert applied.status == 200, body+ assert body["applied"] == 2+ assert [+ (source["vendor"], source["kind"], source["supply_channel"])+ for source in body["sources"]+ ] == [+ ("openai", "subscription", "native_cli"),+ ("anthropic", "api_key", "hub"),+ ]+ assert all(path.read_bytes() == content for path, content in before.items())++ listed = app.client.get("/api/models/sources")+ assert listed.status == 200, listed.json()+ assert [source["id"] for source in listed.json()["sources"]] == [+ source["id"] for source in body["sources"]+ ]+ serialized = json.dumps(body)+ assert "sk-ant-e2e-copy-only-123456" not in serialized+ assert "codex-oauth-e2e-123456" not in serialized++ captured_digests = set()+ for request in mock_llm_upstream.requests():+ headers = request["headers"]+ credential = headers.get("x-api-key")+ if credential is None:+ authorization = headers.get("authorization", "")+ prefix = "Bearer "+ credential = (+ authorization[len(prefix) :]+ if authorization.startswith(prefix)+ else authorization+ )+ if credential:+ captured_digests.add(+ hashlib.sha256(credential.encode("utf-8")).hexdigest()+ )+ assert seeded_api_key_digest in captured_digestsdiff --git a/tests/e2e/test_model_hub_mock_upstream.py b/tests/e2e/test_model_hub_mock_upstream.pynew file mode 100644index 000000000..ee09febf7--- /dev/null+++ b/tests/e2e/test_model_hub_mock_upstream.py@@ -0,0 +1,501 @@+"""Contract tests for the standalone Model Hub mock upstream."""++from __future__ import annotations++import json+import re+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import Any+from urllib.error import HTTPError, URLError+from urllib.parse import urlsplit+from urllib.request import ProxyHandler, Request, build_opener++import pytest++from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+++pytestmark = pytest.mark.e2e_model_hub++PROTOCOL_CASES = {+ "anthropic": {+ "path": "/v1/messages",+ "body": {+ "model": "mock-model",+ "max_tokens": 32,+ "messages": [{"role": "user", "content": "hello"}],+ },+ "response_key": "type",+ "response_value": "message",+ "terminal": "message_stop",+ "invalid_param": None,+ },+ "openai_responses": {+ "path": "/v1/responses",+ "body": {"model": "mock-model", "input": "hello"},+ "response_key": "object",+ "response_value": "response",+ "terminal": "response.completed",+ "invalid_param": "input",+ },+ "openai_chat": {+ "path": "/v1/chat/completions",+ "body": {+ "model": "mock-model",+ "messages": [{"role": "user", "content": "hello"}],+ },+ "response_key": "object",+ "response_value": "chat.completion",+ "terminal": "[DONE]",+ "invalid_param": "messages",+ },+}++_NO_PROXY_OPENER = build_opener(ProxyHandler({}))+++def _request(+ base_url: str,+ path: str,+ *,+ method: str = "GET",+ body: object | None = None,+ headers: dict[str, str] | None = None,+ timeout: float = 2,+) -> tuple[int, dict[str, str], bytes]:+ data = None+ request_headers = dict(headers or {})+ if body is not None:+ data = json.dumps(body).encode("utf-8")+ request_headers.setdefault("Content-Type", "application/json")+ request = Request(+ f"{base_url}{path}",+ data=data,+ headers=request_headers,+ method=method,+ )+ try:+ response = _NO_PROXY_OPENER.open(request, timeout=timeout)+ except HTTPError as exc:+ response = exc+ with response:+ return response.status, dict(response.headers), response.read()+++def _json_request(+ base_url: str,+ path: str,+ *,+ method: str = "GET",+ body: object | None = None,+ headers: dict[str, str] | None = None,+) -> tuple[int, dict[str, str], Any]:+ status, response_headers, raw = _request(+ base_url,+ path,+ method=method,+ body=body,+ headers=headers,+ )+ return status, response_headers, json.loads(raw)+++def _configure(base_url: str, **config: object) -> dict[str, Any]:+ status, _, payload = _json_request(+ base_url, "/__control/config", method="POST", body=config+ )+ assert status == 200+ assert payload["ok"] is True+ return payload["config"]++[email protected]("protocol", PROTOCOL_CASES)+def test_mock_upstream_inventory_and_buffered_protocol_shapes(+ mock_llm_upstream, protocol: str+) -> None:+ """Mock contract: all three protocol surfaces are shape-distinct."""++ case = PROTOCOL_CASES[protocol]+ config = _configure(+ mock_llm_upstream.url,+ protocol=protocol,+ models=[+ {+ "id": "relay/model",+ "display_name": "Relay Model",+ "context_length": 42_000,+ "pricing": {"input": "0.01", "output": "0.02"},+ }+ ],+ )+ assert config["models_endpoint"] == "ok"++ status, _, inventory = _json_request(+ mock_llm_upstream.url, "/v1/models"+ )+ assert status == 200+ assert inventory["object"] == "list"+ assert inventory["data"][0]["id"] == "relay/model"+ assert inventory["data"][0]["context_length"] == 42_000+ assert inventory["data"][0]["pricing"]["input"] == "0.01"+ if protocol == "anthropic":+ assert inventory["data"][0]["display_name"] == "Relay Model"+ assert inventory["data"][0]["type"] == "model"+ else:+ assert "display_name" not in inventory["data"][0]+ assert inventory["data"][0]["object"] == "model"++ status, _, payload = _json_request(+ mock_llm_upstream.url,+ case["path"],+ method="POST",+ body={**case["body"], "model": "relay/model"},+ )+ assert status == 200+ assert payload[case["response_key"]] == case["response_value"]+ assert payload["model"] == "relay/model"+ assert payload["usage"]++[email protected]("protocol", PROTOCOL_CASES)+def test_mock_upstream_invalid_probe_evidence_is_family_distinctive(+ mock_llm_upstream, protocol: str+) -> None:+ """Mock contract: invalid probes expose protocol-specific evidence."""++ case = PROTOCOL_CASES[protocol]+ _configure(mock_llm_upstream.url, protocol=protocol)+ status, _, payload = _json_request(+ mock_llm_upstream.url,+ case["path"],+ method="POST",+ body={},+ )+ assert status == 400+ error = payload["error"]+ if protocol == "anthropic":+ assert payload["type"] == "error"+ assert "param" not in error+ else:+ assert error["param"] == case["invalid_param"]++[email protected]("protocol", PROTOCOL_CASES)+ ("stream_behavior", "terminal_present"),+ [("healthy", True), ("interrupt_after_first_output", False)],+)+def test_mock_upstream_sse_healthy_and_interrupted_streams(+ mock_llm_upstream,+ protocol: str,+ stream_behavior: str,+ terminal_present: bool,+) -> None:+ """Mock contract: interruption follows the first model output."""++ case = PROTOCOL_CASES[protocol]+ _configure(+ mock_llm_upstream.url,+ protocol=protocol,+ stream=stream_behavior,+ )+ status, headers, raw = _request(+ mock_llm_upstream.url,+ case["path"],+ method="POST",+ body={**case["body"], "stream": True},+ )+ text = raw.decode("utf-8")+ assert status == 200+ assert headers["Content-Type"].startswith("text/event-stream")+ assert "mock response" in text+ assert (case["terminal"] in text) is terminal_present+++ ("auth", "status"),+ [+ ("401", 401),+ ("403_banned", 403),+ ("402", 402),+ ("429", 429),+ ("quota_message", 429),+ ("5xx", 503),+ ],+)+def test_mock_upstream_auth_modes_precede_every_protocol_surface(+ mock_llm_upstream, auth: str, status: int+) -> None:+ """Mock contract: auth is evaluated before discovery or inference."""++ _configure(+ mock_llm_upstream.url,+ auth=auth,+ protocol="openai_chat",+ models_endpoint="http_500",+ )+ models_status, _, models_payload = _json_request(+ mock_llm_upstream.url, "/v1/models"+ )+ inference_status, _, inference_payload = _json_request(+ mock_llm_upstream.url,+ "/v1/responses",+ method="POST",+ body={},+ )+ assert models_status == status+ assert inference_status == status+ assert models_payload["error"]["type"] != "not_found_error"+ assert inference_payload["error"]["type"] != "not_found_error"+++ ("behavior", "status"),+ [("http_404", 404), ("http_500", 500)],+)+def test_mock_upstream_models_endpoint_http_failures_are_isolated(+ mock_llm_upstream, behavior: str, status: int+) -> None:+ """Mock contract amendment: discovery can fail after protocol proof."""++ case = PROTOCOL_CASES["openai_chat"]+ _configure(+ mock_llm_upstream.url,+ auth="ok",+ protocol="openai_chat",+ models_endpoint=behavior,+ )+ models_status, _, _ = _json_request(+ mock_llm_upstream.url, "/v1/models"+ )+ inference_status, _, inference = _json_request(+ mock_llm_upstream.url,+ case["path"],+ method="POST",+ body=case["body"],+ )+ assert models_status == status+ assert inference_status == 200+ assert inference["object"] == "chat.completion"+++def test_mock_upstream_models_endpoint_malformed_json_is_isolated(+ mock_llm_upstream,+) -> None:+ """Mock contract amendment: malformed discovery is independently set."""++ _configure(mock_llm_upstream.url, models_endpoint="malformed_json")+ status, headers, raw = _request(+ mock_llm_upstream.url, "/v1/models"+ )+ assert status == 200+ assert headers["Content-Type"].startswith("application/json")+ with pytest.raises(json.JSONDecodeError):+ json.loads(raw)++ status, _, payload = _json_request(+ mock_llm_upstream.url,+ "/v1/chat/completions",+ method="POST",+ body=PROTOCOL_CASES["openai_chat"]["body"],+ )+ assert status == 200+ assert payload["object"] == "chat.completion"+++def test_mock_upstream_models_endpoint_timeout_is_isolated(+ mock_llm_upstream,+) -> None:+ """Mock contract amendment: discovery can time out independently."""++ _configure(mock_llm_upstream.url, models_endpoint="timeout")+ with pytest.raises((TimeoutError, URLError)):+ _request(+ mock_llm_upstream.url,+ "/v1/models",+ timeout=0.05,+ )+ status, _, payload = _json_request(+ mock_llm_upstream.url,+ "/v1/chat/completions",+ method="POST",+ body=PROTOCOL_CASES["openai_chat"]["body"],+ )+ assert status == 200+ assert payload["object"] == "chat.completion"+++def test_mock_upstream_timeout_teardown_joins_handlers_and_closes_socket(+) -> None:+ """Mock lifecycle: timeout handlers and accepted sockets end at stop."""++ upstream = MockLLMUpstream().start()+ parsed = urlsplit(upstream.url)+ assert parsed.hostname is not None and parsed.port is not None+ address = (parsed.hostname, parsed.port)+ handler_threads = ()+ try:+ _configure(upstream.url, models_endpoint="timeout")+ with pytest.raises((TimeoutError, URLError)):+ _request(upstream.url, "/v1/models", timeout=0.05)++ deadline = time.monotonic() + 2+ while time.monotonic() < deadline:+ handler_threads = upstream.active_handler_threads()+ if handler_threads:+ break+ time.sleep(0.01)+ assert handler_threads+ finally:+ upstream.stop()++ assert all(not thread.is_alive() for thread in handler_threads)+ assert upstream.active_handler_threads() == ()+ with pytest.raises(OSError):+ socket.create_connection(address, timeout=0.2)+++def test_mock_upstream_empty_inventory_is_success_not_discovery_failure(+ mock_llm_upstream,+) -> None:+ """Mock contract amendment: an empty successful inventory stays 200."""++ _configure(+ mock_llm_upstream.url,+ auth="ok",+ models_endpoint="ok",+ models=[],+ )+ status, _, payload = _json_request(+ mock_llm_upstream.url, "/v1/models"+ )+ assert status == 200+ assert payload["data"] == []+++def test_mock_upstream_control_validation_capture_envelope_and_reset(+ mock_llm_upstream,+) -> None:+ """Mock contract: control config is strict and capture is enveloped."""++ for invalid in (+ {"unknown": True},+ {"auth": "invalid"},+ {"stream": "invalid"},+ {"protocol": "invalid"},+ {"models_endpoint": "invalid"},+ {"models": [""]},+ ):+ status, _, payload = _json_request(+ mock_llm_upstream.url,+ "/__control/config",+ method="POST",+ body=invalid,+ )+ assert status == 400+ assert payload["ok"] is False++ headers = {+ "Authorization": "Bearer test-secret",+ "User-Agent": "model-hub-e2e",+ "X-Uncaptured": "ignored",+ }+ status, _, _ = _json_request(+ mock_llm_upstream.url,+ "/v1/chat/completions",+ method="POST",+ body=PROTOCOL_CASES["openai_chat"]["body"],+ headers=headers,+ )+ assert status == 200+ status, _, captured = _json_request(+ mock_llm_upstream.url, "/__control/requests"+ )+ assert status == 200+ assert set(captured) == {"requests"}+ assert len(captured["requests"]) == 1+ record = captured["requests"][0]+ assert record == {+ "method": "POST",+ "path": "/v1/chat/completions",+ "headers": {+ "authorization": "Bearer test-secret",+ "content-type": "application/json",+ "user-agent": "model-hub-e2e",+ },+ "body": PROTOCOL_CASES["openai_chat"]["body"],+ }++ status, _, payload = _json_request(+ mock_llm_upstream.url,+ "/__control/requests",+ method="DELETE",+ )+ assert status == 200+ assert payload == {"ok": True}+ _, _, captured = _json_request(+ mock_llm_upstream.url, "/__control/requests"+ )+ assert captured == {"requests": []}+++def test_mock_upstream_contract_client_ignores_inherited_proxy(+ monkeypatch,+ mock_llm_upstream,+) -> None:+ """Mock contract: loopback control and data calls never use host proxies."""++ for name in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"):+ monkeypatch.setenv(name, "http://127.0.0.1:1")+ for name in ("NO_PROXY", "no_proxy"):+ monkeypatch.delenv(name, raising=False)++ _configure(mock_llm_upstream.url, protocol="openai_chat")+ status, _, payload = _json_request(+ mock_llm_upstream.url,+ "/v1/chat/completions",+ method="POST",+ body=PROTOCOL_CASES["openai_chat"]["body"],+ )+ assert status == 200+ assert payload["object"] == "chat.completion"++ status, _, captured = _json_request(+ mock_llm_upstream.url, "/__control/requests"+ )+ assert status == 200+ assert [request["path"] for request in captured["requests"]] == [+ "/v1/chat/completions"+ ]+++def test_mock_upstream_starts_standalone_with_bare_python() -> None:+ """Mock contract: the CLI imports no Avibe or pytest dependency."""++ driver = Path(__file__).parent / "drivers" / "mock_llm_upstream.py"+ process = subprocess.Popen(+ [sys.executable, str(driver), "--host", "127.0.0.1", "--port", "0"],+ cwd=driver.parents[3],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ try:+ assert process.stdout is not None+ first_line = process.stdout.readline().strip()+ match = re.search(r"(http://127\.0\.0\.1:\d+)$", first_line)+ assert match, first_line+ status, _, payload = _json_request(match.group(1), "/v1/models")+ assert status == 200+ assert payload["data"][0]["id"] == "mock-model"+ finally:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.pynew file mode 100644index 000000000..4e7182466--- /dev/null+++ b/tests/e2e/test_model_hub_routing.py@@ -0,0 +1,335 @@+"""API-feasible Model Hub routing and fallback E2E scenarios."""++from __future__ import annotations++from datetime import datetime, timezone++import pytest++from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+from tests.e2e.test_model_hub_migration import _write+from tests.e2e.test_model_hub_runtime import (+ _engine_app,+ _install_engine,+)+from tests.e2e.test_model_hub_sources import (+ MENU_MODEL,+ SYNTHETIC_API_KEY,+ _configure_protocol,+ _create_source,+)+++pytestmark = pytest.mark.e2e_model_hub+++def _seed_codex_native_login(home) -> None:+ _write(+ home / ".codex" / "auth.json",+ (+ '{"auth_mode":"chatgpt","tokens":'+ '{"access_token":"codex-native-e2e-123456"}}'+ ),+ )+ _write(+ home / ".codex" / "config.toml",+ 'cli_auth_credentials_store = "file"\n',+ )+++def test_d1_subscription_added_after_api_key_is_appended_at_tail(+ mock_llm_upstream,+ model_hub_app,+) -> None:+ """D1: current placement appends a later native subscription."""++ # D-1 remains open: current shipped behavior appends at tail, so the API+ # key precedes and can burn before the later subscription.+ _configure_protocol(+ mock_llm_upstream,+ "openai_responses",+ models=[{"id": "gpt-5.3-codex"}],+ )+ api_source, _ = _create_source(+ model_hub_app,+ mock_llm_upstream,+ protocol="openai_responses",+ nonce="scn_d100000000000001",+ )+ _seed_codex_native_login(model_hub_app.home)+ scan = model_hub_app.client.post("/api/models/migration/scan", {})+ scan_body = scan.json()+ assert scan.status == 200, scan_body+ [native_item] = [+ item+ for item in scan_body["scan"]["items"]+ if item["kind"] == "oauth_native"+ ]+ applied = model_hub_app.client.post(+ "/api/models/migration/apply", {"item_ids": [native_item["id"]]}+ )+ applied_body = applied.json()+ assert applied.status == 200, applied_body+ native_source = next(+ source+ for source in applied_body["sources"]+ if (+ source["vendor"] == "openai"+ and source["kind"] == "subscription"+ and source["supply_channel"] == "native_cli"+ )+ )++ mode = model_hub_app.client.patch(+ "/api/models/agents/codex/mode", {"mode": "hub"}+ )+ assert mode.status == 200, mode.json()++ agent = model_hub_app.client.get(+ "/api/models/agents/codex/sources"+ )+ assert agent.status == 200, agent.json()+ agent_body = agent.json()+ assert agent_body["agent"]["sources"]["order"] == [+ api_source["id"],+ native_source["id"],+ ]+++def _prepare_probe_chain(+ app,+ first_upstream: MockLLMUpstream,+ second_upstream: MockLLMUpstream | None = None,+):+ _install_engine(app)+ _configure_protocol(+ first_upstream,+ "anthropic",+ models=[{"id": MENU_MODEL}],+ )+ first, _ = _create_source(+ app,+ first_upstream,+ nonce="scn_dprobe000000001",+ vendor="anthropic",+ display_name="First probe source",+ )+ sources = [first]+ if second_upstream is not None:+ _configure_protocol(+ second_upstream,+ "anthropic",+ models=[{"id": MENU_MODEL}],+ )+ second, _ = _create_source(+ app,+ second_upstream,+ nonce="scn_dprobe000000002",+ vendor="anthropic",+ display_name="Second probe source",+ )+ sources.append(second)+ mode = app.client.patch(+ "/api/models/agents/claude/mode", {"mode": "hub"}+ )+ assert mode.status == 200, mode.json()+ chain = app.client.put(+ f"/api/models/agents/claude/chain?model={MENU_MODEL}",+ {+ "hops": [+ {"source_id": source["id"], "model_id": MENU_MODEL}+ for source in sources+ ]+ },+ )+ assert chain.status == 200, chain.json()+ started = app.client.post("/api/models/runtime/start", {})+ assert started.status == 200, started.json()+ assert started.json()["runtime"]["status"]["health"] == "ok"+ first_upstream.reset_requests()+ if second_upstream is not None:+ second_upstream.reset_requests()+ return sources+++def _probe(app):+ return app.client.post(+ "/api/models/agents/claude/probe", {"model": MENU_MODEL}+ )+++def _source_by_id(app, source_id: str):+ sources = app.client.get("/api/models/sources")+ assert sources.status == 200, sources.json()+ return next(+ source+ for source in sources.json()["sources"]+ if source["id"] == source_id+ )+++def test_d2_healthy_hop_is_served_by_the_real_engine_probe(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """D2 API subset: a healthy exact hop reaches the mock through the engine."""++ with _engine_app(model_hub_app_factory) as app:+ [source] = _prepare_probe_chain(app, mock_llm_upstream)+ response = _probe(app)+ body = response.json()+ assert response.status == 200, body+ assert body["probe"]["reachable"] is True+ assert body["probe"]["source_id"] == source["id"]+ assert body["probe"]["model_id"] == MENU_MODEL+ captured = [+ item+ for item in mock_llm_upstream.requests()+ if item["path"] == "/v1/messages"+ ]+ assert captured+ assert all(+ item["headers"].get("x-api-key") == SYNTHETIC_API_KEY+ for item in captured+ )+++def _assert_probe_cooldown_and_next_request_selection(+ *,+ app,+ first_upstream,+ second_upstream,+ auth_behavior: str,+ expected_detail: str,+ expected_reason: str,+ expected_delay: int,+) -> None:+ first, second = _prepare_probe_chain(+ app, first_upstream, second_upstream+ )+ first_upstream.configure(auth=auth_behavior)+ failed = _probe(app)+ failed_body = failed.json()+ assert failed.status == 200, failed_body+ assert failed_body["probe"]["reachable"] is False+ assert failed_body["probe"]["source_id"] == first["id"]+ first_state = _source_by_id(app, first["id"])["state"]+ assert first_state["status"] == "cooldown"+ assert first_state["detail_key"] == expected_detail+ retry_at = datetime.fromisoformat(first_state["retry_at"])+ delay = (retry_at - datetime.now(timezone.utc)).total_seconds()+ assert expected_delay - 8 <= delay <= expected_delay + 2++ next_probe = _probe(app)+ next_body = next_probe.json()+ assert next_probe.status == 200, next_body+ assert next_body["probe"]["reachable"] is True+ assert next_body["probe"]["source_id"] == second["id"]+ events = app.client.get("/api/models/events?limit=10").json()["events"]+ assert any(+ event["kind"] == "cooldown"+ and event["from_source"] == first["id"]+ and event["reason"] == expected_reason+ for event in events+ )+++def test_d3_rate_limit_moves_the_next_api_probe_to_hop_one(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """D3 partial API evidence: cooldown written; next-request selection proven.++ The same-turn hop walk is not covered here; it requires the private turn+ gateway credential issued only to a live backend turn.+ """++ with MockLLMUpstream() as second_upstream:+ with _engine_app(model_hub_app_factory) as app:+ _assert_probe_cooldown_and_next_request_selection(+ app=app,+ first_upstream=mock_llm_upstream,+ second_upstream=second_upstream,+ auth_behavior="429",+ expected_detail="models.source.cooldown.rate_limited",+ expected_reason="rate_limited",+ expected_delay=60,+ )+++def test_d4_quota_moves_the_next_api_probe_to_hop_one(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """D4 partial API evidence: cooldown written; next-request selection proven.++ The same-turn hop walk is not covered here; it requires the private turn+ gateway credential issued only to a live backend turn.+ """++ with MockLLMUpstream() as second_upstream:+ with _engine_app(model_hub_app_factory) as app:+ _assert_probe_cooldown_and_next_request_selection(+ app=app,+ first_upstream=mock_llm_upstream,+ second_upstream=second_upstream,+ auth_behavior="quota_message",+ expected_detail="models.source.cooldown.quota_exhausted",+ expected_reason="quota_exhausted",+ expected_delay=300,+ )+++def test_d5_nonrefreshable_401_marks_the_key_for_repair(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """D5 API subset: a static key is revoked without an in-probe refresh."""++ with MockLLMUpstream() as second_upstream:+ with _engine_app(model_hub_app_factory) as app:+ first, second = _prepare_probe_chain(+ app, mock_llm_upstream, second_upstream+ )+ mock_llm_upstream.configure(auth="401")+ failed = _probe(app)+ assert failed.status == 200, failed.json()+ assert failed.json()["probe"]["reachable"] is False+ state = _source_by_id(app, first["id"])["state"]+ assert state == {+ "status": "needs_action",+ "retry_at": None,+ "detail_key": (+ "models.source.needs_action.credential_revoked"+ ),+ }+ inference_requests = [+ item+ for item in mock_llm_upstream.requests()+ if item["path"] == "/v1/messages"+ ]+ assert len(inference_requests) == 1+ next_probe = _probe(app)+ assert next_probe.status == 200, next_probe.json()+ assert next_probe.json()["probe"]["source_id"] == second["id"]+++def test_d6_server_error_ignores_retry_after_and_uses_flat_cooldown(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ """D6 API subset: a 5xx uses 30s despite Retry-After: 600."""++ # D-4 is open. The current contract deliberately records the flat 30s+ # server-error cooldown rather than honoring the upstream Retry-After.+ with MockLLMUpstream() as second_upstream:+ with _engine_app(model_hub_app_factory) as app:+ _assert_probe_cooldown_and_next_request_selection(+ app=app,+ first_upstream=mock_llm_upstream,+ second_upstream=second_upstream,+ auth_behavior="5xx",+ expected_detail="models.source.cooldown.server_error",+ expected_reason="server_error",+ expected_delay=30,+ )diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pynew file mode 100644index 000000000..20e39765c--- /dev/null+++ b/tests/e2e/test_model_hub_runtime.py@@ -0,0 +1,494 @@+"""Model Hub feature gate and managed-runtime E2E scenarios."""++from __future__ import annotations++import os+import signal+import socket+import subprocess+import sys+import tempfile+import time+from pathlib import Path+from types import SimpleNamespace++import psutil+import pytest+import yaml++from tests.e2e.drivers.model_hub_app import (+ HTTPResult,+ ModelHubTestApp,+ _OwnedProcess,+)+++pytestmark = pytest.mark.e2e_model_hub+++def _local_engine_manifest() -> str:+ raw = os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", "").strip()+ if not raw:+ pytest.skip(+ "managed Model Hub engine unavailable: set "+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH to an offline manifest"+ )+ path = Path(raw).expanduser()+ if not path.is_file():+ pytest.skip(+ f"managed Model Hub engine manifest does not exist: {path}"+ )+ return str(path.resolve())+++def _engine_app(model_hub_app_factory):+ manifest = _local_engine_manifest()+ return model_hub_app_factory(+ extra_env={+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": manifest,+ "VIBE_MODEL_HUB_ENGINE_OFFLINE": "1",+ }+ )+++def _install_engine(app) -> list[str]:+ observed: list[str] = []+ response = app.client.post("/api/models/runtime/install", {})+ body = response.json()+ if (+ response.status == 422+ and body.get("error") == "runtime_platform_unsupported"+ ):+ host_reason = body.get("detail") or body["error"]+ pytest.skip(+ "managed Model Hub engine unavailable on this host: "+ f"{host_reason}"+ )+ assert response.status == 200, body+ observed.append(body["runtime"]["status"]["health"])+ deadline = time.monotonic() + 60+ latest = body["runtime"]+ while time.monotonic() < deadline:+ status_response = app.client.get("/api/models/runtime/status")+ assert status_response.status == 200, status_response.json()+ latest = status_response.json()["runtime"]+ health = latest["status"]["health"]+ observed.append(health)+ if health != "installing":+ break+ time.sleep(0.1)+ assert latest["status"]["health"] == "not_started", latest+ assert latest["status"]["verified"] is True+ return observed+++def _app_with_install_response(+ status: int, body: bytes+) -> SimpleNamespace:+ response = HTTPResult(status=status, headers={}, body=body)+ client = SimpleNamespace(post=lambda *_args, **_kwargs: response)+ return SimpleNamespace(client=client)+++def test_install_engine_skips_exact_unsupported_host_response() -> None:+ """Harness contract: an unsupported manifest target is a precondition."""++ app = _app_with_install_response(+ 422,+ b'{"error":"runtime_platform_unsupported","detail":"linux/s390x"}',+ )++ with pytest.raises(pytest.skip.Exception, match="linux/s390x"):+ _install_engine(app)+++ ("status", "body"),+ [+ (422, b'{"error":"engine_down"}'),+ (500, b'{"error":"runtime_platform_unsupported"}'),+ ],+)+def test_install_engine_keeps_other_installer_failures_red(+ status: int,+ body: bytes,+) -> None:+ """Harness contract: post-precondition product failures never skip."""++ app = _app_with_install_response(status, body)++ with pytest.raises(AssertionError):+ _install_engine(app)+++def test_harness_scrubs_inherited_backend_credentials(+ monkeypatch,+ tmp_path: Path,+) -> None:+ """Harness contract: subprocesses inherit no user backend credentials."""++ inherited = {+ "ANTHROPIC_API_KEY": "real-user-anthropic-key",+ "ANTHROPIC_BASE_URL": "https://real-user-anthropic.example",+ "CLAUDE_CODE_OAUTH_TOKEN": "real-user-claude-token",+ "OPENAI_API_KEY": "real-user-openai-key",+ "OPENAI_BASE_URL": "https://real-user-openai.example",+ "OPENCODE_CONFIG_CONTENT": '{"real":"user"}',+ }+ for name, value in inherited.items():+ monkeypatch.setenv(name, value)++ app = ModelHubTestApp(Path.cwd(), tmp_path)++ assert set(inherited).isdisjoint(app.env)+ assert app.env["HOME"] == str(tmp_path / "home")+ assert app.env["CODEX_HOME"] == str(tmp_path / "home" / ".codex")+++def test_harness_cleans_controller_when_ui_start_fails(+ monkeypatch,+ tmp_path: Path,+) -> None:+ """Harness contract: partial startup never leaves a child process alive."""++ app = ModelHubTestApp(Path.cwd(), tmp_path)+ process: subprocess.Popen[bytes] | None = None++ def start_controller() -> None:+ nonlocal process+ process = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(60)"],+ start_new_session=True,+ )+ app._controller = process++ def fail_ui_start() -> None:+ raise OSError("synthetic UI startup failure")++ monkeypatch.setattr(app, "_initialize_config", lambda: None)+ monkeypatch.setattr(app, "_start_controller", start_controller)+ monkeypatch.setattr(app, "_start_ui", fail_ui_start)+ try:+ with pytest.raises(+ RuntimeError, match="hermetic Model Hub app failed to start"+ ):+ app.start()+ assert process is not None+ assert process.poll() is not None+ assert app._controller is None+ finally:+ if process is not None and process.poll() is None:+ process.kill()+ process.wait(timeout=5)+++ "interruption_type",+ [KeyboardInterrupt, SystemExit],+ ids=["keyboard-interrupt", "system-exit"],+)+def test_harness_cleans_controller_when_startup_is_interrupted(+ monkeypatch,+ tmp_path: Path,+ interruption_type: type[BaseException],+) -> None:+ """Harness contract: startup interruptions cannot leak controller children."""++ app = ModelHubTestApp(Path.cwd(), tmp_path)+ process: subprocess.Popen[bytes] | None = None++ def start_controller() -> None:+ nonlocal process+ process = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(60)"],+ start_new_session=True,+ )+ app._controller = process++ def interrupt_ui_start() -> None:+ raise interruption_type("synthetic startup interruption")++ monkeypatch.setattr(app, "_initialize_config", lambda: None)+ monkeypatch.setattr(app, "_start_controller", start_controller)+ monkeypatch.setattr(app, "_start_ui", interrupt_ui_start)+ try:+ with pytest.raises(+ interruption_type,+ match="synthetic startup interruption",+ ):+ app.start()+ assert process is not None+ assert process.poll() is not None+ assert app._controller is None+ finally:+ if process is not None and process.poll() is None:+ process.kill()+ process.wait(timeout=5)+++def test_harness_retries_with_fresh_port_after_ui_bind_race(+ monkeypatch,+) -> None:+ """Harness contract: an occupied UI port retries without child leaks."""++ ui_processes: list[subprocess.Popen[bytes]] = []+ controller_process: subprocess.Popen[bytes] | None = None+ with tempfile.TemporaryDirectory(+ prefix="avibe-model-hub-port-race-", dir="/tmp"+ ) as runtime_root:+ app = ModelHubTestApp(Path.cwd(), Path(runtime_root))+ occupied_port = app.port+ start_ui = app._start_ui++ def start_and_capture_ui() -> None:+ start_ui()+ assert app._ui is not None+ ui_processes.append(app._ui)++ monkeypatch.setattr(app, "_start_ui", start_and_capture_ui)+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as blocker:+ blocker.bind(("127.0.0.1", occupied_port))+ blocker.listen(1)+ with app:+ controller_process = app._controller+ assert controller_process is not None+ assert app.port != occupied_port+ assert len(ui_processes) >= 2+ assert all(+ process.poll() is not None+ for process in ui_processes[:-1]+ )+ assert ui_processes[-1].poll() is None+ finally:+ app.stop()++ assert controller_process is not None+ assert controller_process.poll() is not None+ assert all(process.poll() is not None for process in ui_processes)+++def test_harness_cleans_detached_child_after_leader_exits(+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Harness contract: no running marked child outlives its leader."""++ app = ModelHubTestApp(Path.cwd(), tmp_path)+ leader_code = (+ "import subprocess, sys; "+ "child = subprocess.Popen("+ "[sys.executable, '-c', 'import time; time.sleep(60)', sys.argv[1]], "+ "start_new_session=True); "+ "print(child.pid, flush=True)"+ )+ leader = subprocess.Popen(+ [sys.executable, "-c", leader_code, str(app.avibe_home)],+ stdout=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ child_pid: int | None = None+ try:+ assert leader.stdout is not None+ child_pid = int(leader.stdout.readline())+ leader.wait(timeout=5)+ assert any(+ process.pid == child_pid+ for processes in app._owned_process_groups().values()+ for process in processes+ )++ with caplog.at_level(+ "WARNING", logger="tests.e2e.drivers.model_hub_app"+ ):+ app.stop()++ assert app._owned_process_groups() == {}+ try:+ child_status = psutil.Process(child_pid).status()+ except psutil.NoSuchProcess:+ child_status = None+ assert child_status in {None, psutil.STATUS_ZOMBIE}+ if child_status == psutil.STATUS_ZOMBIE:+ assert f"pid={child_pid}" in caplog.text+ finally:+ if leader.poll() is None:+ os.killpg(leader.pid, signal.SIGKILL)+ leader.wait(timeout=5)+ if child_pid is not None:+ for process_group, processes in (+ app._owned_process_groups().items()+ ):+ if any(+ process.pid == child_pid for process in processes+ ):+ try:+ os.killpg(process_group, signal.SIGKILL)+ except ProcessLookupError:+ pass+++def test_harness_tracks_pid_status_after_marker_argv_disappears(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Harness contract: tracked PID status, not stale argv, proves absence."""++ app = ModelHubTestApp(Path.cwd(), tmp_path)+ identity = _OwnedProcess(+ pid=4242,+ process_group=4242,+ create_time=123.0,+ argv=f"synthetic-child {app.avibe_home}",+ )+ status = {"value": psutil.STATUS_RUNNING}++ class FakeProcess:+ def create_time(self) -> float:+ return identity.create_time++ def status(self) -> str:+ return status["value"]++ monkeypatch.setattr(app, "_owned_process_groups", lambda: {})+ monkeypatch.setattr(+ "tests.e2e.drivers.model_hub_app.psutil.Process",+ lambda _pid: FakeProcess(),+ )+ tracked = {identity.pid: identity}++ running, zombies = app._wait_for_owned_processes(tracked, timeout=0)+ assert running == tracked+ assert zombies == {}++ status["value"] = psutil.STATUS_ZOMBIE+ running, zombies = app._wait_for_owned_processes(tracked, timeout=0)+ assert running == {}+ assert zombies == tracked+ with caplog.at_level(+ "WARNING", logger="tests.e2e.drivers.model_hub_app"+ ):+ app._log_persistent_zombies(zombies)+ assert "harmless zombie" in caplog.text+++def test_a1_feature_flag_disables_the_complete_models_api(+ disabled_model_hub_app,+) -> None:+ """A1: every Model Hub API route is dormant when the flag is off."""++ requests = (+ ("GET", "/api/models/sources", None),+ ("GET", "/api/models/runtime/status", None),+ ("GET", "/api/models/events", None),+ ("GET", "/api/models/usage", None),+ ("POST", "/api/models/sources/observe", {}),+ ("PATCH", "/api/models/agents/claude/mode", {"mode": "hub"}),+ )+ for method, path, payload in requests:+ response = disabled_model_hub_app.client.request(+ method,+ path,+ **({"json_body": payload} if payload is not None else {}),+ )+ body = response.json()+ assert response.status == 404, (method, path, body)+ assert body == {+ "ok": False,+ "contract_version": 6,+ "error": "feature_disabled",+ }++ config = disabled_model_hub_app.client.get("/api/config")+ assert config.status == 200+ assert config.json()["capabilities"]["model_hub"]["enabled"] is False+++def test_a2_offline_engine_install_start_stop_and_hardened_config(+ model_hub_app_factory,+) -> None:+ """A2: install/start/stop preserves the hardened engine configuration."""++ with _engine_app(model_hub_app_factory) as app:+ observed = _install_engine(app)+ assert "installing" in observed++ started = app.client.post("/api/models/runtime/start", {})+ started_body = started.json()+ assert started.status == 200, started_body+ runtime = started_body["runtime"]+ assert runtime["enabled"] is True+ assert runtime["status"]["health"] == "ok"+ assert runtime["status"]["listening"]["host"] == "127.0.0.1"++ configs = list(+ (+ app.avibe_home+ / "runtime"+ / "model-hub"+ / "state"+ / "instances"+ ).glob("*/config.yaml")+ )+ assert len(configs) == 1+ config = yaml.safe_load(configs[0].read_text(encoding="utf-8"))+ assert config["host"] == "127.0.0.1"+ assert config["request-retry"] == 0+ assert config["disable-cooling"] is True+ assert config["usage-statistics-enabled"] is False+ assert config["force-model-prefix"] is True+ assert config["passthrough-headers"] is False++ stopped = app.client.post("/api/models/runtime/stop", {})+ stopped_body = stopped.json()+ assert stopped.status == 200, stopped_body+ assert stopped_body["runtime"]["enabled"] is False+ assert stopped_body["runtime"]["status"]["health"] == "not_started"+++def test_a3_runtime_stop_reports_every_blocking_backend(+ model_hub_app,+) -> None:+ """A3: the API guards runtime stop with every blocking backend."""++ for backend in ("claude", "codex"):+ changed = model_hub_app.client.patch(+ f"/api/models/agents/{backend}/mode", {"mode": "hub"}+ )+ assert changed.status == 200, changed.json()+ refused = model_hub_app.client.post("/api/models/runtime/stop", {})+ body = refused.json()+ assert refused.status == 409, body+ assert body["error"] == "runtime_in_use"+ assert body["backends"] == ["claude", "codex"]+++def test_a5_controller_restart_during_oauth_poll_reports_engine_down(+ model_hub_app_factory,+) -> None:+ """A5: restart during a Hub OAuth poll does not fake materialization."""++ with _engine_app(model_hub_app_factory) as app:+ _install_engine(app)+ started = app.client.post("/api/models/runtime/start", {})+ assert started.status == 200, started.json()+ oauth = app.client.post(+ "/api/models/oauth/start",+ {+ "vendor": "anthropic",+ "channel": "hub",+ "client_nonce": "ofn_a500000000000001",+ },+ )+ oauth_body = oauth.json()+ assert oauth.status == 200, oauth_body+ flow_id = oauth_body["flow"]["flow_id"]++ app.restart_controller()+ poll = app.client.get(f"/api/models/oauth/status/{flow_id}")+ body = poll.json()+ assert poll.status == 503, body+ assert body["error"] == "engine_down"+ assert "material" not in str(body.get("detail", "")).lower()diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pynew file mode 100644index 000000000..10ce8cdda--- /dev/null+++ b/tests/e2e/test_model_hub_sources.py@@ -0,0 +1,623 @@+"""Model Hub API-key Source scenarios over real HTTP and controller IPC."""++from __future__ import annotations++import json+import time+from typing import Any++import pytest++from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+++pytestmark = pytest.mark.e2e_model_hub++CONTRACT_VERSION = 6+MENU_MODEL = "claude-sonnet-4-6"+SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"+++def _configure_protocol(+ upstream: MockLLMUpstream,+ protocol: str = "anthropic",+ *,+ models: list[dict[str, Any]] | None = None,+) -> None:+ upstream.configure(+ auth="ok",+ stream="healthy",+ protocol=protocol,+ models_endpoint="ok",+ models=models+ if models is not None+ else [{"id": "mock-model"}],+ )+ upstream.reset_requests()+++def _source_payload(+ upstream: MockLLMUpstream,+ *,+ protocol: str = "anthropic",+ nonce: str = "scn_01j5w8z7p4n6q2rt",+ vendor: str = "custom",+ display_name: str = "E2E mock source",+) -> dict[str, Any]:+ return {+ "kind": "api_key",+ "vendor": vendor,+ "display_name": display_name,+ "base_url": upstream.url,+ "key": SYNTHETIC_API_KEY,+ "protocol": protocol,+ "client_nonce": nonce,+ }+++def _create_source(+ app,+ upstream: MockLLMUpstream,+ *,+ protocol: str = "anthropic",+ nonce: str = "scn_01j5w8z7p4n6q2rt",+ vendor: str = "custom",+ display_name: str = "E2E mock source",+ extra: dict[str, Any] | None = None,+) -> tuple[dict[str, Any], dict[str, Any]]:+ payload = {+ **_source_payload(+ upstream,+ protocol=protocol,+ nonce=nonce,+ vendor=vendor,+ display_name=display_name,+ ),+ **(extra or {}),+ }+ response = app.client.post("/api/models/sources", payload)+ body = response.json()+ assert response.status == 201, body+ assert body["ok"] is True+ assert body["contract_version"] == CONTRACT_VERSION+ return body["source"], payload+++ "protocol",+ ["anthropic", "openai_responses", "openai_chat"],+)+def test_b1_auto_observe_selects_protocol_from_response_shape(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+ protocol: str,+) -> None:+ """B1: auto observation proves each protocol from response evidence."""++ _configure_protocol(mock_llm_upstream, protocol)+ request = _source_payload(mock_llm_upstream, protocol=protocol)+ request.pop("kind")+ request.pop("display_name")+ request.pop("client_nonce")+ request.pop("protocol") # Wire form for the UI's `auto` selection.++ response = model_hub_app.client.post(+ "/api/models/sources/observe", request+ )+ body = response.json()+ assert response.status == 200, body+ assert body["contract_version"] == CONTRACT_VERSION+ assert body["observation"] == {+ "contract_version": CONTRACT_VERSION,+ "outcome": "observed",+ "reachable": True,+ "authenticated": "authenticated",+ "protocol": protocol,+ "discovery": "succeeded",+ "models": ["mock-model"],+ }+ captured_paths = [item["path"] for item in mock_llm_upstream.requests()]+ assert "/v1/models" in captured_paths+ assert any(path != "/v1/models" for path in captured_paths)+++def test_b2_manual_protocol_mismatch_is_refused_with_proof_error(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B2: a manual protocol cannot persist contrary response evidence."""++ _configure_protocol(mock_llm_upstream, "openai_chat")+ response = model_hub_app.client.post(+ "/api/models/sources",+ _source_payload(mock_llm_upstream, protocol="anthropic"),+ )+ body = response.json()+ assert response.status == 422, body+ assert body["ok"] is False+ assert body["error"] == "discovery_failed"+ assert body["detail"].endswith("ambiguous_source")+ assert body["observation"]["protocol"] is None+ assert body["observation"]["outcome"] == "ambiguous"+ listed = model_hub_app.client.get("/api/models/sources").json()+ assert listed["sources"] == []+++def test_b3_discovered_model_persists_only_contract_fields(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B3: relay inventory extensions are deliberately not persisted."""++ _configure_protocol(+ mock_llm_upstream,+ "anthropic",+ models=[+ {+ "id": "relay-model",+ "display_name": "Upstream display",+ "context_length": 128_000,+ "pricing": {"input": "0.01", "output": "0.02"},+ }+ ],+ )+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ [model] = source["models"]+ assert set(model) == {+ "id",+ "display_name",+ "origin",+ "reasoning_efforts",+ "discovered_at",+ "retired",+ }+ assert model["id"] == "relay-model"+ assert model["display_name"] is None+ assert model["origin"] == "discovered"+ assert model["reasoning_efforts"] == []+ assert model["retired"] is False+ assert model["discovered_at"]+ serialized = str(model)+ assert "context_length" not in serialized+ assert "pricing" not in serialized+++ "models_endpoint",+ ["http_404", "http_500", "malformed_json"],+)+def test_b4_inventory_failure_requires_consent_then_commits_error_source(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+ models_endpoint: str,+) -> None:+ """B4: protocol proof survives an independently failed inventory."""++ _configure_protocol(mock_llm_upstream, "openai_chat")+ mock_llm_upstream.configure(models_endpoint=models_endpoint)+ payload = _source_payload(+ mock_llm_upstream,+ protocol="openai_chat",+ nonce={+ "http_404": "scn_b400000000000001",+ "http_500": "scn_b400000000000002",+ "malformed_json": "scn_b400000000000003",+ }[models_endpoint],+ )++ rejected = model_hub_app.client.post(+ "/api/models/sources", payload+ )+ rejected_body = rejected.json()+ assert rejected.status == 422, rejected_body+ assert rejected_body["error"] == "discovery_failed"+ assert rejected_body["detail"].endswith("inventory_unavailable")+ assert rejected_body["observation"]["protocol"] == "openai_chat"+ assert rejected_body["observation"]["discovery"] == "failed"+ assert model_hub_app.client.get(+ "/api/models/sources"+ ).json()["sources"] == []++ accepted = model_hub_app.client.post(+ "/api/models/sources",+ {**payload, "accept_unavailable_inventory": True},+ )+ accepted_body = accepted.json()+ assert accepted.status == 201, accepted_body+ source = accepted_body["source"]+ assert source["protocol"] == "openai_chat"+ assert source["models"] == []+ assert source["state"] == {+ "status": "error",+ "retry_at": None,+ "detail_key": "models.source.error.unclassified",+ }+++ reason=(+ "B5 product gap: a byte-equivalent replay of a committed Source "+ "nonce currently returns 409 source_nonce_conflict"+ )+)+def test_b5_source_create_nonce_is_idempotent_across_http_replay(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B5: replaying a committed client nonce cannot duplicate a Source."""++ _configure_protocol(mock_llm_upstream)+ first, payload = _create_source(+ model_hub_app,+ mock_llm_upstream,+ nonce="scn_b500000000000001",+ )+ replay = model_hub_app.client.post("/api/models/sources", payload)+ replay_body = replay.json()+ assert replay.status == 201, replay_body+ assert replay_body["source"]["id"] == first["id"]+ sources = model_hub_app.client.get(+ "/api/models/sources"+ ).json()["sources"]+ assert [source["id"] for source in sources] == [first["id"]]+++def test_b6_replace_key_rolls_back_then_rename_and_retarget_commit(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B6: failed edits roll back; valid credential and metadata edits commit."""++ _configure_protocol(mock_llm_upstream)+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ original_ref = source["credential_ref"]+ original_mask = source["masked_credential"]+ revocation_journal = (+ model_hub_app.avibe_home+ / "state"+ / "model_hub_pending_revocations.json"+ )+ assert revocation_journal.is_file()+ assert json.loads(revocation_journal.read_text(encoding="utf-8")) == []+ journal_mtime = revocation_journal.stat().st_mtime_ns++ time.sleep(0.01)+ mock_llm_upstream.configure(auth="401")+ failed = model_hub_app.client.put(+ f"/api/models/sources/{source['id']}/credential",+ {"key": "sk-model-hub-e2e-rejected"},+ )+ failed_body = failed.json()+ assert failed.status == 502, failed_body+ assert failed_body["error"] == "discovery_failed"+ after_failure = model_hub_app.client.get(+ "/api/models/sources"+ ).json()["sources"][0]+ assert after_failure["credential_ref"] == original_ref+ assert after_failure["masked_credential"] == original_mask+ # The journal is the public rollback evidence boundary. An empty, rewritten+ # journal means the rejected replacement was queued before cleanup and then+ # observably removed; engine-private credential storage stays opaque.+ assert revocation_journal.stat().st_mtime_ns > journal_mtime+ assert json.loads(revocation_journal.read_text(encoding="utf-8")) == []++ mock_llm_upstream.configure(auth="ok")+ replaced = model_hub_app.client.put(+ f"/api/models/sources/{source['id']}/credential",+ {"key": "sk-model-hub-e2e-replacement"},+ )+ replaced_body = replaced.json()+ assert replaced.status == 200, replaced_body+ assert replaced_body["source"]["credential_ref"] != original_ref++ renamed = model_hub_app.client.patch(+ f"/api/models/sources/{source['id']}",+ {"display_name": "Renamed E2E source"},+ )+ assert renamed.status == 200, renamed.json()+ assert renamed.json()["source"]["display_name"] == "Renamed E2E source"++ with MockLLMUpstream() as replacement_upstream:+ _configure_protocol(replacement_upstream)+ retargeted = model_hub_app.client.patch(+ f"/api/models/sources/{source['id']}",+ {"base_url": replacement_upstream.url},+ )+ retargeted_body = retargeted.json()+ assert retargeted.status == 200, retargeted_body+ assert retargeted_body["source"]["base_url"] == (+ replacement_upstream.url+ )+ assert any(+ request["path"] == "/v1/models"+ for request in replacement_upstream.requests()+ )+++def _create_guarded_source(app, upstream: MockLLMUpstream) -> dict[str, Any]:+ _configure_protocol(+ upstream,+ "anthropic",+ models=[{"id": MENU_MODEL}],+ )+ source, _ = _create_source(+ app,+ upstream,+ nonce="scn_guardedsource0001",+ vendor="anthropic",+ )+ mode = app.client.patch(+ "/api/models/agents/claude/mode", {"mode": "hub"}+ )+ assert mode.status == 200, mode.json()+ chain = app.client.put(+ f"/api/models/agents/claude/chain?model={MENU_MODEL}",+ {+ "hops": [+ {"source_id": source["id"], "model_id": MENU_MODEL}+ ]+ },+ )+ assert chain.status == 200, chain.json()+ return source+++def test_b7_delete_guard_requires_exact_echo_before_force(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B7: destructive chain impact must be echoed exactly before commit."""++ source = _create_guarded_source(model_hub_app, mock_llm_upstream)+ endpoint = f"/api/models/sources/{source['id']}"+ refused = model_hub_app.client.delete(endpoint, {})+ refusal = refused.json()+ assert refused.status == 409, refusal+ assert refusal["error"] == "source_in_route_chain"+ assert refusal["would_remove_hops"]+ assert refusal["would_interrupt"] == [+ {"backend": "claude", "model_id": MENU_MODEL, "agents": []}+ ]++ stale_hops = [dict(hop) for hop in refusal["would_remove_hops"]]+ stale_hops[0]["model_id"] = "stale-confirmed-model"+ wrong_hops = model_hub_app.client.delete(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": stale_hops,+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ wrong_hops_body = wrong_hops.json()+ assert wrong_hops.status == 409, wrong_hops_body+ assert wrong_hops_body["would_remove_hops"] == refusal["would_remove_hops"]+ assert wrong_hops_body["would_interrupt"] == refusal["would_interrupt"]++ stale_interruptions = [+ dict(interruption) for interruption in refusal["would_interrupt"]+ ]+ stale_interruptions[0]["model_id"] = "stale-confirmed-model"+ wrong_interruptions = model_hub_app.client.delete(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": stale_interruptions,+ },+ )+ wrong_interruptions_body = wrong_interruptions.json()+ assert wrong_interruptions.status == 409, wrong_interruptions_body+ assert wrong_interruptions_body["would_remove_hops"] == refusal[+ "would_remove_hops"+ ]+ assert wrong_interruptions_body["would_interrupt"] == refusal[+ "would_interrupt"+ ]++ committed = model_hub_app.client.delete(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ committed_body = committed.json()+ assert committed.status == 200, committed_body+ assert committed_body["removed_hops"] == refusal["would_remove_hops"]+ assert committed_body["interrupted"] == refusal["would_interrupt"]+ assert model_hub_app.client.get(+ "/api/models/sources"+ ).json()["sources"] == []+++def test_b8_delete_force_is_query_only_in_the_current_http_contract(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B8: DELETE force is query-only in the current HTTP contract."""++ # Open decision B6 has no D-1..D-4 identifier in plan section 5:+ # normalize destructive force transport or retain the current split.+ source = _create_guarded_source(model_hub_app, mock_llm_upstream)+ endpoint = f"/api/models/sources/{source['id']}"+ refusal = model_hub_app.client.delete(endpoint, {}).json()++ body_force = model_hub_app.client.delete(+ endpoint,+ {+ "force": True,+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ assert body_force.status == 400+ assert body_force.json()["error"] == "invalid_source_order"++ query_force = model_hub_app.client.delete(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ assert query_force.status == 200, query_force.json()+++def test_b8_refresh_force_is_body_only_in_the_current_http_contract(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B8: refresh force is body-only in the current HTTP contract."""++ # Open decision B6 has no D-1..D-4 identifier in plan section 5:+ # normalize destructive force transport or retain the current split.+ source = _create_guarded_source(model_hub_app, mock_llm_upstream)+ endpoint = f"/api/models/sources/{source['id']}/refresh"+ mock_llm_upstream.configure(models=[])+ refused = model_hub_app.client.post(endpoint, {})+ refusal = refused.json()+ assert refused.status == 409, refusal+ assert refusal["error"] == "source_model_in_route_chain"++ query_force = model_hub_app.client.post(+ f"{endpoint}?force=true",+ {+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ assert query_force.status == 409, query_force.json()+ assert query_force.json()["error"] == "source_model_in_route_chain"++ body_force = model_hub_app.client.post(+ endpoint,+ {+ "force": True,+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ )+ body = body_force.json()+ assert body_force.status == 200, body+ assert body["removed_hops"] == refusal["would_remove_hops"]+ assert body["interrupted"] == refusal["would_interrupt"]+++def test_b9_refetch_updates_added_and_removed_inventory(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B9: refetch adds new inventory rows and removes vanished rows."""++ _configure_protocol(+ mock_llm_upstream,+ models=[{"id": "stable-model"}, {"id": "removed-model"}],+ )+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ mock_llm_upstream.configure(+ models=[{"id": "stable-model"}, {"id": "added-model"}]+ )+ refreshed = model_hub_app.client.post(+ f"/api/models/sources/{source['id']}/refresh", {}+ )+ body = refreshed.json()+ assert refreshed.status == 200, body+ assert {model["id"] for model in body["source"]["models"]} == {+ "stable-model",+ "added-model",+ }+++ reason=(+ "B9 fix-first: refresh currently overwrites discovered_at for "+ "pre-existing models"+ )+)+def test_b9_refetch_preserves_existing_model_discovery_timestamp(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B9: inventory diff must preserve timestamps of existing rows."""++ _configure_protocol(+ mock_llm_upstream,+ models=[{"id": "stable-model"}, {"id": "removed-model"}],+ )+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ before = {+ model["id"]: model["discovered_at"] for model in source["models"]+ }+ time.sleep(0.01)+ mock_llm_upstream.configure(+ models=[{"id": "stable-model"}, {"id": "added-model"}]+ )+ refreshed = model_hub_app.client.post(+ f"/api/models/sources/{source['id']}/refresh", {}+ )+ refreshed_body = refreshed.json()+ models = {+ model["id"]: model for model in refreshed_body["source"]["models"]+ }+ assert models["stable-model"]["discovered_at"] == before[+ "stable-model"+ ]+++def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(+ mock_llm_upstream: MockLLMUpstream,+ model_hub_app,+) -> None:+ """B10: custom rows are mutable; upstream rows remain managed."""++ _configure_protocol(mock_llm_upstream)+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ endpoint = f"/api/models/sources/{source['id']}/models"++ managed = model_hub_app.client.post(+ endpoint,+ {+ "model_id": "mock-model",+ "display_name": "Cannot replace",+ "reasoning_efforts": ["turbo"],+ },+ )+ assert managed.status == 409+ assert managed.json()["error"] == "source_model_managed_upstream"++ added = model_hub_app.client.post(+ endpoint,+ {+ "model_id": "manual-model",+ "display_name": "Manual model",+ "reasoning_efforts": ["turbo", "careful"],+ },+ )+ added_body = added.json()+ assert added.status == 201, added_body+ manual = next(+ model+ for model in added_body["source"]["models"]+ if model["id"] == "manual-model"+ )+ assert manual["origin"] == "manual"+ assert manual["reasoning_efforts"] == ["turbo", "careful"]++ updated = model_hub_app.client.patch(+ f"{endpoint}/manual-model",+ {"reasoning_efforts": ["experimental-tier"]},+ )+ assert updated.status == 200, updated.json()+ manual = next(+ model+ for model in updated.json()["source"]["models"]+ if model["id"] == "manual-model"+ )+ assert manual["reasoning_efforts"] == ["experimental-tier"]++ deleted = model_hub_app.client.delete(+ f"{endpoint}/manual-model", {}+ )+ assert deleted.status == 200, deleted.json()+ assert "manual-model" not in {+ model["id"] for model in deleted.json()["source"]["models"]+ }diff --git a/tests/e2e/test_model_hub_usage_events.py b/tests/e2e/test_model_hub_usage_events.pynew file mode 100644index 000000000..49d94845a--- /dev/null+++ b/tests/e2e/test_model_hub_usage_events.py@@ -0,0 +1,93 @@+"""Model Hub usage and resolution-event E2E scenarios."""++from __future__ import annotations++import json++import pytest++from tests.e2e.test_model_hub_sources import (+ _configure_protocol,+ _create_source,+)+++pytestmark = pytest.mark.e2e_model_hub+++def test_e2_usage_windows_are_bounded(+ model_hub_app,+) -> None:+ """E2: valid, garbage, and pathological windows stay bounded."""++ for query, expected in (+ ("1", 1),+ ("62", 62),+ ("garbage", 30),+ ("100000", 62),+ ):+ response = model_hub_app.client.get(+ f"/api/models/usage?days={query}"+ )+ body = response.json()+ assert response.status == 200, body+ assert body["usage"]["window_days"] == expected+ assert body["usage"]["totals"] == {+ "requests": 0,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ }++def test_e3_event_feed_paginates_and_never_persists_credentials(+ mock_llm_upstream,+ model_hub_app,+) -> None:+ """E3: event pages are cursor-stable and credential-free on disk/wire."""++ _configure_protocol(mock_llm_upstream)+ source, _ = _create_source(model_hub_app, mock_llm_upstream)+ secret = "sk-model-hub-e2e-not-real"+ mock_llm_upstream.configure(models_endpoint="http_500")+ for _ in range(3):+ response = model_hub_app.client.post(+ f"/api/models/sources/{source['id']}/refresh", {}+ )+ assert response.status == 502, response.json()+ assert response.json()["error"] == "discovery_failed"++ first = model_hub_app.client.get("/api/models/events?limit=2")+ first_body = first.json()+ assert first.status == 200, first_body+ assert len(first_body["events"]) == 2+ assert all(event["kind"] == "needs_action" for event in first_body["events"])+ assert all(+ event["reason"] == "unclassified_error"+ for event in first_body["events"]+ )++ cursor = first_body["events"][-1]["id"]+ second = model_hub_app.client.get(+ f"/api/models/events?limit=2&before={cursor}"+ )+ second_body = second.json()+ assert second.status == 200, second_body+ assert len(second_body["events"]) == 1+ assert second_body["events"][0]["id"] not in {+ event["id"] for event in first_body["events"]+ }++ wire = json.dumps(+ [*first_body["events"], *second_body["events"]],+ sort_keys=True,+ )+ assert secret not in wire+ assert "authorization" not in wire.lower()+ event_file = (+ model_hub_app.avibe_home+ / "state"+ / "model_hub_resolution_events.json"+ )+ assert event_file.is_file()+ assert secret not in event_file.read_text(encoding="utf-8")diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 66ffc435d..290cbb6bc 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -128,6 +128,13 @@ capabilities:- tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py+ - tests/e2e/test_model_hub_guards.py+ - tests/e2e/test_model_hub_migration.py+ - tests/e2e/test_model_hub_mock_upstream.py+ - tests/e2e/test_model_hub_routing.py+ - tests/e2e/test_model_hub_runtime.py+ - tests/e2e/test_model_hub_sources.py+ - tests/e2e/test_model_hub_usage_events.pyharness:- tests/scenario_harness/model_hub.pyunit_or_contract_tests:diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 2ff41c8e8..142af8c1a 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -26,6 +26,13 @@ capability:- tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py+ - tests/e2e/test_model_hub_guards.py+ - tests/e2e/test_model_hub_migration.py+ - tests/e2e/test_model_hub_mock_upstream.py+ - tests/e2e/test_model_hub_routing.py+ - tests/e2e/test_model_hub_runtime.py+ - tests/e2e/test_model_hub_sources.py+ - tests/e2e/test_model_hub_usage_events.pystatus_legend:covered:description: closed-loop coverage exists at the declared layer@@ -42,6 +49,26 @@ status_legend:test_required: falseexpected_fail: falsepriority: true+ assert:+ description: the E2E scenario asserts the intended contract when its environmental preconditions are present+ test_required: true+ expected_fail: false+ priority: false+ baseline:+ description: the E2E scenario freezes current behavior while its product decision remains open+ test_required: true+ expected_fail: false+ priority: true+ xfail:+ description: executable evidence isolates a known broken product surface without weakening passing invariants+ test_required: true+ expected_fail: true+ priority: true+ skip:+ description: this layer cannot execute the scenario; reason and owning_layer identify the boundary+ test_required: false+ expected_fail: false+ priority: falsescenarios:- id: MH-CATALOG-001name: Every scenario, observation, and canonical test resolves to discoverable executable evidence@@ -469,8 +496,337 @@ scenarios:kind: timeout_cancellayer: scenariotest: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly+ - id: A1+ name: Feature-off Model Hub routes remain dormant+ status: assert+ kind: gate+ layer: e2e-auto+ test: tests/e2e/test_model_hub_runtime.py::test_a1_feature_flag_disables_the_complete_models_api+ - id: A2+ name: Offline engine install, start, stop, and hardened configuration+ status: assert+ kind: runtime_lifecycle+ layer: e2e-auto+ test: tests/e2e/test_model_hub_runtime.py::test_a2_offline_engine_install_start_stop_and_hardened_config+ - id: A3+ name: Runtime stop reports blocking Hub backends in API and UI copy+ status: skip+ kind: guard+ layer: ui-e2e+ reason: UI copy is not executable from the pytest API layer+ owning_layer: Playwright lane (ui/e2e)+ evidence: docs/plans/model-hub-e2e-test-plan.md#a-gating-and-runtime-lifecycle-c1c2c5c9c15+ partial_evidence:+ test: tests/e2e/test_model_hub_runtime.py::test_a3_runtime_stop_reports_every_blocking_backend+ covers: structured 409 guard, runtime_in_use code, and exact blocking backend list+ - id: A4+ name: Runtime toggle fails closed when the agents read fails+ status: skip+ kind: guard+ layer: ui-e2e+ reason: runtime-toggle interaction is not executable from the pytest API layer+ owning_layer: Playwright lane (ui/e2e)+ evidence: docs/plans/model-hub-e2e-test-plan.md#a-gating-and-runtime-lifecycle-c1c2c5c9c15+ - id: A5+ name: Controller restart during OAuth poll reports engine_down+ status: assert+ kind: recovery+ layer: e2e-auto+ test: tests/e2e/test_model_hub_runtime.py::test_a5_controller_restart_during_oauth_poll_reports_engine_down+ - id: B1+ name: Automatic observation selects protocol from response evidence+ status: assert+ kind: protocol+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b1_auto_observe_selects_protocol_from_response_shape+ - id: B2+ name: Manual protocol mismatch is refused with proof evidence+ status: assert+ kind: protocol+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b2_manual_protocol_mismatch_is_refused_with_proof_error+ - id: B3+ name: Discovery drops upstream-only inventory extensions+ status: assert+ kind: persistence+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b3_discovered_model_persists_only_contract_fields+ - id: B4+ name: Unavailable inventory requires explicit acceptance before commit+ status: assert+ kind: recovery+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b4_inventory_failure_requires_consent_then_commits_error_source+ - id: B5+ name: Replayed source creation nonce is idempotent+ status: xfail+ kind: idempotency+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b5_source_create_nonce_is_idempotent_across_http_replay+ - id: B6+ name: Credential replacement rolls back or commits atomically+ status: assert+ kind: persistence+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b6_replace_key_rolls_back_then_rename_and_retarget_commit+ - id: B7+ name: Source deletion requires an exact guard-plan echo+ status: assert+ kind: guard+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b7_delete_guard_requires_exact_echo_before_force+ - id: B8+ name: Delete and refresh retain their current force-transport asymmetry+ status: baseline+ kind: compatibility+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b8_delete_force_is_query_only_in_the_current_http_contract+ - id: B9+ name: Inventory refetch preserves timestamps for existing models+ status: xfail+ kind: persistence+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b9_refetch_preserves_existing_model_discovery_timestamp+ - id: B10+ name: Custom-model mutation obeys upstream ownership boundaries+ status: assert+ kind: mutation+ layer: e2e-auto+ test: tests/e2e/test_model_hub_sources.py::test_b10_custom_models_and_free_text_tiers_obey_ownership_rules+ - id: B11+ name: Model Hub error codes resolve to human-readable copy+ status: skip+ kind: copy+ layer: ui-e2e+ reason: rendered error copy is not executable from the pytest API layer+ owning_layer: Playwright lane (ui/e2e)+ evidence: docs/plans/model-hub-e2e-test-plan.md#b-api-key-sources-c16c29+ - id: C1+ name: Hub OAuth starts, presents authorization, polls, and cancels+ status: skip+ kind: oauth+ layer: e2e-auto+ reason: the mock upstream does not implement the managed engine provider-OAuth authorization surface+ owning_layer: future live OAuth suite (managed engine provider OAuth)+ evidence: docs/plans/model-hub-e2e-test-plan.md#c-oauth-lifecycle-c30c40-partial-by-1+ - id: C2+ name: OAuth expiry and nonce replay preserve one flow+ status: skip+ kind: oauth+ layer: e2e-auto+ reason: OAuth expiry and replay require provider-OAuth state issued by the managed engine+ owning_layer: future live OAuth suite (managed engine provider OAuth)+ evidence: docs/plans/model-hub-e2e-test-plan.md#c-oauth-lifecycle-c30c40-partial-by-1+ - id: C3+ name: Native OAuth start failures resolve to actionable copy+ status: skip+ kind: oauth+ layer: e2e-auto+ reason: native start-failure states require a controlled native CLI auth process and credential store+ owning_layer: native OAuth scenario suite+ evidence: docs/plans/model-hub-e2e-test-plan.md#c-oauth-lifecycle-c30c40-partial-by-1+ - id: C4+ name: Real-vendor login materializes a source with adoption guidance+ status: skip+ kind: oauth+ layer: manual+ reason: full provider login requires real vendor accounts and credentials+ owning_layer: manual live-vendor regression+ evidence: docs/plans/model-hub-e2e-test-plan.md#c-oauth-lifecycle-c30c40-partial-by-1+ - id: D1+ name: A later native subscription is appended after an API-key source+ status: baseline+ kind: placement+ layer: e2e-auto+ test: tests/e2e/test_model_hub_routing.py::test_d1_subscription_added_after_api_key_is_appended_at_tail+ - id: D2+ name: A healthy first hop reaches the upstream through the real engine+ status: assert+ kind: routing+ layer: e2e-auto+ test: tests/e2e/test_model_hub_routing.py::test_d2_healthy_hop_is_served_by_the_real_engine_probe+ - id: D3+ name: Rate limiting falls through to hop one within the original turn+ status: skip+ kind: failover+ layer: turn-gateway+ reason: same-turn walk requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ partial_evidence:+ test: tests/e2e/test_model_hub_routing.py::test_d3_rate_limit_moves_the_next_api_probe_to_hop_one+ covers: cooldown written; next-request selection proven; same-turn hop walk is not covered here+ - id: D4+ name: Quota exhaustion falls through to hop one within the original turn+ status: skip+ kind: failover+ layer: turn-gateway+ reason: same-turn walk requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ partial_evidence:+ test: tests/e2e/test_model_hub_routing.py::test_d4_quota_moves_the_next_api_probe_to_hop_one+ covers: cooldown written; next-request selection proven; same-turn hop walk is not covered here+ - id: D5+ name: A nonrefreshable 401 marks the source for repair+ status: assert+ kind: authentication+ layer: e2e-auto+ test: tests/e2e/test_model_hub_routing.py::test_d5_nonrefreshable_401_marks_the_key_for_repair+ - id: D6+ name: A server error uses the current flat cooldown+ status: baseline+ kind: failover+ layer: e2e-auto+ test: tests/e2e/test_model_hub_routing.py::test_d6_server_error_ignores_retry_after_and_uses_flat_cooldown+ - id: D7+ name: A partial stream terminates without replaying another source+ status: skip+ kind: stream+ layer: turn-gateway+ reason: same-turn partial-stream handling requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D8+ name: Cooldown expiry recovers hop zero and emits recovery+ status: skip+ kind: recovery+ layer: contract+ reason: deterministic cooldown expiry requires a controllable clock across resolution and recovery+ owning_layer: unit/contract suite (controllable-time resolution)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D9+ name: Exhausting every hop returns mapping_target_unavailable+ status: skip+ kind: failover+ layer: turn-gateway+ reason: same-turn route exhaustion requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D10+ name: Undeclared reasoning effort is omitted from the upstream request+ status: skip+ kind: compatibility+ layer: turn-gateway+ reason: exact turn request capture requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D11+ name: Claude token counting behavior is documented at the gateway+ status: skip+ kind: compatibility+ layer: turn-gateway+ reason: backend count-tokens routing requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D12+ name: Backend injection remains isolated by backend contract+ status: skip+ kind: injection+ layer: contract+ reason: backend launch injection is not observable through the browser-visible HTTP API+ owning_layer: backend injection contract suite+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: D13+ name: Member permissions expose explicit Model Hub denials+ status: skip+ kind: authorization+ layer: ui-e2e+ reason: member dead-ends require a second authenticated role context unavailable in the local bypass-auth harness+ owning_layer: Playwright lane (multi-role permissions)+ evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81+ - id: E1+ name: Metered turns aggregate cache-aware upstream usage+ status: skip+ kind: usage+ layer: turn-gateway+ reason: metered turns require the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#e-usage-and-events-c54c60+ - id: E2+ name: Usage windows remain bounded for every days input+ status: assert+ kind: usage+ layer: e2e-auto+ test: tests/e2e/test_model_hub_usage_events.py::test_e2_usage_windows_are_bounded+ - id: E3+ name: Resolution events paginate without credential material+ status: assert+ kind: security+ layer: e2e-auto+ test: tests/e2e/test_model_hub_usage_events.py::test_e3_event_feed_paginates_and_never_persists_credentials+ - id: F1+ name: Native scan produces the copy-only migration action matrix+ status: xfail+ kind: migration+ layer: e2e-auto+ test: tests/e2e/test_model_hub_migration.py::test_f1_unsupported_opencode_provider_ids_are_noted+ - id: F2+ name: Migration copies original API-key bytes without changing native files+ status: assert+ kind: migration+ layer: e2e-auto+ test: tests/e2e/test_model_hub_migration.py::test_f2_apply_is_copy_only_and_places_native_login_before_keys+ - id: F3+ name: First Model Hub visit surfaces importable native configuration+ status: skip+ kind: migration+ layer: ui-e2e+ reason: first-visit banner rendering is not executable from the pytest API layer+ owning_layer: Playwright lane (ui/e2e)+ evidence: docs/plans/model-hub-e2e-test-plan.md#f-migration-c61c67+ - id: G1+ name: A guard echo missing agents remains confirmable+ status: assert+ kind: compatibility+ layer: e2e-auto+ test: tests/e2e/test_model_hub_guards.py::test_g1_guard_echo_missing_agents_does_not_loop+ - id: G2+ name: Source-order write and chain reorder retain their current divergence+ status: baseline+ kind: compatibility+ layer: e2e-auto+ test: tests/e2e/test_model_hub_guards.py::test_g2_source_order_write_and_chain_reorder_are_divergent+ - id: G3+ name: Malformed JSON is distinguishable from business refusals+ status: xfail+ kind: contract+ layer: e2e-auto+ test: tests/e2e/test_model_hub_guards.py::test_g3_malformed_json_is_distinct_from_business_refusals+ - id: H1+ name: Claude protocol turns complete through an OpenAI Chat source+ status: skip+ kind: cross_protocol+ layer: turn-gateway+ reason: cross-protocol turn completion requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#h-cross-protocol-functional-floor-owner-ruling-baseline+ - id: H2+ name: Parallel tool calls preserve cross-protocol tuple correlation+ status: skip+ kind: cross_protocol+ layer: turn-gateway+ reason: parallel tool correlation requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#h-cross-protocol-functional-floor-owner-ruling-baseline+ - id: H3+ name: Image blocks pass through without breaking terminal framing+ status: skip+ kind: cross_protocol+ layer: turn-gateway+ reason: image-block terminal framing requires the private credential issued to a live backend turn+ owning_layer: future live-turn suite (turn gateway)+ evidence: docs/plans/model-hub-e2e-test-plan.md#h-cross-protocol-functional-floor-owner-ruling-baselinenext_priority:- MH-PROTOCOL-004- MH-RUNTIME-001- MH-OAUTH-B-001- MH-OAUTH-C-001+ - B5+ - B8+ - B9+ - D1+ - D6+ - F1+ - G2+ - G3diff --git a/tests/scenarios/model_hub/test_model_hub_catalog.py b/tests/scenarios/model_hub/test_model_hub_catalog.pyindex bbe50f13e..17dcb2147 100644--- a/tests/scenarios/model_hub/test_model_hub_catalog.py+++ b/tests/scenarios/model_hub/test_model_hub_catalog.py@@ -3,9 +3,11 @@from __future__ import annotationsimport ast+import refrom pathlib import Pathimport yaml+from markdown_it import MarkdownItSCENARIO_ROOT = Path("tests/scenarios/model_hub")@@ -54,6 +56,93 @@ def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[streturn names+def _resolve_test_evidence(+ *,+ scenario_id: str,+ test_ref: object,+ canonical_tests: set[str],+ expected_fail: bool,+) -> None:+ assert isinstance(test_ref, str), (+ f"Scenario {scenario_id} has no executable test reference"+ )+ path_text, separator, function_name = test_ref.partition("::")+ assert separator and path_text and function_name, (+ f"Scenario {scenario_id} has malformed test reference {test_ref!r}"+ )+ path = Path(path_text)+ assert path_text in canonical_tests+ assert path.is_file()+ if path.suffix in _UI_SUFFIXES:+ # Expected failures are declared with pytest markers, which UI cases+ # cannot carry. Vitest validates actual UI collection separately.+ assert not expected_fail, (+ f"Scenario {scenario_id} is evidenced by a UI case, which "+ "cannot carry an expected failure"+ )+ evidence = path.read_text()+ else:+ function = _test_function(path, function_name)+ actual_expected_fail = "xfail" in _decorator_names(function)+ assert actual_expected_fail == expected_fail+ evidence = ast.get_docstring(function) or ""+ assert scenario_id in evidence, (+ f"Scenario {scenario_id} is not named inside {test_ref}; "+ "state the catalog ID in the test docstring — for a UI case, in "+ "its name — so the executable evidence is greppable by ID"+ )+++def _markdown_heading_fragments(path: Path) -> set[str]:+ tokens = MarkdownIt().parse(path.read_text())+ counts: dict[str, int] = {}+ fragments: set[str] = set()+ for index, token in enumerate(tokens[:-1]):+ if token.type != "heading_open":+ continue+ heading = tokens[index + 1].content.lower()+ base = re.sub(r"[^\w\- ]", "", heading)+ base = re.sub(r"\s+", "-", base).strip("-")+ duplicate = counts.get(base, 0)+ counts[base] = duplicate + 1+ fragments.add(base if duplicate == 0 else f"{base}-{duplicate}")+ return fragments+++def _resolve_evidence_reference(+ *,+ scenario_id: str,+ reference: object,+ canonical_tests: set[str],+ expected_fail: bool,+) -> None:+ assert isinstance(reference, str), (+ f"Scenario {scenario_id} has no evidence reference"+ )+ if "::" in reference:+ _resolve_test_evidence(+ scenario_id=scenario_id,+ test_ref=reference,+ canonical_tests=canonical_tests,+ expected_fail=expected_fail,+ )+ return++ path_text, separator, fragment = reference.partition("#")+ assert separator and path_text and fragment, (+ f"Scenario {scenario_id} has malformed document reference "+ f"{reference!r}"+ )+ path = Path(path_text)+ assert path.is_file(), (+ f"Scenario {scenario_id} points to missing evidence document {path}"+ )+ assert fragment in _markdown_heading_fragments(path), (+ f"Scenario {scenario_id} points to missing heading #{fragment} in "+ f"{path}"+ )++def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:"""MH-CATALOG-001: every live row resolves, names its own ID, and is reachable from the project index."""@@ -73,41 +162,44 @@ def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:status = statuses[scenario["status"]]if not status["test_required"]:assert test_ref is None- continue- assert isinstance(test_ref, str), f"Scenario {scenario['id']} has no executable test"- path_text, function_name = test_ref.split("::", 1)- path = Path(path_text)- assert path_text in canonical_tests- assert path.is_file()- if path.suffix in _UI_SUFFIXES:- # An expected failure is declared here with `pytest.mark.xfail`, which a- # UI case cannot carry, so a UI-evidenced row may not claim one.- assert not status["expected_fail"], (- f"Scenario {scenario['id']} is evidenced by a UI case, which cannot carry an expected failure"- )- # Whether that ID names a case vitest actually *runs* is a question only- # vitest answers; `ui/scripts/validate-scenario-catalog.mjs` asks it in- # the `npm test` run CI already does over this suite. Approximating it- # here would mean re-deciding, from text, which declarations execute —- # the answer would be wrong for a skipped, unreachable, or run-time-named- # case, and wrong quietly. So this side stops at what it reads exactly:- # the file exists and states the ID.- evidence = path.read_text()else:- function = _test_function(path, function_name)- expected_fail = "xfail" in _decorator_names(function)- assert expected_fail == status["expected_fail"]- evidence = ast.get_docstring(function) or ""- assert scenario["id"] in evidence, (- f"Scenario {scenario['id']} is not named inside {test_ref}; "- "state the catalog ID in the test docstring — for a UI case, in its name — "- "so the executable evidence is greppable by ID"- )+ _resolve_evidence_reference(+ scenario_id=scenario["id"],+ reference=test_ref,+ canonical_tests=canonical_tests,+ expected_fail=status["expected_fail"],+ )++ partial_evidence = scenario.get("partial_evidence")+ if partial_evidence is not None:+ assert isinstance(partial_evidence, dict)+ assert partial_evidence.get("covers")+ _resolve_evidence_reference(+ scenario_id=scenario["id"],+ reference=partial_evidence.get("test"),+ canonical_tests=canonical_tests,+ expected_fail=False,+ )+ evidence_ref = scenario.get("evidence")+ if evidence_ref is not None:+ _resolve_evidence_reference(+ scenario_id=scenario["id"],+ reference=evidence_ref,+ canonical_tests=canonical_tests,+ expected_fail=False,+ )if scenario["status"] == "partial":missing_layer = scenario.get("missing_layer")assert missing_layer and missing_layer != scenario["layer"], (f"Scenario {scenario['id']} is partial, so it must name the unproved layer in missing_layer")+ if scenario["status"] == "skip":+ for field in ("reason", "owning_layer"):+ value = scenario.get(field)+ assert isinstance(value, str) and value.strip(), (+ f"Scenario {scenario['id']} is skipped, so {field} must "+ "name the blocking boundary"+ )entry = _indexed_capability()assert entry["catalog"] == (SCENARIO_ROOT / "catalog.yaml").as_posix()