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): replace source-inspection guards with boundary behavior tests (#2174)
Call White9a17894c7d0c
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 2517c0f78..b86fabdd6 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -6456,8 +6456,8 @@ class ModelHubService:# the native-slot read used to be one — strands the tuple until restart:# the retry finds a pending claim with no task and gets ``engine_down``,# and a cancelled owner never reaches the release at all.- # ``test_oauth_start_keeps_every_owner_await_inside_the_installed_task``- # holds the shape so the next pre-check cannot re-open the window.+ # ``test_nonce_oauth_start_retry_arriving_at_the_claim_joins_the_owner``+ # retries at the claim so the next pre-check cannot re-open the window.async def start_and_remember() -> dict:pending_source_id = _source_id()flow: OAuthFlowState | None = Nonediff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 3d211f555..25d611f16 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -196,7 +196,8 @@ comparison. A gate may not report success by comparing stale input with itself.- `tests/test_model_hub_runtime.py`- `ui/src/components/settings/models/*.test.*`-`tests/test_model_hub_config.py::test_every_versioned_object_ends_at_the_terminal_version_the_code_writes`+`scripts/check_model_hub_authorities.py`, run by+`tests/test_model_hub_config.py::test_model_hub_authority_closure_is_generated_from_live_files`,enforces the closure over whatever files this directory holds rather than over this list— versioned objects by their shape, and every `contract_version` a document writes astext — so an object or declaration added later is covered without an edit here. Thisdiff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex 80667ee36..075ff9efa 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -1045,6 +1045,9 @@ def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_assert [(model.id, model.display_name) for model in manual] == [(identity, "Long manual")]assert all(model.id not in invalid for model in source.models)assert source.state.status == "standby"+ # Failed discovery admits the Source on protocol evidence alone; the first+ # successful call must still prove it.+ assert bool(source.verification_pending) is (discovery is ObservationDiscovery.FAILED)assert _tree_digest(native_home) != beforeconfig_payload = json.loads((native_home / ".config" / "opencode" / "opencode.json").read_text(diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex a41ee8514..d605d3fa5 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -7,7 +7,6 @@ import inspectimport ioimport jsonimport re-import textwrapimport threadingfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone@@ -4515,6 +4514,15 @@ def test_hub_to_direct_fallback_does_not_require_engine_sync(tmp_path):assert adapter.synced == []+async def _confirm_guard(call):+ try:+ return await call({})+ except ModelHubError as refusal:+ if "would_remove_hops" not in (refusal.data or {}):+ raise+ return await call({"force": True, **refusal.data})++def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):service_node = next(node@@ -4610,6 +4618,137 @@ def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):assert service._engine_synced is True+def _catalog_without(service, model_id):+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")+ return baseline, [model for model in baseline if model["id"] != model_id]+++async def _delete_seeded_custom_model(service):+ service.store.config.sources[0].models.append(+ ModelHubModelConfig(id="claude-extra-model", provenance="manual")+ )+ return await service.delete_custom_model("src_first0001", "claude-extra-model")+++async def _reconcile_builtin_supplied_model(service):+ service.store.config.sources[0].models.append(+ ModelHubModelConfig(id="claude-extra-model", provenance="manual")+ )+ catalog = [{"id": model.id} for model in service.store.config.agents["claude"].models]+ service._builtin_snapshots = lambda _backends: {+ "claude": {"complete": True, "models": [*catalog, {"id": "claude-extra-model"}]},+ }+ return await service.reconcile_builtin_models(("claude",))+++_PROJECTION_MODEL = "claude-opus-4-6"+_PROJECTION_MUTATIONS = {+ "rename_source": (+ lambda service: service.patch_source("src_first0001", {"display_name": "Renamed"}),+ None,+ ),+ "switch_mode_direct": (+ lambda service: service.set_agent_mode("claude", "direct"),+ None,+ ),+ "reorder_agent_sources": (+ lambda service: service.set_agent_sources("claude", {"order": ["src_second001", "src_first0001"]}),+ None,+ ),+ "reorder_chain": (+ lambda service: service.set_agent_chain(+ "claude",+ _PROJECTION_MODEL,+ {"hops": [+ {"source_id": "src_second001", "model_id": _PROJECTION_MODEL},+ {"source_id": "src_first0001", "model_id": _PROJECTION_MODEL},+ ]},+ ),+ None,+ ),+ "retarget_base_url": (+ lambda service: _confirm_guard(lambda guard: service.patch_source(+ "src_first0001", {"base_url": "https://relay.example/v1", **guard},+ )),+ lambda bindings: bindings["src_first0001"].base_url == "https://relay.example/v1",+ ),+ "delete_source": (+ lambda service: _confirm_guard(lambda guard: service.delete_source(+ "src_second001",+ force=guard.get("force", False),+ confirmed_remove_hops=guard.get("would_remove_hops"),+ confirmed_interruptions=guard.get("would_interrupt"),+ )),+ lambda bindings: set(bindings) == {"src_first0001"},+ ),+ "add_custom_model": (+ lambda service: service.add_custom_model(+ "src_first0001", {"model_id": "claude-extra-model", "reasoning_efforts": []},+ ),+ lambda bindings: "claude-extra-model" in bindings["src_first0001"].model_ids,+ ),+ "delete_custom_model": (+ _delete_seeded_custom_model,+ lambda bindings: bindings["src_first0001"].model_ids == (_PROJECTION_MODEL,),+ ),+ "reconcile_builtin_models": (+ _reconcile_builtin_supplied_model,+ lambda bindings: "claude-extra-model" in bindings["src_first0001"].route_model_ids,+ ),+ "refresh_source": (+ lambda service: service.refresh_source("src_first0001"),+ lambda bindings: bindings["src_first0001"].model_ids == (_PROJECTION_MODEL, "claude-sonnet-4-6"),+ ),+ "set_reasoning_efforts": (+ lambda service: service.update_model_reasoning_efforts(+ "src_first0001", _PROJECTION_MODEL, {"reasoning_efforts": ["low"]},+ ),+ lambda bindings: bindings["src_first0001"].model_reasoning_efforts == ((_PROJECTION_MODEL, ("low",)),),+ ),+ "drop_agent_source": (+ lambda service: _confirm_guard(lambda guard: service.set_agent_sources(+ "claude", {"order": ["src_first0001"], **guard},+ )),+ lambda bindings: bindings["src_second001"].route_model_ids == (_PROJECTION_MODEL,),+ ),+ "shorten_chain": (+ lambda service: _confirm_guard(lambda guard: service.set_agent_chain(+ "claude",+ _PROJECTION_MODEL,+ {"hops": [{"source_id": "src_first0001", "model_id": _PROJECTION_MODEL}], **guard},+ )),+ lambda bindings: _PROJECTION_MODEL not in bindings["src_second001"].route_model_ids,+ ),+ "remove_catalog_model": (+ lambda service: _confirm_guard(lambda guard: service.set_agent_models(+ "claude",+ *_catalog_without(service, "claude-opus-4-7"),+ force=guard.get("force", False),+ confirmed_remove_hops=guard.get("would_remove_hops"),+ confirmed_interruptions=guard.get("would_interrupt"),+ )),+ lambda bindings: "claude-opus-4-7" not in bindings["src_first0001"].route_model_ids,+ ),+}++[email protected]("mutation", _PROJECTION_MUTATIONS)+def test_public_mutations_sync_the_engine_only_when_bindings_change(tmp_path, mutation):+ service, store, adapter = _service(tmp_path)+ _set_claude_route_fixture(store, ("src_first0001", "src_second001"), _PROJECTION_MODEL)+ service._engine_synced = True+ call, synced_projection = _PROJECTION_MUTATIONS[mutation]++ asyncio.run(call(service))++ if synced_projection is None:+ assert adapter.synced == []+ else:+ assert len(adapter.synced) == 1+ assert synced_projection({binding.source_id: binding for binding in adapter.synced[0]})+ assert service._engine_synced is True++def test_source_adoption_projection_is_sorted_by_backend_and_menu_model(tmp_path):service, store, _adapter = _service(tmp_path)source = ModelHubSourceConfig(@@ -7082,6 +7221,50 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(assert quota_reads == [source.id, source.id]+ "disposition",+ [RetainedMaterialDisposition.FLOW_SOURCE_REF, RetainedMaterialDisposition.UNKNOWN],+)+def test_hub_reauth_fail_closed_syncs_the_pruned_binding(tmp_path, disposition):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered"),+ ModelHubModelConfig(id="manual-model", provenance="manual"),+ ],+ credential_ref="cred_hub_existing",+ )+ store.config.sources.append(source)+ _refresh_fixture_routes(store.config)+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "failed",+ "error_key": "models.oauth.binding_failed",+ "channel": "hub",+ "retained_material_disposition": disposition,+ "retained_credential_ref": None,+ }+ )+ service._engine_synced = True+ adapter.synced.clear()++ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert len(adapter.synced) == 1+ synced = {binding.source_id: binding for binding in adapter.synced[0]}+ assert synced[source.id].model_ids == ("manual-model",)++@pytest.mark.parametrize("disposition",[@@ -7434,6 +7617,171 @@ def test_failed_hub_create_keeps_flow_when_ref_cleanup_is_not_durable(tmp_path):assert service.oauth_flows.binding(flow["flow_id"]) is not None+def _make_ref_cleanup_non_durable(service, adapter):+ def fail_journal_write(*_args, **_kwargs):+ raise OSError("journal is unavailable")++ async def fail_revocation(credential_ref):+ adapter.revoked.append(credential_ref)+ raise RuntimeError("engine is unavailable")++ service.revocations.add = fail_journal_write+ adapter.revoke_credential = fail_revocation+++def test_unbound_hub_start_fails_when_ref_cleanup_is_not_durable(tmp_path):+ service, _, adapter = _service(tmp_path)+ start_oauth = adapter.start_oauth++ async def start_foreign_flow_with_material(source_id, vendor):+ flow = await start_oauth(source_id, vendor)+ return OAuthFlowState(+ **{+ **flow.__dict__,+ "source_id": "src_foreign001",+ "credential_ref": "cred_unbound_flow",+ }+ )++ adapter.start_oauth = start_foreign_flow_with_material+ _make_ref_cleanup_non_durable(service, adapter)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))++ assert exc_info.value.code == "engine_down"+ assert adapter.revoked == ["cred_unbound_flow"]+ assert service.revocations.list() == []+++def test_failed_hub_oauth_source_creation_keeps_flow_when_ref_cleanup_is_not_durable(+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_oauth_rollback",+ }+ )+ adapter.fail_sync = True+ _make_ref_cleanup_non_durable(service, adapter)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ _create_source(+ service,+ {+ "kind": "subscription",+ "vendor": "anthropic",+ "display_name": "Rollback subscription",+ "supply_channel": "hub",+ "oauth_flow_ref": flow["flow_id"],+ },+ )+ )++ assert exc_info.value.code == "engine_down"+ assert adapter.revoked == ["cred_oauth_rollback"]+ assert store.config.sources == []+ assert service.revocations.list() == []+ assert service.oauth_flows.channel(flow["flow_id"]) == "hub"+++def test_cancelled_hub_oauth_source_creation_fails_when_ref_cleanup_is_not_durable(+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_oauth_cancelled",+ }+ )+ _make_ref_cleanup_non_durable(service, adapter)++ async def scenario():+ observing = asyncio.Event()++ async def blocked_observation(*_args, **_kwargs):+ observing.set()+ await asyncio.Event().wait()++ adapter.observe_source = blocked_observation+ task = asyncio.create_task(+ _create_source(+ service,+ {+ "kind": "subscription",+ "vendor": "anthropic",+ "display_name": "Cancelled subscription",+ "supply_channel": "hub",+ "oauth_flow_ref": flow["flow_id"],+ },+ )+ )+ await observing.wait()+ task.cancel()+ with pytest.raises(ModelHubError) as exc_info:+ await task+ return exc_info.value++ refusal = asyncio.run(scenario())++ assert (refusal.code, refusal.status) == ("engine_down", 503)+ assert adapter.revoked == ["cred_oauth_cancelled"]+ assert store.config.sources == []+ assert service.revocations.list() == []+++def test_orphaned_hub_reauth_fails_when_ref_cleanup_is_not_durable(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],+ credential_ref="cred_hub_old",+ )+ store.config.sources.append(source)+ _refresh_fixture_routes(store.config)+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]+ with pytest.raises(ModelHubError) as delete_refusal:+ asyncio.run(service.delete_source(source.id))+ asyncio.run(+ service.delete_source(+ source.id,+ force=True,+ confirmed_remove_hops=delete_refusal.value.data["would_remove_hops"],+ confirmed_interruptions=delete_refusal.value.data["would_interrupt"],+ )+ )+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_orphan",+ }+ )+ _make_ref_cleanup_non_durable(service, adapter)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "engine_down"+ assert adapter.revoked[-1] == "cred_hub_orphan"+ assert service.revocations.list() == []++@pytest.mark.parametrize(("terminal_state", "disposition", "retained_credential_ref"),[@@ -8245,36 +8593,44 @@ def test_nonce_oauth_start_owner_cancellation_releases_waiter_and_tuple(tmp_pathassert len(adapter.oauth_start_calls) == 1-def test_oauth_start_keeps_every_owner_await_inside_the_installed_task(tmp_path):[email protected]("channel", ("native_cli", "hub"))+def test_nonce_oauth_start_retry_arriving_at_the_claim_joins_the_owner(tmp_path, channel):"""A claimed nonce stays awaitable and releasable from the claim onward.The claim is what a concurrent same-tuple retry looks for, and the only- release is ``start_and_remember``'s own ``finally``. An owner await placed- before the task is installed therefore strands the tuple until restart, so- this asserts the property rather than the one pre-check that broke it: on the- owner path from claim to install there is nothing to wait on at all.+ release is the owner task's own ``finally``. The retry is scheduled the+ instant the owner claims, so any owner await before its task is installed+ lets the retry find a pending claim with no task and fail ``engine_down``."""- tree = ast.parse(textwrap.dedent(inspect.getsource(ModelHubService.oauth_start)))- body = tree.body[0].body- claim = next(i for i, stmt in enumerate(body) if "claim_nonce" in ast.unparse(stmt))- install = next(i for i, stmt in enumerate(body) if "_oauth_start_tasks[nonce_key] = task" in ast.unparse(stmt))+ async def run_retry_at_claim():+ service, _, adapter = _service(tmp_path)+ request = {+ "vendor": "anthropic",+ "channel": channel,+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",+ }+ claim_nonce = service.oauth_flows.claim_nonce+ retries = []++ def claim_then_retry(*args, **kwargs):+ claim = claim_nonce(*args, **kwargs)+ if claim.owner:+ retries.append(asyncio.create_task(service.oauth_start(dict(request))))+ return claim- for stmt in body[claim + 1 : install]:- if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):- # The task's own awaits are the safe ones: it is installed before it- # is awaited, and it owns the release.- continue- if isinstance(stmt, ast.If) and ast.unparse(stmt.test) == "nonce_key is None":- # No nonce, no claim — nothing for a retry to await or for a- # cancellation to leak.- continue- waits = [node for node in ast.walk(stmt) if isinstance(node, (ast.Await, ast.AsyncWith, ast.AsyncFor))]- assert not waits, f"owner awaits before its task is installed: {ast.unparse(stmt)}"+ service.oauth_flows.claim_nonce = claim_then_retry+ first = await service.oauth_start(request)+ return first, await retries[0], adapter++ first, retried, adapter = asyncio.run(run_retry_at_claim())++ assert retried == first+ assert len(adapter.oauth_start_calls) == 1def test_nonce_oauth_start_coalesces_a_retry_while_the_native_slot_read_waits(tmp_path):- """The member the structure guard above exists for, end to end."""+ """A retry that waits behind the native-slot lock still joins the owner."""async def run_concurrent_start():service, _, adapter = _service(tmp_path)diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 1f716361c..c43a111d7 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -29,7 +29,7 @@ from config.v2_config import (V2Config,is_model_hub_enabled,)-from core.handlers.model_hub.service import CONTRACT_VERSION, ModelHubService+from core.handlers.model_hub.service import ModelHubServicefrom core.services.settings import default_configfrom core.handlers.model_hub.adapter import (DiscoveredModel,@@ -47,7 +47,6 @@ from scripts.check_model_hub_authorities import (from vibe import apiCONTRACTS = Path("docs/plans/model-hub-contracts")-UI_MODEL_CONSUMERS = Path("ui/src/components/settings/models")def _schema(name: str) -> dict:@@ -66,35 +65,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():protocols = tuple(_schema("source.schema.json")["properties"]["protocol"]["enum"])assert SOURCE_PROTOCOLS == protocols- type_source = (UI_MODEL_CONSUMERS / "types.ts").read_text(encoding="utf-8")- tuple_match = re.search(- r"export const SOURCE_PROTOCOLS\s*=\s*\[(.*?)\]\s*as const",- type_source,- re.DOTALL,- )- assert tuple_match is not None- ui_protocols = tuple(re.findall(r"'([^']+)'", tuple_match.group(1)))- assert frozenset(ui_protocols) == frozenset(protocols)- assert len(ui_protocols) == len(set(ui_protocols))-- type_match = re.search(- r"export type SourceProtocol\s*=\s*(.*?);",- type_source,- re.DOTALL,- )- assert type_match is not None- assert re.sub(r"\s+", "", type_match.group(1)) == "(typeofSOURCE_PROTOCOLS)[number]"-retired_alias = "openai" + "_compatible"- for filename in (- "types.ts",- "vendorMeta.ts",- "modelsApi.ts",- "mockData.ts",- "modelRows.test.ts",- ):- assert retired_alias not in (UI_MODEL_CONSUMERS / filename).read_text(encoding="utf-8")-example = copy.deepcopy(_schema("source.schema.json")["examples"][0])example["protocol"] = retired_aliaswith pytest.raises(ValidationError):@@ -833,101 +804,6 @@ def test_v8_mirror_registry_is_executable_and_complete():_validate_mirror_entry(entry, schemas)-def _versioned_nodes(node):- """Yield every `contract_version` subschema, however deeply a branch nests it."""-- if isinstance(node, dict):- declared = node.get("properties")- if isinstance(declared, dict) and isinstance(declared.get("contract_version"), dict):- yield declared["contract_version"]- for value in node.values():- yield from _versioned_nodes(value)- elif isinstance(node, list):- for item in node:- yield from _versioned_nodes(item)---def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():- # One number spans all versioned objects, so a bump has to move every one of- # them at once — round 4 shipped it half-applied because nothing compared the- # schemas with each other or with the writer. Reading the accepted values out- # of whatever schemas the directory holds, rather than listing the ones that- # carry a version, covers an object added later without editing this test.- #- # TurnProvenance is the one exception, and it earns it by being written to- # disk: the same bump that republishes an envelope would strand every record- # a released build persisted, so it accepts the released values and ends at- # the terminal one. The `== [terminal]` branch is what keeps that from- # spreading to objects that never outlive their request.- registry = json.loads(- (CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8")- )- terminal = registry["contract_version"]- assert CONTRACT_VERSION == terminal- persisted = registry["contract_version_closure"][- "persisted_schema_version_floors"- ]- checked = set()- for path in sorted(CONTRACTS.glob("*.schema.json")):- for node in _versioned_nodes(json.loads(path.read_text(encoding="utf-8"))):- checked.add(path.name)- accepted = [node["const"]] if "const" in node else list(node["enum"])- assert accepted == sorted(set(accepted)), path.name- assert accepted[-1] == terminal, path.name- if path.name in persisted:- assert accepted == list(- range(persisted[path.name], terminal + 1)- ), path.name- else:- assert accepted == [terminal], path.name- assert set(persisted) <= checked- assert "api-response.schema.json" in checked-- # The schemas above are structured, so their versions are read from the shape.- # Every other file beside them publishes the same number as text, and nothing- # compared those: `api.md` carried the terminal value in eighteen envelopes- # while three of its own declarations still named the previous one, which is- # two review rounds spent on one stale sentence at a time. Matching the token- # a consumer reads, rather than a list of sentences, is what makes the next- # declaration fail here instead of in review — and it is why a claim about the- # current value is written as `contract_version <n>` while a bare `vN` names- # the generation a sentence was authored in.- stated = 0- for path in sorted(CONTRACTS.iterdir()):- if not path.is_file() or path.name.endswith(".schema.json"):- continue- for value in re.findall(r"contract_version[^0-9]{0,12}(\d+)", path.read_text(encoding="utf-8")):- stated += 1- assert int(value) == terminal, path.name- assert stated-- # The UI declares the same number as a literal type, and `tsc` is the only- # thing that would have caught it drifting — one language boundary away from- # every check above, which is where this bump went half-applied a second time.- # A regex over the declaration is cheap; noticing in review is not.- declared = re.search(- r"^export const CONTRACT_VERSION = (\d+) as const;$",- Path("ui/src/components/settings/models/types.ts").read_text(encoding="utf-8"),- flags=re.MULTILINE,- )- assert declared is not None- assert int(declared.group(1)) == terminal-- ui_types = Path("ui/src/components/settings/models/types.ts").read_text(encoding="utf-8")- persisted_versions = re.search(- r"export const PERSISTED_TURN_CONTRACT_VERSIONS\s*=\s*(\[[^\]]*\])\s+as const;",- ui_types,- )- assert persisted_versions is not None- provenance_schema = json.loads((CONTRACTS / "turn-provenance.schema.json").read_text(encoding="utf-8"))- assert json.loads(persisted_versions.group(1)) == provenance_schema["properties"]["contract_version"]["enum"]- assert re.search(- r"export type TurnProvenance\s*=\s*\{\s*contract_version:\s*"- r"\(typeof PERSISTED_TURN_CONTRACT_VERSIONS\)\[number\];",- ui_types,- )--def test_contracts_readme_indexes_every_file_beside_it():# The index is what a reader consults to learn a contract exists at all, so a# file missing from it is invisible even though it ships. Both this PR's@@ -1062,6 +938,24 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp} in result["findings"]+def _versioned_nodes(node):+ """Yield every `contract_version` subschema, however deeply a branch nests it."""++ if isinstance(node, dict):+ declared = node.get("properties")+ if isinstance(declared, dict) and isinstance(declared.get("contract_version"), dict):+ yield declared["contract_version"]+ for value in node.values():+ yield from _versioned_nodes(value)+ elif isinstance(node, list):+ for item in node:+ yield from _versioned_nodes(item)+++def test_api_response_envelope_stays_versioned():+ assert any(_versioned_nodes(_schema("api-response.schema.json")))++def test_turn_provenance_contract_preserves_an_empty_stripped_effort():payload = copy.deepcopy(_schema("turn-provenance.schema.json")["examples"][0])payload["served"]["stripped_reasoning_efforts"] = [""]diff --git a/tests/test_model_hub_credential_address.py b/tests/test_model_hub_credential_address.pyindex adcdcf718..15cb710a1 100644--- a/tests/test_model_hub_credential_address.py+++ b/tests/test_model_hub_credential_address.py@@ -897,6 +897,18 @@ def test_the_runtime_repairs_a_stored_address_before_the_engine_sees_it(tmp_pathassert adapter.synced[-1][0].model_ids == ("gpt-5.5", "x-ai/grok-4.6-latest")+def test_a_repair_on_an_already_synced_engine_resyncs_the_projection(tmp_path) -> None:+ """A repaired id is a projection change even when the engine was up to date."""++ service, store, adapter = _addressed_service(tmp_path, {"cred_fixture123": ADDRESS})+ service._engine_synced = True++ asyncio.run(service._prepare_engine_for_demand())++ assert len(adapter.synced) == 1+ assert adapter.synced[0][0].model_ids == ("gpt-5.5", "x-ai/grok-4.6-latest")++def test_the_runtime_leaves_an_id_alone_when_the_address_is_unprovable(tmp_path) -> None:"""No proof, no rename — the file is left exactly as the last release left it.diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex ede27a5dd..28ba0647a 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -103,11 +103,13 @@ from storage.models import agent_sessions, messages, metadatafrom vibe.i18n import t as i18n_tfrom vibe.model_hub_runtime.adapter import (_AuthenticationEvidence,+ _AuthRecord,CLIProxyEngineAdapter,hub_subscription_serving_protocol,_HUB_SUBSCRIPTION_PROTOCOLS,_OAUTH_ENDPOINTS,_parse_protocol_authenticated_evidence,+ _probe_oauth_protocol_response,_probe_protocol_response,_PROTOCOL_OBSERVATION_TAXONOMY,_ProtocolEvidence,@@ -8551,73 +8553,6 @@ def test_top_level_authentication_rejection_is_classified_without_forging_protoc)-def test_protocol_observation_consumers_cannot_classify_from_status_codes() -> None:- module_path = Path(__file__).parents[1] / "vibe/model_hub_runtime/adapter.py"- module_source = module_path.read_text(encoding="utf-8")- tree = ast.parse(module_source)- assert _PROTOCOL_OBSERVATION_TAXONOMY.keys() == set(SOURCE_PROTOCOLS)- assert _PROTOCOL_OBSERVATION_TAXONOMY["anthropic"].request_body == {- "max_tokens": 0,- "messages": [],- }- assert _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_path != _PROTOCOL_OBSERVATION_TAXONOMY[- "openai_chat"- ].request_path- assert all(- "model" not in taxonomy.request_body- for taxonomy in _PROTOCOL_OBSERVATION_TAXONOMY.values()- )- consumers = {- node.name: node- for node in ast.walk(tree)- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))- and node.name in {"_probe_protocol_response", "_probe_oauth_protocol_response"}- }-- assert consumers.keys() == {- "_probe_protocol_response",- "_probe_oauth_protocol_response",- }- assert "json={}" not in module_source- assert '"data": "{}"' not in module_source- assert "_endpoint_for_protocol(" not in module_source- for consumer in consumers.values():- consumer_source = ast.get_source_segment(module_source, consumer)- assert consumer_source is not None- assert "_PROTOCOL_OBSERVATION_TAXONOMY" in consumer_source- calls = [node for node in ast.walk(consumer) if isinstance(node, ast.Call)]- assert any(- isinstance(call.func, ast.Name) and call.func.id == "_parse_protocol_authenticated_evidence"- for call in calls- )- compared_statuses = {- constant.value- for compare in ast.walk(consumer)- if isinstance(compare, ast.Compare)- for constant in ast.walk(compare)- if isinstance(constant, ast.Constant)- and isinstance(constant.value, int)- and not isinstance(constant.value, bool)- }- assert not compared_statuses-- auth_branch_offenders = []- for function in (- node- for node in ast.walk(tree)- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))- and node.name not in {- "_parse_protocol_authenticated_evidence",- }- ):- for branch in (node for node in ast.walk(function) if isinstance(node, (ast.If, ast.IfExp))):- condition = ast.unparse(branch.test)- branch_source = ast.unparse(branch)- if any(token in condition for token in ("status", "error")) and "_AuthenticationEvidence" in branch_source:- auth_branch_offenders.append((function.name, condition))- assert not auth_branch_offenders--def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -> None:query = "api-version=2026-07-23"@@ -8654,10 +8589,83 @@ def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -assert len(paths) == len(SOURCE_PROTOCOLS)assert len(set(paths)) == len(paths)assert {request_query for _path, request_query, _body in requests} == {query}- assert [body for _path, _query, body in requests] == [- dict(_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_body)- for protocol in SOURCE_PROTOCOLS+ # Model-free bodies fail request validation before a relay schedules capacity.+ assert dict(zip(SOURCE_PROTOCOLS, (body for _path, _query, body in requests))) == {+ "anthropic": {"max_tokens": 0, "messages": []},+ "openai_responses": {},+ "openai_chat": {},+ }++[email protected]("status", (200, 401))+def test_protocol_observation_classifies_from_the_body_not_the_status(status) -> None:+ """A status code alone neither proves an interface nor authenticates a key."""++ async def scenario() -> list:+ async def shapeless(_request: web.Request) -> web.Response:+ return web.json_response({"status": "ok"}, status=status)++ app = web.Application()+ app.router.add_post("/{tail:.*}", shapeless)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ try:+ return [+ await _probe_protocol_response(+ vendor="custom",+ protocol=protocol,+ base_url=f"http://127.0.0.1:{port}/v1",+ secret="test-observation-key",+ )+ for protocol in SOURCE_PROTOCOLS+ ]+ finally:+ await runner.cleanup()++ for evidence in asyncio.run(scenario()):+ assert evidence.protocol is _ProtocolProof.UNPROVEN+ assert evidence.authentication is _AuthenticationEvidence.UNKNOWN++[email protected]("status", (200, 401))+ ("vendor", "protocol"),+ (("anthropic", "anthropic"), ("openai", "openai_responses"), ("codex", "openai_responses")),+)+def test_oauth_protocol_observation_classifies_from_the_body_not_the_status(vendor, protocol, status) -> None:+ """The engine-held OAuth probe sends the model-free body and reads the shape, not the status."""++ class Client:+ def __init__(self) -> None:+ self.payloads: list[dict] = []++ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ self.payloads.append(payload)+ return {"status_code": status, "body": json.dumps({"status": "ok"})}++ client = Client()+ evidence = _probe_oauth_protocol_response(+ client=client, # type: ignore[arg-type]+ auth=_AuthRecord(+ identity="account.json",+ auth_index="0",+ name="account.json",+ provider=vendor,+ fingerprint="fp",+ ),+ vendor=vendor,+ protocol=protocol,+ )++ assert [json.loads(payload["data"]) for payload in client.payloads] == [+ {"anthropic": {"max_tokens": 0, "messages": []}, "openai_responses": {}}[protocol]]+ assert evidence.protocol is _ProtocolProof.UNPROVEN+ assert evidence.authentication is _AuthenticationEvidence.UNKNOWNdef test_protocol_observation_adds_standard_v1_paths_to_a_bare_origin() -> None:diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 8d119f089..5cba88f5f 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1300,28 +1300,6 @@ def test_chain_write_rejects_models_outside_the_current_menu(assert store.load().to_payload() == before-def test_refresh_ignores_preexisting_unrelated_interruption(tmp_path):- menu_model = "claude-opus-4-6"- source = _source("src_refresh02", (menu_model,))- broken = _source("src_refresh03", ("other",), status="cooldown")- broken.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2099-01-01T00:00:00Z",- detail_key="models.source.cooldown.rate_limited",- )- config = _config([source, broken], model=menu_model)- config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(broken.id, "other"),)- )- adapter = FakeAdapter(discovered=(menu_model,))- service, _store, _ = _service(tmp_path, config, adapter)-- result = asyncio.run(service.refresh_source(source.id))-- assert result["removed_hops"] == []- assert result["interrupted"] == []--def test_engine_binding_preserves_empty_inventory(tmp_path):source = _source("src_empty01", (), vendor="openai")config = _config([source], model="requested")@@ -1411,48 +1389,6 @@ def test_set_agent_chain_reports_removed_hops_and_syncs_transport_targets(tmp_pa}-def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):- menu_model = "claude-opus-4-6"- first = _source("src_chain008", (menu_model,))- second = _source("src_chain009", (menu_model,))- broken = _source(- "src_chain010",- ("other",),- status="cooldown",- )- broken.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2099-01-01T00:00:00Z",- detail_key="models.source.cooldown.rate_limited",- )- config = _config([first, second, broken], model=menu_model)- config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(broken.id, "other"),)- )- service, store, adapter = _service(tmp_path, config)-- 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 result["interrupted"] == []- assert len(adapter.synced) == 1- assert set(adapter.synced[0][-1].route_model_ids) == {- "other", *(model.id for agent in config.agents.values() for model in agent.models- if model.id not in {menu_model, "claude-sonnet-4-6"})- }- assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]--def test_source_creation_cancellation_revokes_unsaved_credential(tmp_path):adapter = FakeAdapter()adapter.discovery_started = asyncio.Event()@@ -1802,44 +1738,98 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):assert adapter.revoked == ["cred_00000001"]-def test_observation_terminal_legality_has_no_service_or_runtime_copy():- from ast import AsyncFunctionDef, Attribute, Call, FunctionDef, Name, parse, walk- from pathlib import Path-- root = Path(__file__).parents[1]- service_tree = parse(- (root / "core/handlers/model_hub/service.py").read_text(encoding="utf-8")- )- runtime_tree = parse(- (root / "vibe/model_hub_runtime/adapter.py").read_text(encoding="utf-8")- )+ "illegal_observation",+ [+ SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=None,+ discovery=ObservationDiscovery.SUCCEEDED,+ models=(DiscoveredModel(id="claude-opus-4-6"),),+ ),+ SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol="anthropic",+ discovery=ObservationDiscovery.FAILED,+ models=(DiscoveredModel(id="claude-opus-4-6"),),+ ),+ SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=True,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ ),+ SourceObservation(+ outcome=ObservationOutcome.AMBIGUOUS,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ ),+ SourceObservation(+ outcome=ObservationOutcome.UNREACHABLE,+ reachable=True,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ ),+ SourceObservation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=True,+ authenticated=None,+ protocol="anthropic",+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ ),+ SourceObservation(+ outcome=ObservationOutcome.TIMEOUT,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(DiscoveredModel(id="claude-opus-4-6"),),+ ),+ ],+ ids=[+ "observed_without_protocol",+ "failed_discovery_with_models",+ "auth_failed_but_authenticated",+ "ambiguous_but_rejected",+ "unreachable_but_reached",+ "adapter_error_with_protocol",+ "timeout_with_models",+ ],+)+def test_illegal_adapter_observation_is_never_previewed_and_revokes_the_credential(+ tmp_path,+ illegal_observation,+):+ adapter = FakeAdapter()+ adapter.observation = illegal_observation+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- def calls(function) -> set[str]:- return {- node.func.id if isinstance(node.func, Name) else node.func.attr- for node in walk(function)- if isinstance(node, Call) and isinstance(node.func, (Name, Attribute))- }+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.observe_source(+ {+ "vendor": "anthropic",+ "base_url": None,+ "key": "sk-test-illegal-observation",+ }+ )+ )- validator = next(- node- for node in walk(service_tree)- if isinstance(node, FunctionDef) and node.name == "_validate_observation"- )- producer = next(- node- for node in walk(runtime_tree)- if isinstance(node, AsyncFunctionDef) and node.name == "observe_source"- )- assert "validate_source_observation" in calls(validator)- assert "make_source_observation" in calls(producer)- assert "SourceObservation" not in calls(producer)- assert not any(- isinstance(node, Attribute)- and isinstance(node.value, Name)- and node.value.id == "ObservationOutcome"- for node in walk(validator)- )+ assert (exc.value.code, exc.value.status) == ("discovery_failed", 502)+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]def test_unsaved_observation_cancellation_revokes_before_settling(tmp_path):@@ -1927,28 +1917,95 @@ def test_unsaved_observation_revoke_failure_is_journaled_and_reconciled(tmp_pathassert adapter.revoked == ["cred_00000001"]-def test_unsaved_observation_fails_when_cleanup_is_not_durable(tmp_path):+ "operation",+ ["observe", "create_source", "replace_credential", "retarget_base_url"],+)+def test_unsaved_observation_fails_when_cleanup_is_not_durable(tmp_path, operation):+ source = _source("src_cleanup01", vendor="custom")+ source.base_url = "https://old-relay.example/v1"adapter = FakeAdapter()adapter.revoke_error = True- service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ )+ service, store, _ = _service(tmp_path, _config([source]), adapter)+ before = store.load().to_payload()def fail_journal_write(*_args, **_kwargs):raise OSError("journal is unavailable")service.revocations.add = fail_journal_write+ mutation = {+ "observe": lambda: service.observe_source(+ {+ "vendor": "anthropic",+ "base_url": None,+ "key": "sk-test-observation-cleanup-failure",+ }+ ),+ "create_source": lambda: service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-create-cleanup-failure",+ }+ ),+ "replace_credential": lambda: service.replace_credential(+ source.id, {"key": "sk-test-replacement-cleanup-failure"}+ ),+ "retarget_base_url": lambda: service.patch_source(+ source.id, {"base_url": "https://new-relay.example/v1"}+ ),+ }[operation]with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.observe_source(+ asyncio.run(mutation())++ assert exc_info.value.code == "engine_down"+ assert store.load().to_payload() == before+ assert service.revocations.list() == []+++def test_provision_cancellation_fails_when_cleanup_is_not_durable(tmp_path):+ adapter = FakeAdapter()+ adapter.provision_started = asyncio.Event()+ adapter.provision_block = asyncio.Event()+ adapter.revoke_error = True+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)++ def fail_journal_write(*_args, **_kwargs):+ raise OSError("journal is unavailable")++ service.revocations.add = fail_journal_write++ async def scenario():+ task = asyncio.create_task(+ service.create_source({+ "kind": "api_key","vendor": "anthropic",- "base_url": None,- "key": "sk-test-observation-cleanup-failure",+ "display_name": "Key",+ "key": "sk-test-provision-cancel-cleanup-failure",}))+ await adapter.provision_started.wait()+ task.cancel()+ adapter.provision_block.set()+ with pytest.raises(ModelHubError) as exc_info:+ await task+ return exc_info.value- assert exc_info.value.code == "engine_down"+ refusal = asyncio.run(scenario())++ assert (refusal.code, refusal.status) == ("engine_down", 503)assert store.load().sources == []assert service.revocations.list() == []@@ -1977,92 +2034,84 @@ def test_credential_cleanup_settlement_has_one_durable_boundary():assert raw_cleanup_callers == {"_require_credential_cleanup"}-def test_source_admission_uses_explicit_owners_and_keeps_verified_paths_proven():- from ast import AsyncFunctionDef, Attribute, Call, Name, parse, walk- from pathlib import Path+def test_created_source_cancellation_fails_when_cleanup_is_not_durable(tmp_path):+ adapter = FakeAdapter()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)+ provision_credential = adapter.provision_credential- root = Path(__file__).parents[1]- production_trees = [- parse(path.read_text(encoding="utf-8"), filename=str(path))- for directory in ("config", "core", "modules", "vibe")- for path in (root / directory).rglob("*.py")- ]- assert not any(- (- isinstance(node, Name)- and node.id == "_default_protocol"- )- or (- isinstance(node, Attribute)- and node.attr == "_default_protocol"- )- for tree in production_trees- for node in walk(tree)- )+ def fail_journal_write(*_args, **_kwargs):+ raise OSError("journal is unavailable")- def async_functions(path: Path) -> dict[str, AsyncFunctionDef]:- tree = parse(path.read_text(encoding="utf-8"), filename=str(path))- return {- node.name: node- for node in walk(tree)- if isinstance(node, AsyncFunctionDef)- }+ async def provision_then_lose_cleanup(*args):+ credential_ref = await provision_credential(*args)+ adapter.revoke_error = True+ service.revocations.add = fail_journal_write+ adapter.discovery_started = asyncio.Event()+ adapter.discovery_block = asyncio.Event()+ return credential_ref- def calls(function: AsyncFunctionDef) -> set[str]:- return {- (- node.func.id- if isinstance(node.func, Name)- else node.func.attr+ adapter.provision_credential = provision_then_lose_cleanup++ async def scenario():+ task = asyncio.create_task(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-created-cancel-cleanup-failure",+ "protocol": "anthropic",+ "save_unverified": True,+ })- for node in walk(function)- if isinstance(node, Call)- and isinstance(node.func, (Name, Attribute))- }+ )+ while adapter.discovery_started is None:+ await asyncio.sleep(0)+ await adapter.discovery_started.wait()+ task.cancel()+ with pytest.raises(ModelHubError) as exc_info:+ await task+ return exc_info.value- service_functions = async_functions(- root / "core/handlers/model_hub/service.py"- )- migration_functions = async_functions(- root / "core/handlers/model_hub/migration.py"- )+ refusal = asyncio.run(scenario())- assert "_require_proven_source_payload" in calls(- service_functions["create_source"]- )- assert "_prepare_takeover" in calls(migration_functions["apply_native_migration"])- assert "_require_proven_source_payload" in calls(migration_functions["_prepare_takeover"])- oauth_calls = calls(service_functions["_create_oauth_source"])- assert "_observe_provisioned_credential" in oauth_calls- assert "_mark_source_unverified" in oauth_calls- assert "_mark_source_unverified" in calls(service_functions["create_source"])- assert "_mark_source_unverified" in calls(migration_functions["_prepare_takeover"])+ assert (refusal.code, refusal.status) == ("engine_down", 503)+ assert store.load().sources == []+ assert service.revocations.list() == []-def test_manual_model_delete_ignores_preexisting_unrelated_gap(tmp_path):- source = _source("src_manual001")- source.models.append(- ModelHubModelConfig(id="manual-model", provenance="manual")- )- broken = _source("src_manual002", ("other-model",), status="cooldown")- broken.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2099-01-01T00:00:00Z",- detail_key="models.source.cooldown.rate_limited",- )- config = _config([source, broken])- config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)- )- service, store, _ = _service(tmp_path, config)+def test_created_source_commit_failure_fails_when_cleanup_is_not_durable(tmp_path):+ adapter = FakeAdapter()+ adapter.revoke_error = True+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)+ journal_add = service.revocations.add- result = asyncio.run(service.delete_custom_model(source.id, "manual-model"))+ def journal_only_the_observation(source_id, credential_ref):+ if source_id != "observation":+ raise OSError("journal is unavailable")+ return journal_add(source_id, credential_ref)- assert result["removed_hops"] == []- assert result["interrupted"] == []- assert [model.id for model in store.load().sources[0].models] == [- "claude-opus-4-6"- ]+ def fail_save(*_args, **_kwargs):+ raise OSError("disk full")++ service.revocations.add = journal_only_the_observation+ store.save = fail_save++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-create-commit-cleanup-failure",+ }+ )+ )++ assert exc_info.value.code == "engine_down"+ assert store.load().sources == []+ assert {entry.source_id for entry in service.revocations.list()} == {"observation"}def test_manual_model_delete_preserves_explicit_route(tmp_path):@@ -2081,58 +2130,6 @@ def test_manual_model_delete_preserves_explicit_route(tmp_path):assert service.agent_chain("claude", menu_model)["current"]["model_id"] == "manual-model"-def test_delete_unused_source_ignores_preexisting_unrelated_gap(tmp_path):- menu_model = "claude-opus-4-6"- healthy = _source("src_delete02", (menu_model,))- unused = _source("src_delete03", ("unused-model",))- broken = _source("src_delete04", ("other-model",), status="cooldown")- broken.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2099-01-01T00:00:00Z",- detail_key="models.source.cooldown.rate_limited",- )- config = _config([healthy], model=menu_model)- config.sources.extend((unused, broken))- config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)- )- service, store, _ = _service(tmp_path, config)-- result = asyncio.run(service.delete_source(unused.id))-- assert result == {"removed_hops": [], "interrupted": []}- assert {source.id for source in store.load().sources} == {healthy.id, broken.id}---def test_credential_replace_ignores_preexisting_unrelated_gap(tmp_path):- menu_model = "claude-opus-4-6"- healthy = _source("src_replace01", (menu_model,))- broken = _source("src_replace02", ("other-model",), status="cooldown")- broken.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2099-01-01T00:00:00Z",- detail_key="models.source.cooldown.rate_limited",- )- config = _config([healthy], model=menu_model)- config.sources.append(broken)- config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)- )- service, _store, adapter = _service(- tmp_path,- config,- FakeAdapter(discovered=(menu_model,)),- )-- result = asyncio.run(- service.replace_credential(healthy.id, {"key": "replacement-key"})- )-- assert result["removed_hops"] == []- assert result["interrupted"] == []- assert adapter.provisioned == ["replacement-key"]--def test_delete_source_reports_and_then_prunes_exact_hops(tmp_path):menu_model = "claude-opus-4-6"source = _source("src_delete01", (menu_model,))@@ -2250,65 +2247,82 @@ def test_inventory_mutations_share_the_successful_discovery_finalizer(assert [model.id for model in persisted.models] == list(discovered)-def test_all_interruption_guards_use_the_shared_baseline_comparator():- from ast import Attribute, AsyncFunctionDef, Name, parse, walk- from pathlib import Path+_GAP_MENU_MODEL = "claude-opus-4-6"- tree = parse(- (Path(__file__).parents[1] / "core/handlers/model_hub/service.py").read_text(- encoding="utf-8"- )++def _catalog_renaming(service, model_id):+ baseline = next(+ agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")- direct_baseline_guards = {- "delete_source",- "_write_agent_chain",- "set_agent_sources",- "delete_custom_model",- }- inventory_guards = {- "patch_source",- "replace_credential",- "refresh_source",- }- methods = {- node.name: node- for node in walk(tree)- if isinstance(node, AsyncFunctionDef)- and node.name in direct_baseline_guards | inventory_guards- }+ return baseline, [+ {**model, "display_name": "Renamed"} if model["id"] == model_id else model+ for model in baseline+ ]- def calls(method):- return [- (- node.func.id- if isinstance(node.func, Name)- else node.func.attr- if isinstance(node.func, Attribute)- else None- )- for node in walk(method)- if node.__class__.__name__ == "Call"- ]-- inventory_finalizer = next(- node- for node in walk(tree)- if node.__class__.__name__ == "AsyncFunctionDef"- and node.name == "_finalize_successful_discovery"- )- assert "_guard_inventory_mutation" in calls(inventory_finalizer)- assert "_apply_discovered_models" in calls(inventory_finalizer)- assert "_commit_synced" in calls(inventory_finalizer)-- for name in inventory_guards:- assert "_finalize_successful_discovery" in calls(methods[name])- assert "_guard_inventory_mutation" not in calls(methods[name])- assert "_apply_discovered_models" not in calls(methods[name])- assert "_introduced_interruptions" not in calls(methods[name])-- for name in direct_baseline_guards:- assert "_introduced_interruptions" in calls(methods[name])- assert "_would_interrupt" not in calls(methods[name])++_PREEXISTING_GAP_MUTATIONS = {+ "refresh_source": lambda service: service.refresh_source("src_gap00001"),+ "retarget_base_url": lambda service: service.patch_source(+ "src_gap00001", {"base_url": "https://new-relay.example/v1"}+ ),+ "replace_credential": lambda service: service.replace_credential(+ "src_gap00001", {"key": "replacement-key"}+ ),+ "set_agent_chain": lambda service: service.set_agent_chain(+ "claude",+ _GAP_MENU_MODEL,+ {+ "hops": [+ {"source_id": "src_gap00002", "model_id": _GAP_MENU_MODEL},+ {"source_id": "src_gap00001", "model_id": _GAP_MENU_MODEL},+ ]+ },+ ),+ "set_agent_sources": lambda service: service.set_agent_sources(+ "claude", {"order": ["src_gap00002", "src_gap00001"]}+ ),+ "set_agent_models": lambda service: service.set_agent_models(+ "claude", *_catalog_renaming(service, "claude-haiku-4-5")+ ),+ "delete_custom_model": lambda service: service.delete_custom_model(+ "src_gap00001", "manual-model"+ ),+ "delete_source": lambda service: service.delete_source("src_gap00003"),+}++[email protected]("mutation", _PREEXISTING_GAP_MUTATIONS)+def test_guards_ignore_a_preexisting_unrelated_interruption(tmp_path, mutation):+ """Only interruptions a mutation introduces need confirmation."""+ first = _source("src_gap00001", (_GAP_MENU_MODEL,), vendor="custom")+ first.base_url = "https://old-relay.example/v1"+ first.models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))+ second = _source("src_gap00002", (_GAP_MENU_MODEL,))+ unused = _source("src_gap00003", ("unused-model",))+ broken = _source("src_gap00004", ("other-model",), status="cooldown")+ broken.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",+ )+ config = _config([first, second], model=_GAP_MENU_MODEL)+ config.sources.extend((unused, broken))+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)+ )+ service, store, _ = _service(+ tmp_path, config, FakeAdapter(discovered=(_GAP_MENU_MODEL, "manual-model"))+ )+ before = store.load().to_payload()++ result = asyncio.run(_PREEXISTING_GAP_MUTATIONS[mutation](service))++ assert result.get("interrupted", []) == []+ assert result.get("removed_hops", []) == []+ assert store.load().to_payload() != before+ assert store.load().agents["claude"].routes["claude-sonnet-4-6"].hops == (+ ModelHubRouteHopConfig(broken.id, "other-model"),+ )def test_direct_mode_refuses_chain_and_probe(tmp_path):diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsxindex af388321c..b2af7543b 100644--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx@@ -1,8 +1,11 @@// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';import i18n from '@/i18n';import { modelsApi } from './modelsApi';import { RouteRecordedTurn } from './RouteRecordedTurn';@@ -18,6 +21,13 @@ const view = (modelId = 'requested-model') => <I18nextProvider i18n={i18n}><RoutafterEach(() => { cleanup(); vi.restoreAllMocks(); });describe('recorded turn error', () => {+ it('reads every contract version a released build persisted', () => {+ const schema = JSON.parse(readFileSync(resolve(+ dirname(fileURLToPath(import.meta.url)), '../../../../..', 'docs/plans/model-hub-contracts/turn-provenance.schema.json',+ ), 'utf8'));+ expect([...PERSISTED_TURN_CONTRACT_VERSIONS]).toEqual(schema.properties.contract_version.enum);+ expectTypeOf<TurnProvenance['contract_version']>().toEqualTypeOf<(typeof PERSISTED_TURN_CONTRACT_VERSIONS)[number]>();+ });it('renders exact historical identity and opens that same structured record', async () => {const user = userEvent.setup();vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(record);diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.tsindex 7248ad618..b39969194 100644--- a/ui/src/components/settings/models/sourceModelContract.test.ts+++ b/ui/src/components/settings/models/sourceModelContract.test.ts@@ -2,9 +2,10 @@ import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-import { describe, expect, it } from 'vitest';+import { describe, expect, expectTypeOf, it } from 'vitest';import { buildMockSources } from './mockData';+import { SOURCE_PROTOCOLS, type SourceProtocol } from './types';const SOURCE_SCHEMA = resolve(dirname(fileURLToPath(import.meta.url)),@@ -13,6 +14,12 @@ const SOURCE_SCHEMA = resolve();describe('Source model wire contract', () => {+ it('offers exactly the protocols the Source schema accepts', () => {+ const schema = JSON.parse(readFileSync(SOURCE_SCHEMA, 'utf8'));+ expect([...SOURCE_PROTOCOLS].sort()).toEqual([...schema.properties.protocol.enum].sort());+ expectTypeOf<SourceProtocol>().toEqualTypeOf<(typeof SOURCE_PROTOCOLS)[number]>();+ });+it('keeps typed fixtures aligned with every required model field and origin member', () => {const schema = JSON.parse(readFileSync(SOURCE_SCHEMA, 'utf8'));const modelSchema = schema.properties.models.items;