Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

test(model-hub): add configured route scenarios (#1383)

Call White09933ea0c847
diff --git a/tests/scenario_harness/README.md b/tests/scenario_harness/README.md
index 333c2daf6..f7e3ffd5f 100644
--- a/tests/scenario_harness/README.md
+++ b/tests/scenario_harness/README.md
@@ -19,6 +19,10 @@ Current contents:
Result/scheduled-delivery harness built on top of the generic layer
- `memory_repair.py`
Public-ASGI Memory Repair harness with a hermetic internal runtime boundary
+- `model_hub.py`
+ Config, adapter, persistence, and exact-route fixtures for Model Hub scenarios
+- `model_hub_native_oauth.py`
+ Native OAuth flow harness for Model Hub subscription scenarios
Recommended layering:
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
new file mode 100644
index 000000000..f93414212
--- /dev/null
+++ b/tests/scenario_harness/model_hub.py
@@ -0,0 +1,309 @@
+"""Reusable Model Hub scenario fixtures.
+
+The harness keeps scenario tests at the service boundary while exposing enough
+adapter telemetry to prove persistence, observation, and exact-hop behavior.
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import AsyncIterator, Iterable, Mapping
+
+from config.v2_config import (
+ ModelHubAgentSourcesConfig,
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubModelConfig,
+ ModelHubRouteConfig,
+ ModelHubRouteHopConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+ ModelHubSourceUsageConfig,
+ model_hub_fixed_menu_ids,
+)
+from core.handlers.model_hub.adapter import (
+ EngineHealth,
+ EngineStatus,
+ ObservationDiscovery,
+ ObservationOutcome,
+ RawCallOutcome,
+ RawOutcomeKind,
+ SourceObservation,
+)
+from core.handlers.model_hub.events import BoundedEventLog
+from core.handlers.model_hub.provenance import BoundedProvenanceStore
+from core.handlers.model_hub.revocations import CredentialRevocationJournal
+from core.handlers.model_hub.service import ModelHubService
+
+
+class MemoryModelHubStore:
+ """In-memory persistence that still uses the production serializer boundary."""
+
+ def __init__(self, config: ModelHubConfig) -> None:
+ self.config = config
+ self.saved_payloads: list[dict] = []
+
+ def load(self) -> ModelHubConfig:
+ return self.config
+
+ def save(self, config: ModelHubConfig) -> None:
+ self.config = ModelHubConfig.from_payload(config.to_payload())
+ self.saved_payloads.append(self.config.to_payload())
+
+
+@dataclass(frozen=True)
+class ScenarioCallResult:
+ kind: RawOutcomeKind
+ status: int | None = None
+ error_code: str | None = None
+ body: bytes | None = None
+ stream_started: bool = False
+
+
+class ScenarioInvokeHandle:
+ def __init__(self, outcome: RawCallOutcome, body: bytes | None) -> None:
+ self._outcome = outcome
+ self._body = body
+
+ @property
+ def stream(self) -> AsyncIterator[bytes] | None:
+ if self._body is None:
+ return None
+
+ async def chunks() -> AsyncIterator[bytes]:
+ yield self._body
+
+ return chunks()
+
+ @property
+ def outcome_available(self) -> bool:
+ return True
+
+ async def outcome(self) -> RawCallOutcome:
+ return self._outcome
+
+ async def close_stream(self) -> None:
+ return None
+
+
+class ModelHubScenarioAdapter:
+ """Deterministic adapter double with observable call boundaries."""
+
+ def __init__(
+ self,
+ *,
+ observation: SourceObservation | None = None,
+ discovery_models: Iterable[str] = (),
+ refresh_models: Iterable[str] | None = None,
+ invoke_results: Iterable[ScenarioCallResult] = (),
+ refreshable_credential_refs: Iterable[str] = (),
+ ) -> None:
+ self.observation = observation or SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="openai_chat",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=tuple(discovery_models),
+ )
+ self.discovery_models = tuple(discovery_models)
+ self.refresh_models = tuple(refresh_models) if refresh_models is not None else self.discovery_models
+ self.invoke_results = deque(invoke_results)
+ self.refreshable_credential_refs = frozenset(refreshable_credential_refs)
+ self.observation_calls: list[tuple[str, str | None, tuple[str, ...]]] = []
+ self.discovery_calls: list[tuple[str, str, str | None, str]] = []
+ self.provisioned_transient: list[str] = []
+ self.provisioned: list[str] = []
+ self.revoked: list[str] = []
+ self.synced: list[tuple[object, ...]] = []
+ self.invocations: list[tuple[str, str, str]] = []
+ self.requests: list[Mapping[str, object]] = []
+
+ async def ensure_installed(self) -> EngineStatus:
+ return await self.status()
+
+ async def start(self) -> EngineStatus:
+ return await self.status()
+
+ async def stop(self) -> None:
+ return None
+
+ async def status(self) -> EngineStatus:
+ return EngineStatus(EngineHealth.OK, "scenario", True, "127.0.0.1", 18443, None)
+
+ async def gateway_token(self) -> str:
+ return "scenario-engine-token"
+
+ async def provision_transient_credential(
+ self,
+ vendor: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ ref = f"cred_observation_{len(self.provisioned_transient) + 1}"
+ self.provisioned_transient.append(ref)
+ return ref
+
+ async def provision_credential(
+ self,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ ref = f"cred_source_{len(self.provisioned) + 1}"
+ self.provisioned.append(ref)
+ return ref
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ self.revoked.append(credential_ref)
+
+ async def sync_sources(self, bindings) -> None:
+ self.synced.append(tuple(bindings))
+
+ async def observe_source(
+ self,
+ vendor: str,
+ base_url: str | None,
+ credential_ref: str,
+ protocol_order,
+ ) -> SourceObservation:
+ self.observation_calls.append((vendor, base_url, tuple(protocol_order)))
+ return self.observation
+
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ ) -> tuple[str, ...]:
+ self.discovery_calls.append((vendor, protocol, base_url, credential_ref))
+ return self.refresh_models
+
+ async def credential_supports_refresh(self, credential_ref: str) -> bool:
+ return credential_ref in self.refreshable_credential_refs
+
+ async def invoke(
+ self,
+ source_id: str,
+ model_id: str,
+ request,
+ stream: bool,
+ origin: str,
+ ) -> ScenarioInvokeHandle:
+ self.invocations.append((source_id, model_id, origin))
+ self.requests.append(request)
+ result = self.invoke_results.popleft()
+ outcome = RawCallOutcome(
+ kind=result.kind,
+ http_status=result.status,
+ error_code=result.error_code,
+ redacted_message=None,
+ stream_started=result.stream_started,
+ model_id=model_id,
+ source_id=source_id,
+ )
+ return ScenarioInvokeHandle(outcome, result.body)
+
+
+def fixed_model(backend: str) -> str:
+ return model_hub_fixed_menu_ids(backend)[0]
+
+
+def source_model(
+ model_id: str,
+ *,
+ provenance: str = "discovered",
+ reasoning_efforts: Iterable[str] = (),
+ display_name: str | None = None,
+) -> ModelHubModelConfig:
+ return ModelHubModelConfig(
+ id=model_id,
+ provenance=provenance,
+ reasoning_efforts=list(reasoning_efforts),
+ display_name=display_name,
+ )
+
+
+def source(
+ source_id: str,
+ models: Iterable[str | ModelHubModelConfig],
+ *,
+ vendor: str = "anthropic",
+ protocol: str = "anthropic",
+ kind: str = "api_key",
+ channel: str = "hub",
+ status: str = "standby",
+ credential_ref: str | None = None,
+ retry_at: str | None = None,
+) -> ModelHubSourceConfig:
+ normalized_models = [item if isinstance(item, ModelHubModelConfig) else source_model(item) for item in models]
+ if credential_ref is None and channel == "hub":
+ credential_ref = f"cred_{source_id}"
+ return ModelHubSourceConfig(
+ id=source_id,
+ kind=kind,
+ vendor=vendor,
+ display_name=source_id,
+ protocol=protocol,
+ supply_channel=channel,
+ billing="monthly" if kind == "subscription" else "metered",
+ state=ModelHubSourceStateConfig(status=status, retry_at=retry_at),
+ usage=ModelHubSourceUsageConfig(),
+ models=normalized_models,
+ credential_ref=credential_ref,
+ )
+
+
+def config_with_sources(
+ sources: Iterable[ModelHubSourceConfig],
+ *,
+ backend: str = "claude",
+ menu_model: str | None = None,
+ hops: Iterable[tuple[str, str]] | None = None,
+) -> ModelHubConfig:
+ source_items = list(sources)
+ agents = {name: ModelHubAgentSupplyConfig.default(name, mode="hub") for name in ("claude", "codex", "opencode")}
+ config = ModelHubConfig(sources=source_items, agents=agents)
+ for name, agent in config.agents.items():
+ eligible = [item.id for item in source_items if ModelHubConfig.source_eligible_for_backend(item, name)]
+ agent.sources = ModelHubAgentSourcesConfig(order=eligible)
+ selected_model = menu_model or fixed_model(backend)
+ if hops is None:
+ hops = tuple(
+ (item.id, selected_model)
+ for item in source_items
+ if ModelHubConfig.source_eligible_for_backend(item, backend)
+ )
+ config.agents[backend].routes[selected_model] = ModelHubRouteConfig(
+ hops=tuple(ModelHubRouteHopConfig(source_id, model_id) for source_id, model_id in hops)
+ )
+ return config
+
+
+def service_for(
+ tmp_path: Path,
+ store: MemoryModelHubStore,
+ adapter: ModelHubScenarioAdapter,
+ *,
+ now=None,
+ requested_model_override=None,
+) -> ModelHubService:
+ state = tmp_path / "model-hub-state"
+ return ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(state / "events.json"),
+ provenance=BoundedProvenanceStore(state / "provenance.json"),
+ revocations=CredentialRevocationJournal(state / "revocations.json"),
+ now=now or (lambda: datetime.now(timezone.utc)),
+ requested_model_override=requested_model_override,
+ )
+
+
+def round_trip(config: ModelHubConfig) -> ModelHubConfig:
+ return ModelHubConfig.from_payload(config.to_payload())
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 2f19d417e..cc25f1e43 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -54,17 +54,24 @@ capabilities:
unit_or_contract_tests:
- ui/src/components/settings/memory/MemoryStatusPanel.test.tsx
- id: model_hub
- name: Model Hub source resolution and supply configuration
+ name: Model Hub configured routes and turn outcomes
status: active
catalog: tests/scenarios/model_hub/catalog.yaml
observations: tests/scenarios/model_hub/observations.yaml
scenario_tests:
+ - tests/scenarios/model_hub/test_model_hub_catalog.py
+ - tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+ - tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+ - 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
+ harness:
+ - tests/scenario_harness/model_hub.py
unit_or_contract_tests:
- tests/test_model_hub_api.py
- tests/test_model_hub_config.py
- tests/test_model_hub_resolution.py
+ - tests/test_model_hub_injection.py
- tests/test_model_hub_runtime.py
- id: harness_failure_recovery
name: Harness per-Session failure recovery
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 302f6c805..6a23e83a9 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -1,25 +1,102 @@
-version: 1
+version: 2
capability:
id: model_hub
- name: Model Hub source resolution and supply configuration
+ name: Model Hub configured routes and turn outcomes
canonical_tests:
- tests/test_model_hub_api.py
- tests/test_model_hub_config.py
- tests/test_model_hub_resolution.py
- tests/test_model_hub_injection.py
- tests/test_model_hub_runtime.py
- - tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+ - tests/scenarios/model_hub/test_model_hub_catalog.py
+ - tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
- tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+ - 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
status_legend:
- covered: closed-loop scenario coverage exists
- partial: unit or contract coverage exists but the cross-lane loop is incomplete
- gap: owned by a later lane or integration pass
+ covered:
+ description: closed-loop coverage exists at the declared layer
+ test_required: true
+ expected_fail: false
+ priority: false
+ partial:
+ description: executable coverage exists at the declared layer, but the layer named in missing_layer is still unproved
+ test_required: true
+ expected_fail: false
+ priority: true
+ gap:
+ description: no executable coverage at any layer yet
+ test_required: false
+ expected_fail: false
+ priority: true
scenarios:
+ - id: MH-CATALOG-001
+ name: Every scenario, observation, and canonical test resolves to discoverable executable evidence
+ status: covered
+ kind: contract
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_catalog.py::test_mh_catalog_001_scenario_catalog_is_complete_and_executable
+ - id: MH-S1-001
+ name: Live conditions never change the exact configured hop identity
+ status: covered
+ kind: determinism
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity
+ - id: MH-CONFIG-001
+ name: Persisted route configuration changes only through an explicit route edit
+ status: covered
+ kind: persistence
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_config_001_chain_is_the_persisted_artifact_until_explicit_edit
+ - id: MH-MATCH-001
+ name: Add-time matching persists each exact hop and returns its visible position
+ status: covered
+ kind: selection
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_001_add_source_persists_and_reports_each_exact_position
+ - id: MH-MATCH-002
+ name: Matching tie-break is deterministic across inventory processing order
+ status: covered
+ kind: determinism
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_002_matching_tie_break_is_independent_of_inventory_order
+ - id: MH-SRC-DELETE-001
+ name: Source deletion removes every reference while preserving survivor order
+ status: covered
+ kind: mutation
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order
+ - id: MH-SUPPLY-GAP-001
+ name: Inventory loss leaves the affected menu model visibly unconfigured
+ status: covered
+ kind: recovery
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss
+ - id: MH-PROTOCOL-001
+ name: Source protocol is response-observed before persistence with no transient residue
+ status: covered
+ kind: observation
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state_is_cleaned
+ - id: MH-PROTOCOL-002
+ name: Every protocol consumer shares the authoritative transport vocabulary
+ status: covered
+ kind: contract
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_protocol_002_contract_exposes_only_the_three_authoritative_transports
+ - id: MH-AC29-001
+ name: A persisted import-shaped Source survives canonical serialization and reload
+ status: covered
+ kind: migration
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_validator
- id: MH-RUNTIME-001
name: Service restart reports an installed engine as idle until first demand
status: partial
kind: recovery
layer: unit
+ missing_layer: scenario
test: tests/test_model_hub_runtime.py::test_mh_runtime_001_service_restart_reports_installed_engine_as_not_started
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
@@ -70,7 +147,7 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_unpinned_hub_projection_is_null_while_explicit_turn_resolves
- id: MH-MIG-001
- name: Migration copies without modifying native configuration
+ name: Native import copies without modifying native configuration
status: covered
kind: migration
layer: scenario
@@ -81,6 +158,42 @@ scenarios:
kind: migration
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_002_oauth_defaults_to_native_sources
+ - id: MH-TAKEOVER-001
+ name: Recoverable failures walk the configured route and exhaust only at its end
+ status: covered
+ kind: recovery
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_turn_takeover_is_silent_and_provenance_names_the_serving_hop
+ - id: MH-ENGINE-001
+ name: Local engine loss is terminal without Source mutation or replay
+ status: covered
+ kind: recovery
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_engine_loss_is_terminal_without_source_mutation_or_replay
+ - id: MH-ENGINE-MIDTURN-001
+ name: Local engine loss after output starts never walks a later hop
+ status: covered
+ kind: recovery
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_mid_turn_engine_loss_never_replays_after_output_starts
+ - id: MH-CREDENTIAL-001
+ name: Credential rejection retries once only for a refreshable credential
+ status: covered
+ kind: authentication
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_static_credential_failure_does_not_retry_or_claim_takeover
+ - id: MH-TURN-RESULT-001
+ name: All terminal outcomes are closed schema-valid provenance products
+ status: covered
+ kind: turn_lifecycle
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_turn_outcomes_and_cancel_are_closed_provenance_products
+ - id: MH-TURN-COPY-001
+ name: Every turn decision resolves to its authoritative backend copy key or silence
+ status: covered
+ kind: turn_lifecycle
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_turn_copy_keys_cover_the_authoritative_outcome_matrix
- id: MH-OAUTH-B-001
name: Device-code OAuth happy path
status: gap
@@ -98,22 +211,18 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_001_claude_paste_code_happy_path
- id: MH-OAUTH-NATIVE-002
- name: Codex native CLI device-code login self-completes and persists its account Source
+ name: Codex native CLI device-code login persists its account Source
status: covered
kind: oauth
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_002_codex_device_code_self_completes
- id: MH-OAUTH-NATIVE-003
- name: Native CLI OAuth cancel, timeout, and signed-out state terminate safely
+ name: Native CLI OAuth cancel and timeout terminate without residue
status: covered
kind: timeout_cancel
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly
next_priority:
- - MH-SEL-001
- - MH-MIG-001
+ - MH-RUNTIME-001
- MH-OAUTH-B-001
- MH-OAUTH-C-001
- - MH-OAUTH-NATIVE-001
- - MH-OAUTH-NATIVE-002
- - MH-OAUTH-NATIVE-003
diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yaml
index 7b29f539d..27e0e343d 100644
--- a/tests/scenarios/model_hub/observations.yaml
+++ b/tests/scenarios/model_hub/observations.yaml
@@ -1,29 +1,30 @@
-version: 1
+version: 2
capability: model_hub
observations:
- id: MH-OBS-001
source: engine-survey-s1
- summary: Engine fallback is broader than the signed taxonomy, so the adapter owns the per-source candidate loop.
+ summary: The adapter owns one Source call while the configured route executor owns cross-Source fallback.
affects:
- - MH-RES-001
+ - MH-S1-001
+ - MH-TAKEOVER-001
+ - MH-CREDENTIAL-001
- id: MH-OBS-002
source: engine-survey-s1
- summary: Engine usage events contain inbound credential material and remain disabled; Model Hub emits its own redacted events.
+ summary: Engine usage events can contain credential material, so Model Hub emits only its own redacted records.
affects:
- - MH-RES-001
+ - MH-PROTOCOL-001
+ - MH-TURN-RESULT-001
+ - MH-TURN-COPY-001
- id: MH-OBS-003
source: engine-survey-s1
- summary: OAuth presentation is runtime-declared rather than inferred from a vendor table.
+ summary: OAuth presentation is runtime-declared rather than inferred from vendor metadata.
affects:
- - MH-OAUTH-A-001
- - MH-OAUTH-B-001
- - MH-OAUTH-C-001
- MH-OAUTH-NATIVE-001
- MH-OAUTH-NATIVE-002
+ - MH-OAUTH-NATIVE-003
- id: MH-OBS-004
source: model-hub-completeness-audit
- summary: A successful OAuth status response must atomically materialize the bound Source; no second create request exists in the live UI path.
+ summary: Persisted Sources from every writer must survive the same canonical serialization and reload boundary.
affects:
- - MH-OAUTH-NATIVE-001
- - MH-OAUTH-NATIVE-002
- - MH-OAUTH-CONSENT-001
+ - MH-AC29-001
+ - MH-MIG-001
diff --git a/tests/scenarios/model_hub/test_model_hub_catalog.py b/tests/scenarios/model_hub/test_model_hub_catalog.py
new file mode 100644
index 000000000..9a1a69225
--- /dev/null
+++ b/tests/scenarios/model_hub/test_model_hub_catalog.py
@@ -0,0 +1,109 @@
+"""Mechanical integrity checks for the Model Hub scenario catalog."""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import yaml
+
+
+SCENARIO_ROOT = Path("tests/scenarios/model_hub")
+PROJECT_INDEX = Path("tests/scenarios/INDEX.yaml")
+CAPABILITY_ID = "model_hub"
+
+
+def _document(name: str) -> dict:
+ return yaml.safe_load((SCENARIO_ROOT / name).read_text())
+
+
+def _indexed_capability() -> dict:
+ index = yaml.safe_load(PROJECT_INDEX.read_text())
+ entry = next((item for item in index["capabilities"] if item["id"] == CAPABILITY_ID), None)
+ assert entry is not None, f"{PROJECT_INDEX} has no {CAPABILITY_ID} capability entry"
+ return entry
+
+
+def _test_function(path: Path, function_name: str) -> ast.FunctionDef | ast.AsyncFunctionDef:
+ tree = ast.parse(path.read_text(), filename=str(path))
+ function = next(
+ (
+ node
+ for node in tree.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == function_name
+ ),
+ None,
+ )
+ assert function is not None, f"Catalog points to missing test {path}::{function_name}"
+ return function
+
+
+def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
+ names: set[str] = set()
+ for decorator in function.decorator_list:
+ node = decorator.func if isinstance(decorator, ast.Call) else decorator
+ if isinstance(node, ast.Attribute):
+ names.add(node.attr)
+ elif isinstance(node, ast.Name):
+ names.add(node.id)
+ return names
+
+
+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."""
+
+ catalog = _document("catalog.yaml")
+ observations = _document("observations.yaml")
+ scenarios = catalog["scenarios"]
+ scenario_by_id = {item["id"]: item for item in scenarios}
+ statuses = catalog["status_legend"]
+
+ assert len(scenario_by_id) == len(scenarios)
+ assert set(statuses) >= {item["status"] for item in scenarios}
+ assert set(catalog["next_priority"]) == {item["id"] for item in scenarios if statuses[item["status"]]["priority"]}
+
+ canonical_tests = set(catalog["capability"]["canonical_tests"])
+ for scenario in scenarios:
+ test_ref = scenario.get("test")
+ 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()
+ function = _test_function(path, function_name)
+ expected_fail = "xfail" in _decorator_names(function)
+ assert expected_fail == status["expected_fail"]
+ assert scenario["id"] in (ast.get_docstring(function) or ""), (
+ f"Scenario {scenario['id']} is not named inside {test_ref}; "
+ "state the catalog ID in the test docstring so the executable evidence is greppable by ID"
+ )
+ 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"
+ )
+
+ entry = _indexed_capability()
+ assert entry["catalog"] == (SCENARIO_ROOT / "catalog.yaml").as_posix()
+ assert entry["observations"] == (SCENARIO_ROOT / "observations.yaml").as_posix()
+ indexed_tests = {
+ item
+ for key in ("scenario_tests", "harness", "unit_or_contract_tests")
+ for item in entry.get(key, [])
+ }
+ assert all(Path(item).is_file() for item in indexed_tests)
+ assert canonical_tests <= indexed_tests, (
+ f"Canonical Model Hub evidence missing from {PROJECT_INDEX}: {sorted(canonical_tests - indexed_tests)}"
+ )
+
+ observation_ids = [item["id"] for item in observations["observations"]]
+ assert len(observation_ids) == len(set(observation_ids))
+ assert all(
+ scenario_id in scenario_by_id
+ for observation in observations["observations"]
+ for scenario_id in observation["affects"]
+ )
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
new file mode 100644
index 000000000..aa60748e5
--- /dev/null
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -0,0 +1,491 @@
+"""First-wave Model Hub scenarios for the v3 configured-chain contract."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+
+from config.v2_config import ModelHubConfig, ModelHubRouteConfig, ModelHubRouteHopConfig
+from core.handlers.model_hub.adapter import (
+ SOURCE_PROTOCOLS,
+ ObservationDiscovery,
+ ObservationOutcome,
+ SourceObservation,
+)
+from core.handlers.model_hub.service import (
+ ModelHubError,
+ _matching_v1_model_id as matching_v1_model_id,
+)
+from modules.agents.model_hub import resolve_model_hub_turn
+from tests.scenario_harness.model_hub import (
+ MemoryModelHubStore,
+ ModelHubScenarioAdapter,
+ config_with_sources,
+ fixed_model,
+ round_trip,
+ service_for,
+ source,
+ source_model,
+)
+
+
[email protected](autouse=True)
+def _enable_model_hub(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
+def _route_pairs(
+ config: ModelHubConfig,
+ backend: str,
+ menu_model: str,
+) -> tuple[tuple[str, str], ...]:
+ return tuple(
+ (hop.source_id, hop.model_id)
+ for hop in config.agents[backend].routes[menu_model].hops
+ )
+
+
+def test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity() -> None:
+ """MH-S1-001: live health changes annotate exact hops but never choose new ones."""
+
+ menu_model = fixed_model("claude")
+ first = source("src_first001", ["upstream-first"])
+ second = source("src_second01", ["upstream-second"])
+ config = config_with_sources(
+ [first, second],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(first.id, "upstream-first"), (second.id, "upstream-second")],
+ )
+ before = resolve_model_hub_turn(
+ config,
+ "claude",
+ menu_model,
+ now=datetime(2026, 8, 1, tzinfo=timezone.utc),
+ )
+
+ changed = round_trip(config)
+ changed.sources[0].state.status = "needs_action"
+ changed.sources[0].state.detail_key = (
+ "models.source.needs_action.credential_revoked"
+ )
+ changed.sources[1].models.append(source_model("catalog-only-new-model"))
+ after = resolve_model_hub_turn(
+ changed,
+ "claude",
+ menu_model,
+ now=datetime(2030, 8, 1, tzinfo=timezone.utc),
+ )
+
+ assert (
+ before.source_model_ids
+ == after.source_model_ids
+ == _route_pairs(config, "claude", menu_model)
+ )
+ assert tuple(
+ (item.source_id, item.model_id) for item in after.inspected_hops
+ ) == before.source_model_ids
+ assert {item.id for item in after.candidates} <= {
+ source_id for source_id, _ in before.source_model_ids
+ }
+ assert after.target_model in {
+ model_id for _, model_id in before.source_model_ids
+ }
+
+
+def test_mh_config_001_chain_is_the_persisted_artifact_until_explicit_edit(
+ tmp_path: Path,
+) -> None:
+ """MH-CONFIG-001: refresh, reload, and inventory changes preserve a chain until a route edit."""
+
+ menu_model = fixed_model("claude")
+ first = source("src_chain001", [menu_model])
+ second = source("src_chain002", [menu_model])
+ config = config_with_sources(
+ [first, second],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(first.id, menu_model), (second.id, menu_model)],
+ )
+ store = MemoryModelHubStore(config)
+ adapter = ModelHubScenarioAdapter(
+ discovery_models=(menu_model,),
+ refresh_models=(menu_model, "new-inventory-model"),
+ )
+ service = service_for(tmp_path, store, adapter)
+ original = _route_pairs(store.load(), "claude", menu_model)
+
+ asyncio.run(service.refresh_source(first.id))
+ assert _route_pairs(store.load(), "claude", menu_model) == original
+ assert _route_pairs(round_trip(store.load()), "claude", menu_model) == original
+
+ result = asyncio.run(
+ service.set_agent_chain(
+ "claude",
+ menu_model,
+ {
+ "hops": [
+ {"source_id": second.id, "model_id": menu_model},
+ {"source_id": first.id, "model_id": menu_model},
+ ]
+ },
+ )
+ )
+ assert [
+ (hop["source_id"], hop["model_id"]) for hop in result["chain"]["chain"]
+ ] == [(second.id, menu_model), (first.id, menu_model)]
+ assert _route_pairs(round_trip(store.load()), "claude", menu_model) == (
+ (second.id, menu_model),
+ (first.id, menu_model),
+ )
+ assert adapter.observation_calls == []
+ assert adapter.discovery_calls == [
+ (first.vendor, first.protocol, first.base_url, first.credential_ref)
+ ]
+
+
+def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
+ tmp_path: Path,
+) -> None:
+ """MH-MATCH-001: add-time matching writes exact hops and returns their persisted positions."""
+
+ menu_model = fixed_model("claude")
+ existing = source("src_existing01", [menu_model])
+ config = config_with_sources(
+ [existing],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(existing.id, menu_model)],
+ )
+ store = MemoryModelHubStore(config)
+ adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="anthropic",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=(menu_model,),
+ ),
+ refresh_models=(menu_model,),
+ )
+ service = service_for(tmp_path, store, adapter)
+
+ result = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "added-source",
+ "base_url": "https://upstream.example/v1",
+ "key": "sk-scenario-add-key",
+ }
+ )
+ )
+ added_id = result["source"]["id"]
+ route = store.load().agents["claude"].routes[menu_model]
+ positions = {
+ (hop.source_id, hop.model_id): index
+ for index, hop in enumerate(route.hops, start=1)
+ }
+ returned = {
+ (item["source_id"], item["model_id"]): item["position"]
+ for item in result["added_to"]
+ }
+
+ assert returned
+ assert all(item["source_id"] == added_id for item in result["added_to"])
+ assert returned == {pair: positions[pair] for pair in returned}
+ assert result["adopted_by"] == [
+ {"backend": "claude", "menu_model": menu_model}
+ ]
+ assert store.load().agents["claude"].sources.order[-1] == added_id
+ assert adapter.revoked == adapter.provisioned_transient
+
+ persisted_after_add = _route_pairs(store.load(), "claude", menu_model)
+ asyncio.run(service.refresh_source(added_id))
+ restarted = service_for(tmp_path / "restart", store, adapter)
+ assert _route_pairs(store.load(), "claude", menu_model) == persisted_after_add
+ assert (
+ _route_pairs(round_trip(restarted.store.load()), "claude", menu_model)
+ == persisted_after_add
+ )
+ assert len(adapter.observation_calls) == 1
+
+
+def test_mh_match_002_matching_tie_break_is_independent_of_inventory_order() -> None:
+ """MH-MATCH-002: the matching-v1 total order produces one result for either processing order."""
+
+ menu_model = "claude-opus-4-6"
+ candidates = (
+ "claude-opus-4-6-20260101",
+ "claude-opus-4-6-20260115",
+ )
+ first = source(
+ "src_tieorder1",
+ candidates,
+ vendor="anthropic",
+ kind="subscription",
+ channel="native_cli",
+ credential_ref=None,
+ )
+ second = source(
+ "src_tieorder2",
+ reversed(candidates),
+ vendor="anthropic",
+ kind="subscription",
+ channel="native_cli",
+ credential_ref=None,
+ )
+
+ def matches(source_order):
+ return {
+ item.id: matching_v1_model_id(
+ backend="claude",
+ requested_model=menu_model,
+ source=item,
+ )
+ for item in source_order
+ }
+
+ first_order = matches((first, second))
+ second_order = matches((second, first))
+
+ assert first_order == second_order
+ assert set(first_order.values()) == {"claude-opus-4-6-20260115"}
+
+
+def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order(
+ tmp_path: Path,
+) -> None:
+ """MH-SRC-DELETE-001: source deletion is one transaction across all backend orders and chains."""
+
+ claude_model = fixed_model("claude")
+ codex_model = fixed_model("codex")
+ opencode_model = "custom/route-model"
+ models = (claude_model, codex_model, "route-model")
+ first = source("src_delete01", models)
+ doomed = source("src_delete02", models)
+ last = source("src_delete03", models)
+ config = config_with_sources(
+ [first, doomed, last],
+ backend="claude",
+ menu_model=claude_model,
+ hops=[
+ (first.id, claude_model),
+ (doomed.id, claude_model),
+ (last.id, claude_model),
+ ],
+ )
+ for backend, menu_model, upstream_model in (
+ ("codex", codex_model, codex_model),
+ ("opencode", opencode_model, "route-model"),
+ ):
+ agent = config.agents[backend]
+ if backend == "opencode":
+ agent.menu.checked = [opencode_model]
+ agent.routes[menu_model] = ModelHubRouteConfig(
+ hops=tuple(
+ ModelHubRouteHopConfig(item.id, upstream_model)
+ for item in (first, doomed, last)
+ )
+ )
+ store = MemoryModelHubStore(config)
+ adapter = ModelHubScenarioAdapter()
+ service = service_for(tmp_path, store, adapter)
+
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.delete_source(doomed.id))
+ assert refusal.value.code == "source_in_route_chain"
+
+ result = asyncio.run(service.delete_source(doomed.id, force=True))
+ assert result["removed_hops"]
+ assert doomed.id not in {item.id for item in store.load().sources}
+ for backend, menu_model in (
+ ("claude", claude_model),
+ ("codex", codex_model),
+ ("opencode", opencode_model),
+ ):
+ assert doomed.id not in store.load().agents[backend].sources.order
+ assert [
+ hop.source_id
+ for hop in store.load().agents[backend].routes[menu_model].hops
+ ] == [first.id, last.id]
+ assert round_trip(store.load()).to_payload() == store.load().to_payload()
+ assert adapter.revoked == [doomed.credential_ref]
+
+
+def test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss(
+ tmp_path: Path,
+) -> None:
+ """MH-SUPPLY-GAP-001: a now-unsupplied menu model stays visible with a zero-length Route."""
+
+ menu_model = fixed_model("claude")
+ supplied = source("src_supply01", [menu_model])
+ store = MemoryModelHubStore(
+ config_with_sources(
+ [supplied],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(supplied.id, menu_model)],
+ )
+ )
+ adapter = ModelHubScenarioAdapter(
+ discovery_models=(menu_model,),
+ refresh_models=("replacement-only-model",),
+ )
+ service = service_for(tmp_path, store, adapter)
+
+ result = asyncio.run(service.refresh_source(supplied.id, force=True))
+ assert result["removed_hops"] == [
+ {
+ "backend": "claude",
+ "menu_model": menu_model,
+ "source_id": supplied.id,
+ "model_id": menu_model,
+ }
+ ]
+ model_supply = next(
+ row
+ for row in service.list_agents()[0]["model_supply"]
+ if row["model_id"] == menu_model
+ )
+ assert model_supply["chain_length"] == 0
+ assert service.agent_chain("claude", menu_model)["chain"] == []
+
+
+def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state_is_cleaned(
+ tmp_path: Path,
+) -> None:
+ """MH-PROTOCOL-001: observation proves protocol before persistence and leaves no transient ref."""
+
+ store = MemoryModelHubStore(config_with_sources([]))
+ adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="openai_chat",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=("observed-model",),
+ )
+ )
+ service = service_for(tmp_path, store, adapter)
+ observed = asyncio.run(
+ service.observe_source(
+ {
+ "vendor": "custom",
+ "base_url": "https://upstream.example/v1",
+ "key": "sk-scenario-observe-key",
+ "protocol_order": [
+ "openai_chat",
+ "openai_responses",
+ "anthropic",
+ ],
+ }
+ )
+ )
+
+ assert observed["observation"]["protocol"] in SOURCE_PROTOCOLS
+ assert observed["observation"]["authenticated"] == "authenticated"
+ assert store.load().sources == []
+ assert adapter.revoked == adapter.provisioned_transient
+ assert all("credential_ref" not in value for value in observed.values())
+
+ ambiguous_store = MemoryModelHubStore(config_with_sources([]))
+ ambiguous_adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.AMBIGUOUS,
+ reachable=True,
+ authenticated=True,
+ protocol=None,
+ discovery=ObservationDiscovery.NOT_ATTEMPTED,
+ model_ids=(),
+ )
+ )
+ ambiguous_service = service_for(
+ tmp_path / "ambiguous",
+ ambiguous_store,
+ ambiguous_adapter,
+ )
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(
+ ambiguous_service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "ambiguous-source",
+ "base_url": "https://ambiguous.example/v1",
+ "key": "sk-scenario-ambiguous-key",
+ }
+ )
+ )
+ assert failure.value.code == "discovery_failed"
+ assert ambiguous_store.load().sources == []
+ assert ambiguous_adapter.revoked == ambiguous_adapter.provisioned_transient
+
+
+def test_mh_protocol_002_contract_exposes_only_the_three_authoritative_transports() -> None:
+ """MH-PROTOCOL-002: the schema and adapter authority have one exact protocol vocabulary."""
+
+ schema = json.loads(
+ Path("docs/plans/model-hub-contracts/source.schema.json").read_text()
+ )
+ schema_protocols = tuple(schema["properties"]["protocol"]["enum"])
+ assert schema_protocols == SOURCE_PROTOCOLS
+ assert len(schema_protocols) == len(set(schema_protocols))
+
+
+def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_validator(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """MH-AC29-001: a real migration write remains valid after serialization and reload."""
+
+ native_home = tmp_path / "native-home"
+ claude_config = native_home / ".claude"
+ claude_config.mkdir(parents=True)
+ (claude_config / "settings.json").write_text(
+ json.dumps({"env": {"ANTHROPIC_API_KEY": "sk-scenario-ac29-key"}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_config))
+ monkeypatch.setenv("CODEX_HOME", str(native_home / ".codex"))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(native_home / ".config"))
+ monkeypatch.setenv("XDG_CACHE_HOME", str(native_home / ".cache"))
+ monkeypatch.setattr(Path, "home", lambda: native_home)
+
+ menu_model = fixed_model("claude")
+ store = MemoryModelHubStore(config_with_sources([]))
+ adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="anthropic",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=(menu_model,),
+ )
+ )
+ service = service_for(tmp_path, store, adapter)
+ scan = service.migration_scan()["items"]
+ result = asyncio.run(service.migration_apply([item["id"] for item in scan]))
+
+ serialized = json.loads(json.dumps(store.load().to_payload()))
+ reloaded = ModelHubConfig.from_payload(serialized)
+ persisted_sources = {item.id: item.to_payload() for item in reloaded.sources}
+
+ assert result["applied"] == len(scan)
+ assert persisted_sources == {item["id"]: item for item in result["sources"]}
+ assert store.saved_payloads
+ assert reloaded.to_payload() == store.load().to_payload()
+ assert set(_route_pairs(reloaded, "claude", menu_model)) == {
+ (position["source_id"], position["model_id"])
+ for position in result["added_to"]
+ if position["backend"] == "claude"
+ and position["menu_model"] == menu_model
+ }
diff --git a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
new file mode 100644
index 000000000..1ced3fdad
--- /dev/null
+++ b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
@@ -0,0 +1,731 @@
+"""Second-wave Model Hub scenarios for the frozen turn contracts."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+
+import aiohttp
+import pytest
+from jsonschema import Draft7Validator
+
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+from core.handlers.model_hub.classification import ResolutionDecision
+from core.handlers.model_hub.provenance import (
+ BoundedProvenanceStore,
+ TURN_OUTCOME_RENDERING_AUTHORITY,
+ TurnCorrelationRegistry,
+ produce_turn_outcome,
+ project_turn_outcome_copy,
+)
+from core.handlers.model_hub.service import ModelHubError
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from core.run_settlement import (
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+)
+from modules.agents.model_hub import ModelHubRuntimeRouter, resolve_model_hub_turn
+from tests.scenario_harness.model_hub import (
+ MemoryModelHubStore,
+ ModelHubScenarioAdapter,
+ ScenarioCallResult,
+ config_with_sources,
+ fixed_model,
+ service_for,
+ source,
+)
+
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+
+
[email protected](autouse=True)
+def _enable_model_hub(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
+class EngineLossAdapter(ModelHubScenarioAdapter):
+ async def invoke(self, source_id, model_id, request, stream, origin):
+ self.invocations.append((source_id, model_id, origin))
+ self.requests.append(request)
+ raise RuntimeError("scenario engine unavailable")
+
+
+class MidTurnEngineLossHandle:
+ def __init__(self, source_id: str, model_id: str) -> None:
+ self._outcome = RawCallOutcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ http_status=None,
+ error_code="engine_down",
+ redacted_message=None,
+ stream_started=True,
+ model_id=model_id,
+ source_id=source_id,
+ )
+
+ @property
+ def stream(self):
+ async def chunks():
+ yield b"data: partial\n\n"
+ raise RuntimeError("scenario engine disappeared")
+
+ return chunks()
+
+ @property
+ def outcome_available(self) -> bool:
+ return True
+
+ async def outcome(self):
+ return self._outcome
+
+ async def close_stream(self) -> None:
+ return None
+
+
+class MidTurnEngineLossAdapter(ModelHubScenarioAdapter):
+ async def invoke(self, source_id, model_id, request, stream, origin):
+ self.invocations.append((source_id, model_id, origin))
+ self.requests.append(request)
+ return MidTurnEngineLossHandle(source_id, model_id)
+
+
+def _provenance_schema() -> dict:
+ return json.loads((CONTRACTS / "turn-provenance.schema.json").read_text())
+
+
+def _turn_copy_rows() -> list[dict[str, str]]:
+ lines = Path("docs/plans/model-hub.md").read_text().splitlines()
+ heading = next(index for index, line in enumerate(lines) if line.startswith("**Turn-outcome copy matrix"))
+ header = next(index for index, line in enumerate(lines[heading:], start=heading) if line.startswith("| Decision |"))
+ rows: list[dict[str, str]] = []
+ for line in lines[header + 2 :]:
+ if not line.startswith("|"):
+ break
+ cells = [cell.strip() for cell in line.strip("|").split("|")]
+ rows.append(
+ {
+ "decision": cells[0].strip("`"),
+ "outcome": cells[1].strip("`"),
+ "rendering": cells[4],
+ }
+ )
+ return rows
+
+
+def _locale_value(locale: dict, key: str) -> object:
+ value: object = locale
+ for part in key.split("."):
+ assert isinstance(value, dict)
+ value = value[part]
+ return value
+
+
+def _projection_for_copy_variant(
+ decision: str,
+ variant: str,
+) -> object:
+ kwargs: dict[str, object] = {}
+ if variant in {"waiting", "interrupted"}:
+ menu_model = fixed_model("claude")
+ supplied = source(
+ "src_copyvariant",
+ [menu_model],
+ status=("cooldown" if variant == "waiting" else "needs_action"),
+ retry_at=(
+ "2026-08-13T01:00:00+00:00" if variant == "waiting" else None
+ ),
+ )
+ if variant == "interrupted":
+ supplied.state.detail_key = (
+ "models.source.needs_action.credential_revoked"
+ )
+ config = config_with_sources(
+ [supplied],
+ backend="claude",
+ menu_model=menu_model,
+ )
+ resolution = resolve_model_hub_turn(
+ config,
+ "claude",
+ menu_model,
+ now=datetime(2026, 8, 13, tzinfo=timezone.utc),
+ )
+ kwargs.update(config=config, resolution=resolution)
+ if decision == "turn.streamed_fallback":
+ kwargs.update(
+ attempted_hop=("src_attempted", menu_model),
+ source_transition_persisted=True,
+ )
+ elif variant == "waiting_without_retry":
+ menu_model = fixed_model("claude")
+ supplied = source("src_copyready", [menu_model])
+ config = config_with_sources(
+ [supplied],
+ backend="claude",
+ menu_model=menu_model,
+ )
+ resolution = resolve_model_hub_turn(
+ config,
+ "claude",
+ menu_model,
+ now=datetime(2026, 8, 13, tzinfo=timezone.utc),
+ )
+ kwargs.update(config=config, resolution=resolution)
+ elif variant == "transition_unpersisted":
+ kwargs["source_transition_persisted"] = False
+ elif variant == "next_current":
+ menu_model = fixed_model("claude")
+ supplied = source("src_copynext", [menu_model])
+ config = config_with_sources(
+ [supplied],
+ backend="claude",
+ menu_model=menu_model,
+ )
+ resolution = resolve_model_hub_turn(
+ config,
+ "claude",
+ menu_model,
+ now=datetime(2026, 8, 13, tzinfo=timezone.utc),
+ )
+ kwargs.update(
+ config=config,
+ resolution=resolution,
+ attempted_hop=("src_attempted", menu_model),
+ source_transition_persisted=True,
+ )
+ return produce_turn_outcome(
+ decision,
+ stream_started=variant == "stream_started",
+ **kwargs,
+ )
+
+
+def _raw_outcome(
+ kind: RawOutcomeKind,
+ *,
+ status: int | None = None,
+ error_code: str | None = None,
+) -> RawCallOutcome:
+ return RawCallOutcome(
+ kind=kind,
+ http_status=status,
+ error_code=error_code,
+ redacted_message=None,
+ stream_started=False,
+ model_id="scenario-model",
+ source_id="src_outcome01",
+ )
+
+
+async def _post(launch) -> tuple[int, dict]:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(
+ f"{launch.gateway_base_url}/v1/messages",
+ headers={"Authorization": f"Bearer {launch.gateway_token}"},
+ json={"model": launch.runtime_model, "messages": [], "stream": False},
+ ) as response:
+ return response.status, await response.json()
+
+
+async def _post_stream(launch) -> tuple[int, bytes, BaseException | None]:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(
+ f"{launch.gateway_base_url}/v1/messages",
+ headers={"Authorization": f"Bearer {launch.gateway_token}"},
+ json={"model": launch.runtime_model, "messages": [], "stream": True},
+ ) as response:
+ body = bytearray()
+ try:
+ async for chunk in response.content.iter_any():
+ body.extend(chunk)
+ except aiohttp.ClientPayloadError as error:
+ return response.status, bytes(body), error
+ return response.status, bytes(body), None
+
+
+def test_mh_turn_takeover_is_silent_and_provenance_names_the_serving_hop(tmp_path: Path) -> None:
+ """MH-TAKEOVER-001: fallback serves in order, or settles exhausted after the same route ends."""
+
+ menu_model = fixed_model("claude")
+ first = source("src_takeover01", [menu_model])
+ second = source("src_takeover02", [menu_model])
+ store = MemoryModelHubStore(
+ config_with_sources(
+ [first, second],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(first.id, menu_model), (second.id, menu_model)],
+ )
+ )
+ adapter = ModelHubScenarioAdapter(
+ invoke_results=(
+ ScenarioCallResult(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ error_code="quota_exhausted",
+ ),
+ ScenarioCallResult(RawOutcomeKind.SUCCESS, body=b'{"answer":"ok"}'),
+ )
+ )
+ service = service_for(
+ tmp_path,
+ store,
+ adapter,
+ now=lambda: datetime(2026, 1, 1, tzinfo=timezone.utc),
+ )
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+
+ exhausted_first = source("src_exhausted01", [menu_model])
+ exhausted_last = source("src_exhausted02", [menu_model])
+ exhausted_store = MemoryModelHubStore(
+ config_with_sources(
+ [exhausted_first, exhausted_last],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[
+ (exhausted_first.id, menu_model),
+ (exhausted_last.id, menu_model),
+ ],
+ )
+ )
+ exhausted_adapter = ModelHubScenarioAdapter(
+ invoke_results=(
+ ScenarioCallResult(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ error_code="quota_exhausted",
+ ),
+ ScenarioCallResult(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ error_code="quota_exhausted",
+ ),
+ )
+ )
+ exhausted_service = service_for(
+ tmp_path / "exhausted",
+ exhausted_store,
+ exhausted_adapter,
+ now=lambda: datetime(2026, 1, 1, tzinfo=timezone.utc),
+ )
+ exhausted_gateway = ModelHubTurnGateway(exhausted_service)
+ exhausted_router = ModelHubRuntimeRouter(
+ service=exhausted_service,
+ turn_gateway=exhausted_gateway,
+ )
+
+ async def exercise() -> tuple[dict, dict]:
+ try:
+ launch = await router.resolve(
+ "claude",
+ menu_model,
+ process_scope="scenario-takeover",
+ turn_id="turn_takeover01",
+ )
+ status, body = await _post(launch)
+ router.settle_turn(
+ "turn_takeover01",
+ settled_by="terminal_result",
+ ts="2026-01-01T00:00:01+00:00",
+ )
+ served_result = {
+ "status": status,
+ "body": body,
+ "provenance": service.get_turn_provenance("turn_takeover01"),
+ }
+ exhausted_launch = await exhausted_router.resolve(
+ "claude",
+ menu_model,
+ process_scope="scenario-exhausted",
+ turn_id="turn_exhausted01",
+ )
+ exhausted_status, exhausted_body = await _post(exhausted_launch)
+ exhausted_router.settle_turn(
+ "turn_exhausted01",
+ settled_by="no_terminal_result",
+ ts="2026-01-01T00:00:01+00:00",
+ )
+ exhausted_result = {
+ "status": exhausted_status,
+ "body": exhausted_body,
+ "provenance": exhausted_service.get_turn_provenance("turn_exhausted01"),
+ }
+ return served_result, exhausted_result
+ finally:
+ await gateway.close()
+ await exhausted_gateway.close()
+
+ result, exhausted_result = asyncio.run(exercise())
+ assert result["status"] == 200
+ assert result["body"] == {"answer": "ok"}
+ assert [source_id for source_id, _model_id, _origin in adapter.invocations] == [
+ first.id,
+ second.id,
+ ]
+ assert result["provenance"]["outcome"] == "served"
+ assert result["provenance"]["failed_attempts"][0]["source_id"] == first.id
+ assert result["provenance"]["served"]["source_id"] == second.id
+ Draft7Validator(_provenance_schema()).validate(result["provenance"])
+ assert exhausted_result["status"] == 503
+ assert (
+ exhausted_result["body"]["error"]["code"]
+ == "mapping_target_unavailable"
+ )
+ assert exhausted_result["provenance"]["outcome"] == "exhausted"
+ assert [attempt["source_id"] for attempt in exhausted_result["provenance"]["failed_attempts"]] == [
+ exhausted_first.id,
+ exhausted_last.id,
+ ]
+ assert exhausted_result["provenance"]["served"] is None
+ Draft7Validator(_provenance_schema()).validate(exhausted_result["provenance"])
+
+
+def test_mh_engine_loss_is_terminal_without_source_mutation_or_replay(tmp_path: Path) -> None:
+ """MH-ENGINE-001: a local engine loss is terminal and never becomes a Source failure."""
+
+ menu_model = fixed_model("claude")
+ upstream = source("src_engine01", [menu_model])
+ store = MemoryModelHubStore(config_with_sources([upstream], backend="claude", menu_model=menu_model))
+ adapter = EngineLossAdapter()
+ service = service_for(tmp_path, store, adapter)
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+
+ async def exercise() -> tuple[int, dict, str, dict]:
+ try:
+ launch = await router.resolve(
+ "claude",
+ menu_model,
+ process_scope="scenario-engine",
+ turn_id="turn_engine01",
+ )
+ status, body = await _post(launch)
+ router.settle_turn(
+ "turn_engine01",
+ settled_by="no_terminal_result",
+ ts="2026-01-01T00:00:01+00:00",
+ )
+ return (
+ status,
+ body,
+ store.load().sources[0].state.status,
+ service.get_turn_provenance("turn_engine01"),
+ )
+ finally:
+ await gateway.close()
+
+ status, body, source_status, provenance = asyncio.run(exercise())
+ assert status == 503
+ assert body["error"]["code"] == "engine_down"
+ assert source_status == "standby"
+ assert len(adapter.invocations) == 1
+ assert provenance["outcome"] == "failed_terminal"
+ assert provenance["terminal_error"]["reason"] == "engine_down"
+ assert provenance["terminal_error"]["source_id"] is None
+ Draft7Validator(_provenance_schema()).validate(provenance)
+
+
+def test_mh_mid_turn_engine_loss_never_replays_after_output_starts(tmp_path: Path) -> None:
+ """MH-ENGINE-MIDTURN-001: once output is visible, local engine loss terminates without a next-hop walk."""
+
+ menu_model = fixed_model("claude")
+ first = source("src_midengine1", [menu_model])
+ backup = source("src_midengine2", [menu_model])
+ store = MemoryModelHubStore(
+ config_with_sources(
+ [first, backup],
+ backend="claude",
+ menu_model=menu_model,
+ hops=[(first.id, menu_model), (backup.id, menu_model)],
+ )
+ )
+ adapter = MidTurnEngineLossAdapter()
+ service = service_for(tmp_path, store, adapter)
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+
+ async def exercise() -> tuple[int, bytes, dict]:
+ try:
+ launch = await router.resolve(
+ "claude",
+ menu_model,
+ process_scope="scenario-mid-engine",
+ turn_id="turn_midengine01",
+ )
+ status, body, _transport_error = await _post_stream(launch)
+ router.settle_turn(
+ "turn_midengine01",
+ settled_by="no_terminal_result",
+ ts="2026-01-01T00:00:01+00:00",
+ )
+ return status, body, service.get_turn_provenance("turn_midengine01")
+ finally:
+ await gateway.close()
+
+ status, body, provenance = asyncio.run(exercise())
+ assert status == 200
+ assert body == b"data: partial\n\n"
+ assert [source_id for source_id, _model_id, _origin in adapter.invocations] == [first.id]
+ assert [item.state.status for item in store.load().sources] == ["standby", "standby"]
+ assert provenance["outcome"] == "failed_terminal"
+ assert provenance["terminal_error"]["reason"] == "engine_down"
+ assert provenance["terminal_error"]["stream_started"] is True
+ assert provenance["terminal_error"]["source_id"] is None
+ Draft7Validator(_provenance_schema()).validate(provenance)
+
+
+def test_mh_static_credential_failure_does_not_retry_or_claim_takeover(tmp_path: Path) -> None:
+ """MH-CREDENTIAL-001: a 401 retries once only when the stored credential can refresh."""
+
+ menu_model = fixed_model("claude")
+ static_source = source("src_credential01", [menu_model])
+ static_store = MemoryModelHubStore(config_with_sources([static_source], backend="claude", menu_model=menu_model))
+ static_adapter = ModelHubScenarioAdapter(
+ invoke_results=(
+ ScenarioCallResult(RawOutcomeKind.HTTP_ERROR, status=401),
+ ScenarioCallResult(RawOutcomeKind.SUCCESS, body=b"should-not-run"),
+ )
+ )
+ static_service = service_for(tmp_path / "static", static_store, static_adapter)
+ static_gateway = ModelHubTurnGateway(static_service)
+ static_router = ModelHubRuntimeRouter(
+ service=static_service,
+ turn_gateway=static_gateway,
+ )
+
+ refresh_ref = "cred_refreshable01"
+ refresh_source = source(
+ "src_credential02",
+ [menu_model],
+ credential_ref=refresh_ref,
+ )
+ refresh_store = MemoryModelHubStore(config_with_sources([refresh_source], backend="claude", menu_model=menu_model))
+ refresh_adapter = ModelHubScenarioAdapter(
+ invoke_results=(
+ ScenarioCallResult(RawOutcomeKind.HTTP_ERROR, status=401),
+ ScenarioCallResult(RawOutcomeKind.SUCCESS, body=b'{"answer":"ok"}'),
+ ),
+ refreshable_credential_refs=(refresh_ref,),
+ )
+ refresh_service = service_for(tmp_path / "refresh", refresh_store, refresh_adapter)
+ refresh_gateway = ModelHubTurnGateway(refresh_service)
+ refresh_router = ModelHubRuntimeRouter(
+ service=refresh_service,
+ turn_gateway=refresh_gateway,
+ )
+
+ async def exercise() -> tuple[int, dict]:
+ try:
+ static_launch = await static_router.resolve(
+ "claude",
+ menu_model,
+ turn_id="turn_credential01",
+ )
+ await _post(static_launch)
+ refresh_launch = await refresh_router.resolve(
+ "claude",
+ menu_model,
+ turn_id="turn_credential02",
+ )
+ return await _post(refresh_launch)
+ finally:
+ await static_gateway.close()
+ await refresh_gateway.close()
+
+ refresh_status, refresh_body = asyncio.run(exercise())
+ assert len(static_adapter.invocations) == 1
+ assert static_store.load().sources[0].state.status == "needs_action"
+ assert static_store.load().sources[0].state.detail_key == "models.source.needs_action.credential_revoked"
+ assert refresh_status == 200
+ assert refresh_body == {"answer": "ok"}
+ assert len(refresh_adapter.invocations) == 2
+ assert refresh_store.load().sources[0].state.status == "standby"
+
+
+def test_mh_turn_outcomes_and_cancel_are_closed_provenance_products(tmp_path: Path) -> None:
+ """MH-TURN-RESULT-001: runtime settlement produces every outcome and no value outside the schema."""
+
+ schema = _provenance_schema()
+ store = BoundedProvenanceStore(tmp_path / "provenance.json")
+ registry = TurnCorrelationRegistry(store)
+ records: list[dict] = []
+
+ def terminalizer(turn_id: str):
+ token = registry.credentials("claude", f"scope-{turn_id}", turn_id)
+ registry.prepare_gateway_turn(
+ backend="claude",
+ token=token,
+ requested_model_id="scenario-model",
+ resolved_model_id="scenario-model",
+ source_id="src_outcome01",
+ via_mapping=False,
+ )
+ return registry.gateway_terminalizer(backend="claude", token=token)
+
+ served = terminalizer("turn_served01")
+ with served:
+ served.finish_attempt(
+ outcome=_raw_outcome(RawOutcomeKind.SUCCESS),
+ decision=ResolutionDecision("return"),
+ )
+ registry.settle(
+ "turn_served01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ exhausted = terminalizer("turn_exhausted01")
+ with exhausted:
+ exhausted.finish_attempt(
+ outcome=_raw_outcome(RawOutcomeKind.HTTP_ERROR, status=429),
+ decision=ResolutionDecision("fallback", reason="rate_limited"),
+ )
+ registry.settle(
+ "turn_exhausted01",
+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,
+ )
+
+ failed = terminalizer("turn_failed01")
+ with failed:
+ failed.finish_attempt(
+ outcome=_raw_outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=400,
+ error_code="request_too_large",
+ ),
+ decision=ResolutionDecision(
+ "surface",
+ error_code="upstream_request_invalid",
+ ),
+ )
+ registry.settle(
+ "turn_failed01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ terminalizer("turn_drop01")
+ registry.settle(
+ "turn_drop01",
+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,
+ )
+
+ registry.mark_no_candidate(
+ backend="claude",
+ process_scope="scope-turn_no_candidate01",
+ turn_id="turn_no_candidate01",
+ requested_model_id="scenario-model",
+ supply_state="interrupted",
+ )
+ registry.settle(
+ "turn_no_candidate01",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ registry.begin_native_attempt(
+ backend="claude",
+ process_scope="scope-turn_canceled01",
+ turn_id="turn_canceled01",
+ requested_model_id="scenario-model",
+ source_id="src_outcome01",
+ resolved_model_id="scenario-model",
+ via_mapping=False,
+ )
+ registry.settle(
+ "turn_canceled01",
+ settled_by=SETTLED_BY_STOPPED,
+ )
+
+ for turn_id in (
+ "turn_served01",
+ "turn_exhausted01",
+ "turn_failed01",
+ "turn_drop01",
+ "turn_no_candidate01",
+ "turn_canceled01",
+ ):
+ record = store.get(turn_id)
+ assert record is not None
+ Draft7Validator(schema).validate(record)
+ records.append(record)
+
+ assert {record["outcome"] for record in records} == set(schema["properties"]["outcome"]["enum"])
+ canceled = store.get("turn_canceled01")
+ dropped = store.get("turn_drop01")
+ assert canceled is not None and dropped is not None
+ assert canceled["canceled_attempt"] is not None
+ assert "reason" not in canceled["canceled_attempt"]
+ assert dropped["outcome"] != canceled["outcome"]
+ assert dropped["terminal_error"]["reason"] == "stream_interrupted"
+
+ ambiguous_store = BoundedProvenanceStore(tmp_path / "ambiguous.json")
+ ambiguous = TurnCorrelationRegistry(ambiguous_store)
+ for turn_id in ("turn_cancel_a", "turn_cancel_b"):
+ ambiguous.begin_native_attempt(
+ backend="claude",
+ process_scope="shared-cancel-scope",
+ turn_id=turn_id,
+ requested_model_id="scenario-model",
+ source_id="src_outcome01",
+ resolved_model_id="scenario-model",
+ via_mapping=False,
+ )
+ for turn_id in ("turn_cancel_a", "turn_cancel_b"):
+ ambiguous.settle(turn_id, settled_by=SETTLED_BY_STOPPED)
+ assert ambiguous_store.get(turn_id) is None
+
+ ambiguous.begin_native_attempt(
+ backend="claude",
+ process_scope="sequential-cancel-scope",
+ turn_id="turn_cancel_control",
+ requested_model_id="scenario-model",
+ source_id="src_outcome01",
+ resolved_model_id="scenario-model",
+ via_mapping=False,
+ )
+ ambiguous.settle("turn_cancel_control", settled_by=SETTLED_BY_STOPPED)
+ control = ambiguous_store.get("turn_cancel_control")
+ assert control is not None
+ Draft7Validator(schema).validate(control)
+ assert control["outcome"] == canceled["outcome"]
+
+
+def test_mh_turn_copy_keys_cover_the_authoritative_outcome_matrix() -> None:
+ """MH-TURN-COPY-001: every frozen turn decision resolves to its backend locale copy or silence."""
+
+ rows = _turn_copy_rows()
+ api_contract = (CONTRACTS / "api.md").read_text()
+ api_decisions = set(re.findall(r"\bturn\.[a-z_.]+", api_contract))
+ schema_outcomes = set(_provenance_schema()["properties"]["outcome"]["enum"])
+ assert {row["decision"] for row in rows} == api_decisions
+ assert {row["outcome"] for row in rows} == schema_outcomes
+
+ projected = {
+ (decision, variant): copy.key if copy is not None else None
+ for decision, rule in TURN_OUTCOME_RENDERING_AUTHORITY.items()
+ for variant, _expected_key in rule.copy_keys
+ for copy in (
+ project_turn_outcome_copy(
+ _projection_for_copy_variant(decision, variant)
+ ),
+ )
+ }
+ expected = {
+ (decision, variant): key
+ for decision, rule in TURN_OUTCOME_RENDERING_AUTHORITY.items()
+ for variant, key in rule.copy_keys
+ }
+ assert projected == expected
+ copy_keys = {key for key in expected.values() if key is not None}
+
+ for language in ("en", "zh"):
+ locale = json.loads(Path(f"vibe/i18n/{language}.json").read_text())
+ assert all(isinstance(_locale_value(locale, key), str) for key in copy_keys)
+
+ nonfallback = TURN_OUTCOME_RENDERING_AUTHORITY["turn.request_nonfallback"]
+ assert "modelHub.launch.retry" not in {
+ key for _variant, key in nonfallback.copy_keys
+ }