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
feat(model-hub): add repair paths and supply guards (#1093)
Call White4416f80ab049
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex e4a74ee35..5498aed14 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -12,7 +12,7 @@ import signalimport timeimport uuidfrom dataclasses import dataclass, field-from typing import Any, Optional+from typing import Any, Callable, Optionalfrom modules.claude_sdk_compat import (CLAUDE_SDK_AVAILABLE,@@ -1001,10 +1001,21 @@ class AgentAuthService:fallback_text = self._t("command.setup.claudeMethodFallback")await self._send_message_with_keyboard(context, text, keyboard, fallback_text=fallback_text)- async def _start_codex_process(self, *, force_reset: bool) -> asyncio.subprocess.Process:+ async def _start_codex_process(+ self,+ *,+ force_reset: bool,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> asyncio.subprocess.Process:binary = self._get_cli_binary("codex")if force_reset:- await self._run_utility_command(binary, "logout")+ await self._run_utility_command(+ binary,+ "logout",+ prepare_start=on_irreversible_start,+ )return await asyncio.create_subprocess_exec(binary,"login",@@ -1020,12 +1031,20 @@ class AgentAuthService:*,force_reset: bool,login_with_claude_ai: bool,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,) -> tuple[ClaudeSDKClient, str, ClaudeOAuthAttempt]:if not CLAUDE_SDK_AVAILABLE:raise ModuleNotFoundError("claude_agent_sdk is required for Claude setup flows")if force_reset:- await self._run_utility_command(self._get_cli_binary("claude"), "auth", "logout")+ await self._run_utility_command(+ self._get_cli_binary("claude"),+ "auth",+ "logout",+ prepare_start=on_irreversible_start,+ )# Claude Code re-applies ``settings.json`` env at startup, so an# OAuth flow must clear stale API-key settings before the control# client or follow-up probes launch.@@ -1209,14 +1228,23 @@ class AgentAuthService:self,*cmd: str,env: dict[str, str] | None = None,+ prepare_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,) -> tuple[bool, str | None]:"""Run a short CLI side-call. Returns ``(ok, error_excerpt)``.Callers that don't care about the outcome (setup preflight)can ignore the return; ``remove_web_auth`` uses it to surface``codex logout`` / ``claude auth logout`` failures so the UI- doesn't lie about a partial sign-out.+ doesn't lie about a partial sign-out. ``prepare_start`` persists+ pre-command state and may return a spawn-failure restoration."""+ restore_on_spawn_failure = (+ prepare_start()+ if prepare_start is not None+ else None+ )try:process = await asyncio.create_subprocess_exec(*cmd,@@ -1224,6 +1252,14 @@ class AgentAuthService:stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,)+ except Exception as err: # noqa: BLE001+ if restore_on_spawn_failure is not None:+ restore_on_spawn_failure()+ if prepare_start is not None:+ raise+ logger.info("Utility command raised for %s: %s", " ".join(cmd), err)+ return False, str(err)+ try:stdout, _ = await asyncio.wait_for(process.communicate(), timeout=20)if process.returncode == 0:return True, None@@ -1903,6 +1939,9 @@ class AgentAuthService:*,force_reset: bool = True,provider_id: Optional[str] = None,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,) -> WebAuthFlow:"""Start an OAuth flow initiated from the Settings page.@@ -1930,7 +1969,10 @@ class AgentAuthService:try:if backend == "codex":- flow.process = await self._start_codex_process(force_reset=force_reset)+ flow.process = await self._start_codex_process(+ force_reset=force_reset,+ on_irreversible_start=on_irreversible_start,+ )flow.reader_task = asyncio.create_task(self._read_codex_output_web(flow))flow.waiter_task = asyncio.create_task(self._wait_for_codex_completion_web(flow))elif backend == "claude":@@ -1938,6 +1980,7 @@ class AgentAuthService:context=None,force_reset=force_reset,login_with_claude_ai=True,+ on_irreversible_start=on_irreversible_start,)flow.claude_client = clientflow.claude_oauth_attempt = attemptdiff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.pyindex ef9ab25d8..ec3603f0e 100644--- a/core/handlers/model_hub/native_oauth.py+++ b/core/handlers/model_hub/native_oauth.py@@ -25,7 +25,15 @@ _MAX_FLOWS = 100class AgentAuthService(Protocol):setup_timeout_seconds: float- async def start_web_setup(self, backend: str, *, force_reset: bool = True) -> Any: ...+ async def start_web_setup(+ self,+ backend: str,+ *,+ force_reset: bool = True,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> Any: ...def get_web_flow_status(self, flow_id: str) -> dict[str, Any]: ...@@ -121,11 +129,47 @@ class AgentAuthNativeOAuthAdapter:self._flows: dict[str, _FlowBinding] = {}async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:+ return await self._start_oauth(+ source_id,+ vendor,+ force_reset=False,+ )++ async def start_reauth(+ self,+ source_id: str,+ vendor: str,+ *,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> OAuthFlowState:+ return await self._start_oauth(+ source_id,+ vendor,+ force_reset=True,+ on_irreversible_start=on_irreversible_start,+ )++ async def _start_oauth(+ self,+ source_id: str,+ vendor: str,+ *,+ force_reset: bool,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> OAuthFlowState:backend = _VENDOR_BACKENDS.get(vendor)if backend is None:raise NativeOAuthUnavailableError- flow = await self._agent_auth_service.start_web_setup(backend, force_reset=False)+ flow = await self._agent_auth_service.start_web_setup(+ backend,+ force_reset=force_reset,+ on_irreversible_start=on_irreversible_start,+ )flow_id = getattr(flow, "flow_id", None)if not isinstance(flow_id, str) or not flow_id:raise NativeOAuthUnavailableErrordiff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex 171bcaf37..5e20cea71 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -8,7 +8,7 @@ import tempfileimport threadingfrom dataclasses import dataclassfrom pathlib import Path-from typing import Literal, Optional, Protocol+from typing import Callable, Literal, Optional, Protocolfrom .adapter import OAuthFlowState@@ -22,7 +22,10 @@ class OAuthFlowBinding:source_id: Optional[str]vendor: Optional[str]experimental_consent: bool = False+ intent: Literal["create", "reauth"] = "create"completed: bool = False+ recovered: bool | None = None+ interrupted_pairs: tuple[dict[str, object], ...] = ()class OAuthAdapter(Protocol):@@ -44,6 +47,16 @@ class NativeOAuthSourceStatus:class NativeOAuthAdapter(OAuthAdapter, Protocol):+ async def start_reauth(+ self,+ source_id: str,+ vendor: str,+ *,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> OAuthFlowState: ...+def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus: ...@@ -57,6 +70,17 @@ class UnavailableNativeOAuthAdapter:async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:raise NativeOAuthUnavailableError+ async def start_reauth(+ self,+ source_id: str,+ vendor: str,+ *,+ on_irreversible_start: Callable[+ [], Callable[[], None] | None+ ] | None = None,+ ) -> OAuthFlowState:+ raise NativeOAuthUnavailableError+async def oauth_status(self, flow_id: str) -> OAuthFlowState:raise NativeOAuthUnavailableError@@ -100,20 +124,30 @@ class OAuthFlowRegistry:source_id = value.get("source_id")vendor = value.get("vendor")experimental_consent = value.get("experimental_consent", False)+ intent = value.get("intent", "create")completed = value.get("completed", False)+ recovered = value.get("recovered")+ interrupted_pairs = value.get("interrupted_pairs", [])if (channel in {"native_cli", "hub"}and (source_id is None or (isinstance(source_id, str) and source_id))and (vendor is None or (isinstance(vendor, str) and vendor))and isinstance(experimental_consent, bool)+ and intent in {"create", "reauth"}and isinstance(completed, bool)+ and (recovered is None or isinstance(recovered, bool))+ and isinstance(interrupted_pairs, list)+ and all(isinstance(item, dict) for item in interrupted_pairs)):flows[flow_id] = OAuthFlowBinding(- channel,- source_id,- vendor,- experimental_consent,- completed,+ channel=channel,+ source_id=source_id,+ vendor=vendor,+ experimental_consent=experimental_consent,+ intent=intent,+ completed=completed,+ recovered=recovered,+ interrupted_pairs=tuple(interrupted_pairs),)return flows@@ -127,7 +161,10 @@ class OAuthFlowRegistry:"source_id": binding.source_id,"vendor": binding.vendor,"experimental_consent": binding.experimental_consent,+ "intent": binding.intent,"completed": binding.completed,+ "recovered": binding.recovered,+ "interrupted_pairs": list(binding.interrupted_pairs),}for flow_id, binding in bounded.items()},@@ -150,30 +187,46 @@ class OAuthFlowRegistry:vendor: str,*,experimental_consent: bool = False,+ intent: Literal["create", "reauth"] = "create",+ recovered: bool | None = None,+ replace_flow_id: str | None = None,) -> None:with self._lock:flows = self._read()+ if replace_flow_id is not None:+ flows.pop(replace_flow_id, None)flows.pop(flow_id, None)flows[flow_id] = OAuthFlowBinding(- channel,- source_id,- vendor,- experimental_consent,+ channel=channel,+ source_id=source_id,+ vendor=vendor,+ experimental_consent=experimental_consent,+ intent=intent,+ recovered=recovered,)self._write(flows)- def complete(self, flow_id: str) -> None:+ def complete(+ self,+ flow_id: str,+ *,+ recovered: bool | None = None,+ interrupted_pairs: list[dict[str, object]] | None = None,+ ) -> None:with self._lock:flows = self._read()binding = flows.get(flow_id)if binding is None:raise KeyError(flow_id)flows[flow_id] = OAuthFlowBinding(- binding.channel,- binding.source_id,- binding.vendor,- binding.experimental_consent,- True,+ channel=binding.channel,+ source_id=binding.source_id,+ vendor=binding.vendor,+ experimental_consent=binding.experimental_consent,+ intent=binding.intent,+ completed=True,+ recovered=recovered,+ interrupted_pairs=tuple(interrupted_pairs or ()),)self._write(flows)@@ -185,6 +238,21 @@ class OAuthFlowRegistry:with self._lock:return self._read().get(flow_id)+ def pending_reauth(+ self,+ source_id: str,+ ) -> tuple[str, OAuthFlowBinding] | None:+ with self._lock:+ flows = self._read()+ for flow_id, binding in reversed(tuple(flows.items())):+ if (+ binding.source_id == source_id+ and binding.intent == "reauth"+ and not binding.completed+ ):+ return flow_id, binding+ return None+def forget(self, flow_id: str) -> None:with self._lock:flows = self._read()diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.pyindex dee985d96..1740d23cc 100644--- a/core/handlers/model_hub/revocations.py+++ b/core/handlers/model_hub/revocations.py@@ -60,14 +60,26 @@ class CredentialRevocationJournal:def add(self, source_id: str, credential_ref: str) -> None:with self._lock:- entries = [entry for entry in self._read() if entry.source_id != source_id]- entries.append(PendingCredentialRevocation(source_id, credential_ref))- self._write(entries)+ entries = self._read()+ entry = PendingCredentialRevocation(source_id, credential_ref)+ if entry not in entries:+ entries.append(entry)+ self._write(entries)- def remove(self, source_id: str) -> None:+ def remove(self, source_id: str, credential_ref: str | None = None) -> None:with self._lock:entries = self._read()- remaining = [entry for entry in entries if entry.source_id != source_id]+ remaining = [+ entry+ for entry in entries+ if not (+ entry.source_id == source_id+ and (+ credential_ref is None+ or entry.credential_ref == credential_ref+ )+ )+ ]if len(remaining) != len(entries):self._write(remaining)diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 6333f7672..8f71738bf 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -18,6 +18,16 @@ async def dispatch_model_hub_rpc(return await service.create_source(payload.get("source"))if operation == "patch_source":return await service.patch_source(payload.get("source_id"), payload.get("patch"))+ if operation == "replace_credential":+ return await service.replace_credential(+ payload.get("source_id"),+ payload.get("credential"),+ )+ if operation == "reauth_source":+ return await service.reauth_source(+ payload.get("source_id"),+ payload.get("reauth"),+ )if operation == "delete_source":await service.delete_source(payload.get("source_id"), force=payload.get("force") is True)return Nonediff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 325557347..c48ce17b9 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -70,6 +70,7 @@ from .resolver import (BackendName,ModelHubTurnResolution,allowed_origins,+ normalize_opencode_requested_model,resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,@@ -105,12 +106,14 @@ class ModelHubError(Exception):*,status: int = 400,detail: Optional[str] = None,+ data: Optional[Mapping[str, Any]] = None,):detail_key = detail or f"modelHub.errors.{code}"super().__init__(detail_key)self.code = codeself.status = statusself.detail = detail_key+ self.data = dict(data or {})class EngineUnavailableError(RuntimeError):@@ -325,10 +328,15 @@ def _binding(source: ModelHubSourceConfig) -> SourceBinding:)-def _oauth_payload(flow: OAuthFlowState, *, channel: str) -> dict:+def _oauth_payload(+ flow: OAuthFlowState,+ *,+ channel: str,+ intent: Literal["create", "reauth"] = "create",+) -> dict:return {"flow_id": flow.flow_id,- "intent": "create",+ "intent": intent,"source_id": flow.source_id,"vendor": flow.vendor,"channel": channel,@@ -476,7 +484,15 @@ class ModelHubService:raise ModelHubError("engine_down", status=503) from Nonedef _bindings(self, config: ModelHubConfig) -> list[SourceBinding]:- return [_binding(source) for source in config.sources if source.supply_channel == "hub"]+ return [+ _binding(source)+ for source in config.sources+ if source.supply_channel == "hub"+ and (+ source.models+ or source.state.status not in {"needs_action", "error"}+ )+ ]@staticmethoddef _clone_config(config: ModelHubConfig) -> ModelHubConfig:@@ -484,7 +500,10 @@ class ModelHubService:async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:bindings = self._bindings(config)- if not bindings and not force_empty:+ has_hub_sources = any(+ source.supply_channel == "hub" for source in config.sources+ )+ if not bindings and not force_empty and not has_hub_sources:returnawait self._engine_call(self.adapter.sync_sources(bindings))@@ -518,14 +537,43 @@ class ModelHubService:returnconfig = self.store.load()await self._sync_sources(config, force_empty=bool(pending_revocations))- active_source_ids = {source.id for source in config.sources}+ self._engine_synced = True+ active_credentials = {+ source.id: source.credential_ref for source in config.sources+ }for pending in pending_revocations:- if pending.source_id in active_source_ids:- self.revocations.remove(pending.source_id)+ if active_credentials.get(pending.source_id) == pending.credential_ref:+ try:+ self.revocations.remove(+ pending.source_id,+ pending.credential_ref,+ )+ except OSError:+ passcontinue- await self._engine_call(self.adapter.revoke_credential(pending.credential_ref))- self.revocations.remove(pending.source_id)- self._engine_synced = True+ try:+ await self.adapter.revoke_credential(pending.credential_ref)+ except Exception as error:+ if not self._credential_was_already_revoked(error):+ continue+ try:+ self.revocations.remove(+ pending.source_id,+ pending.credential_ref,+ )+ except OSError:+ pass++ @staticmethod+ def _credential_was_already_revoked(error: Exception) -> bool:+ # The frozen adapter surface has no typed not-found result. Match the+ # concrete runtime's closed error here so replay remains idempotent.+ from vibe.model_hub_runtime.state import EngineStateError++ return (+ isinstance(error, EngineStateError)+ and str(error) == "credential is unavailable"+ )def _oauth_adapter(self, channel: OAuthChannel) -> OAuthAdapter:if channel == "hub":@@ -569,17 +617,64 @@ class ModelHubService:logger.warning("Failed to persist Model Hub resolution event")async def _rollback_credential(self, source_id: str, credential_ref: str) -> None:- self.revocations.add(source_id, credential_ref)+ journaled = False+ try:+ self.revocations.add(source_id, credential_ref)+ except OSError:+ pass+ else:+ journaled = Truetry:await self.adapter.revoke_credential(credential_ref)except Exception:return+ if not journaled:+ returntry:- self.revocations.remove(source_id)+ self.revocations.remove(source_id, credential_ref)except OSError:# A replayed revoke is safer than losing the only durable ref.pass+ async def _rollback_replacement(+ self,+ source_id: str,+ replacement_ref: str,+ old_credential_ref: str | None,+ *,+ old_revocation_recorded: bool,+ ) -> None:+ if old_revocation_recorded and old_credential_ref:+ try:+ self.revocations.remove(source_id, old_credential_ref)+ except OSError:+ pass+ if replacement_ref != old_credential_ref:+ await self._rollback_credential(source_id, replacement_ref)++ def _mark_same_handle_reauth_needs_action(self, source_id: str) -> None:+ # The engine may replace OAuth material behind the same opaque ref.+ # Without an old snapshot, fail closed instead of restoring stale supply.+ config = self._clone_config(self.store.load())+ source = self._source(config, source_id)+ source.models = [+ model for model in source.models if model.provenance == "manual"+ ]+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ )+ self.store.save(config)++ async def _discard_unbound_hub_flow(self, flow: OAuthFlowState) -> None:+ if flow.credential_ref:+ await self._rollback_credential(flow.source_id, flow.credential_ref)+ return+ try:+ await self.adapter.cancel_oauth(flow.flow_id)+ except Exception:+ pass+def _raise_if_flow_expired(self, flow_id: str, flow: OAuthFlowState) -> None:if not flow.expires_at_iso or flow.state in {"success", "failed", "cancelled"}:return@@ -597,13 +692,13 @@ class ModelHubService:manual_models: list[ModelHubModelConfig],discovered: list[str],) -> None:- if any(+ if (not discovered and not manual_models) or any(not isinstance(model_id, str)or not model_idor contains_credential_material(model_id)for model_id in discovered):- raise ModelHubError("discovery_failed")+ raise ModelHubError("discovery_failed", status=502)discovered_at = self.now().isoformat()manual_model_ids = {model.id for model in manual_models}source.models = [@@ -776,6 +871,8 @@ class ModelHubService:binding: OAuthFlowBinding,) -> OAuthFlowState | None:source = self._completed_oauth_source(binding)+ if binding.intent == "reauth" and not binding.completed:+ return Noneif source is None:if binding.completed:try:@@ -789,7 +886,7 @@ class ModelHubService:self.oauth_flows.complete(flow_id)except (KeyError, OSError):pass- failed = source.state.status == "error"+ failed = binding.intent == "create" and source.state.status == "error"return OAuthFlowState(flow_id=flow_id,source_id=source.id,@@ -808,16 +905,290 @@ class ModelHubService:credential_ref=source.credential_ref,)+ def _completed_reauth_result(+ self,+ binding: OAuthFlowBinding,+ ) -> dict | None:+ if not binding.completed:+ return None+ source = self._completed_oauth_source(binding)+ if source is None:+ raise ModelHubError("flow_not_found", status=404)+ return {+ "source": source.to_payload(),+ "recovered": binding.recovered is True,+ "interrupted_pairs": list(binding.interrupted_pairs),+ }++ async def _mark_native_reauth_unavailable(+ self,+ source_id: str,+ *,+ status: Literal["needs_action", "error"],+ ) -> list[dict]:+ async with self._mutation_lock:+ config = self.store.load()+ source = self._source(config, source_id)+ source.models = [+ model for model in source.models if model.provenance == "manual"+ ]+ source.account_label = None+ source.state = ModelHubSourceStateConfig(+ status=status,+ detail_key=(+ "models.source.needs_action.oauth_expired"+ if status == "needs_action"+ else "models.source.error.unclassified"+ ),+ )+ self.store.save(config)+ return self._would_interrupt(config)++ async def _materialize_reauth(+ self,+ flow_id: str,+ binding: OAuthFlowBinding,+ flow: OAuthFlowState,+ ) -> dict:+ if binding.source_id is None or binding.vendor is None:+ raise ModelHubError("flow_not_found", status=404)++ if binding.channel == "native_cli":+ try:+ source_status = self.native_oauth_adapter.completed_source_status(+ flow_id+ )+ except KeyError:+ raise ModelHubError("flow_not_found", status=404) from None+ except Exception:+ interrupted_pairs = await self._mark_native_reauth_unavailable(+ binding.source_id,+ status="error",+ )+ raise ModelHubError(+ "discovery_failed",+ status=502,+ data={"interrupted_pairs": interrupted_pairs},+ ) from None++ async with self._mutation_lock:+ binding = self._oauth_binding(flow_id)+ completed = self._completed_reauth_result(binding)+ if completed is not None:+ return completed+ config = self.store.load()+ source = self._source(config, binding.source_id)+ if not self._source_matches_binding(source, binding):+ raise ModelHubError("flow_not_found", status=404)+ source.account_label = source_status.account_label+ source.state = (+ ModelHubSourceStateConfig(status="standby")+ if source_status.signed_in+ else ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ )+ )+ manual = [+ model for model in source.models if model.provenance == "manual"+ ]+ discovered = list(_native_model_ids(binding.vendor))+ if not discovered:+ source.models = []+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )+ self.store.save(config)+ interrupted_pairs = self._would_interrupt(config)+ raise ModelHubError(+ "discovery_failed",+ status=502,+ data={"interrupted_pairs": interrupted_pairs},+ )+ self._apply_discovered_models(source, manual, discovered)+ self.store.save(config)+ interrupted_pairs = self._would_interrupt(config)+ self._complete_reauth_flow(+ flow_id,+ binding,+ interrupted_pairs,+ )+ return {+ "source": source.to_payload(),+ "recovered": binding.recovered is True,+ "interrupted_pairs": interrupted_pairs,+ }++ if not flow.credential_ref:+ raise ModelHubError("flow_not_found", status=404)+ replacement_ref = flow.credential_ref+ async with self._mutation_lock:+ binding = self._oauth_binding(flow_id)+ completed = self._completed_reauth_result(binding)+ if completed is not None:+ return completed+ source: ModelHubSourceConfig | None = None+ old_credential_ref: str | None = None+ committed = False+ old_revocation_recorded = False+ try:+ previous = self.store.load()+ config = self._clone_config(previous)+ source = self._source(config, binding.source_id)+ old_credential_ref = source.credential_ref+ if not self._source_matches_binding(source, binding):+ raise ModelHubError("flow_not_found", status=404)+ manual = [+ model+ for model in source.models+ if model.provenance == "manual"+ ]+ source.credential_ref = replacement_ref+ discovered = await self._discover(source)+ self._apply_discovered_models(source, manual, discovered)+ source.state = ModelHubSourceStateConfig(status="standby")+ interrupted_pairs = self._would_interrupt(config)+ if (+ old_credential_ref+ and old_credential_ref != replacement_ref+ ):+ self.revocations.add(source.id, old_credential_ref)+ old_revocation_recorded = True+ await self._commit_synced(previous, config)+ committed = True+ self._complete_reauth_flow(+ flow_id,+ binding,+ interrupted_pairs,+ )+ except Exception:+ if not committed:+ try:+ if source is None:+ await self._rollback_credential(+ binding.source_id,+ replacement_ref,+ )+ elif replacement_ref == old_credential_ref:+ self._mark_same_handle_reauth_needs_action(source.id)+ else:+ await self._rollback_replacement(+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ finally:+ try:+ self.oauth_flows.forget(flow_id)+ except OSError:+ pass+ raise++ if old_credential_ref and old_credential_ref != replacement_ref:+ try:+ await self.adapter.revoke_credential(old_credential_ref)+ except Exception:+ pass+ else:+ try:+ self.revocations.remove(+ binding.source_id,+ old_credential_ref,+ )+ except OSError:+ pass+ return {+ "source": source.to_payload(),+ "recovered": binding.recovered is True,+ "interrupted_pairs": interrupted_pairs,+ }++ def _complete_reauth_flow(+ self,+ flow_id: str,+ binding: OAuthFlowBinding,+ interrupted_pairs: list[dict],+ ) -> None:+ try:+ self.oauth_flows.complete(+ flow_id,+ recovered=binding.recovered is True,+ interrupted_pairs=interrupted_pairs,+ )+ except KeyError:+ try:+ self.oauth_flows.remember(+ flow_id,+ binding.channel,+ binding.source_id,+ binding.vendor,+ experimental_consent=binding.experimental_consent,+ intent="reauth",+ recovered=binding.recovered,+ )+ self.oauth_flows.complete(+ flow_id,+ recovered=binding.recovered is True,+ interrupted_pairs=interrupted_pairs,+ )+ except (KeyError, OSError):+ pass+ except OSError:+ pass++ def _fail_closed_hub_reauth(+ self,+ binding: OAuthFlowBinding,+ *,+ config: ModelHubConfig | None = None,+ ) -> ModelHubConfig:+ config = config or self.store.load()+ if binding.source_id is None:+ raise ModelHubError("flow_not_found", status=404)+ source = self._source(config, binding.source_id)+ if not self._source_matches_binding(source, binding):+ raise ModelHubError("flow_not_found", status=404)+ source.models = [+ model+ for model in source.models+ if model.provenance == "manual"+ ]+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ )+ self.store.save(config)+ return config+async def _materialize_completed_oauth(self,flow_id: str,binding: OAuthFlowBinding,flow: OAuthFlowState,- ) -> OAuthFlowState:+ ) -> tuple[OAuthFlowState, dict | None]:if flow.state != "success":- return flow+ if (+ flow.state == "failed"+ and binding.intent == "reauth"+ and binding.channel == "hub"+ and binding.source_id is not None+ ):+ async with self._mutation_lock:+ # error_key is presentation-only until the owner-ruled+ # retained-material discriminator lands.+ self._fail_closed_hub_reauth(binding)+ return flow, Noneif binding.source_id is None or binding.vendor is None:raise ModelHubError("flow_not_found", status=404)+ if binding.intent == "reauth":+ repair_result = await self._materialize_reauth(+ flow_id,+ binding,+ flow,+ )+ return flow, repair_resultif binding.channel == "hub" and not binding.experimental_consent:raise ModelHubError("consent_required", status=409)@@ -853,7 +1224,7 @@ class ModelHubService:completed = self._completed_oauth_flow(flow_id, binding)if completed is None:raise ModelHubError("flow_not_found", status=404)- return completed+ return completed, Nonedef list_sources(self) -> list[dict]:config = self.store.load()@@ -987,6 +1358,97 @@ class ModelHubService:await self._rollback_credential(source.id, rollback_credential_ref)raise+ async def replace_credential(self, source_id: str, payload: object) -> dict:+ if (+ not isinstance(payload, dict)+ or set(payload) - {"key", "force"}+ or set(payload) < {"key"}+ or not isinstance(payload.get("key"), str)+ or not str(payload["key"]).strip()+ or (+ "force" in payload+ and not isinstance(payload.get("force"), bool)+ )+ ):+ raise ModelHubError("discovery_failed")++ key = str(payload["key"]).strip()+ force = payload.get("force") is True+ async with self._mutation_lock:+ previous = self.store.load()+ config = self._clone_config(previous)+ source = self._source(config, source_id)+ if (+ source.kind != "api_key"+ or source.supply_channel != "hub"+ or not source.credential_ref+ ):+ raise ModelHubError("discovery_failed")++ old_credential_ref = source.credential_ref+ replacement_ref = await self._engine_call(+ self.adapter.provision_credential(+ source.vendor,+ source.protocol,+ key,+ source.base_url,+ )+ )+ committed = False+ old_revocation_recorded = False+ try:+ source.credential_ref = replacement_ref+ source.masked_credential = _mask_credential(key)+ manual = [+ model for model in source.models if model.provenance == "manual"+ ]+ discovered = await self._discover(source)+ self._apply_discovered_models(source, manual, discovered)+ source.state = ModelHubSourceStateConfig(status="standby")++ interrupted_pairs = self._would_interrupt(config)+ recovered = self._source(+ previous,+ source_id,+ ).state.status in {"needs_action", "error"}+ if interrupted_pairs and not recovered and not force:+ raise ModelHubError(+ "source_last_supplier",+ status=409,+ data={"would_interrupt": interrupted_pairs},+ )++ if old_credential_ref != replacement_ref:+ self.revocations.add(source.id, old_credential_ref)+ old_revocation_recorded = True+ await self._commit_synced(previous, config)+ committed = True+ except Exception:+ if not committed:+ await self._rollback_replacement(+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ raise++ if old_credential_ref != replacement_ref:+ try:+ await self.adapter.revoke_credential(old_credential_ref)+ except Exception:+ pass+ else:+ try:+ self.revocations.remove(source.id, old_credential_ref)+ except OSError:+ pass+ return {+ "source": source.to_payload(),+ "recovered": recovered,+ "interrupted_pairs": interrupted_pairs,+ }+async def patch_source(self, source_id: str, payload: dict) -> dict:if not isinstance(payload, dict) or set(payload) - {"display_name", "base_url"}:raise ModelHubError("discovery_failed")@@ -1057,27 +1519,95 @@ class ModelHubService:return Truereturn False- def _only_selected_supplier(self, config: ModelHubConfig, source: ModelHubSourceConfig) -> bool:- return any(self._only_selected_model_supplier(config, source, model.id) for model in source.models)+ def _protected_menu_models(+ self,+ config: ModelHubConfig,+ backend: BackendName,+ ) -> dict[str, list[str]]:+ agent = config.agents[backend]+ if agent.mode != "hub":+ return {}++ protected: dict[str, list[str]] = {}++ def add(model_id: object, named_agent: str | None = None) -> None:+ normalized = str(model_id or "").strip()+ if not normalized:+ return+ if backend == "opencode" and agent.menu is not None:+ normalized = (+ normalize_opencode_requested_model(+ normalized,+ tuple(agent.menu.checked),+ )+ or normalized+ )+ names = protected.setdefault(normalized, [])+ if named_agent is not None and named_agent not in names:+ names.append(named_agent)++ default_model = self._backend_default_model(backend)+ add(default_model)+ if self.named_agents_override is not None:+ for name, pinned_model in self.named_agents_override(backend):+ add(str(pinned_model or "").strip() or default_model, name)+ if agent.menu_kind == "open" and agent.menu is not None:+ for identifier in agent.menu.checked:+ add(identifier)+ else:+ for mapping in agent.mappings:+ if mapping.enabled:+ add(mapping.builtin_id)+ return protected++ def _would_interrupt(self, config: ModelHubConfig) -> list[dict]:+ gaps: list[dict] = []+ for backend_name in MODEL_HUB_BACKENDS:+ backend = cast(BackendName, backend_name)+ unavailable_source_ids = self._unavailable_native_sources(config, backend)+ for model_id, agents in self._protected_menu_models(config, backend).items():+ resolution = resolve_model_hub_turn(+ config,+ backend,+ model_id,+ now=self.now(),+ unavailable_source_ids=unavailable_source_ids,+ )+ if resolution.candidates:+ continue+ gaps.append(+ {+ "backend": backend,+ "model_id": model_id,+ "agents": agents,+ }+ )+ return gapsasync def delete_source(self, source_id: str, *, force: bool = False) -> None:async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, source_id)- if not force and self._only_selected_supplier(config, source):- raise ModelHubError("mode_switch_blocked", status=409)config.sources = [item for item in config.sources if item.id != source_id]for agent in config.agents.values():agent.sources.order = [item for item in agent.sources.order if item != source_id]config.refresh_follow_orders()+ would_interrupt = self._would_interrupt(config)+ if would_interrupt and not force:+ raise ModelHubError(+ "source_last_supplier",+ status=409,+ data={"would_interrupt": would_interrupt},+ )self._prune_unavailable_agent_references(config)if source.credential_ref:self.revocations.add(source.id, source.credential_ref)try:await self._commit_synced(previous, config)except Exception:- self.revocations.remove(source.id)+ if source.credential_ref:+ self.revocations.remove(source.id, source.credential_ref)raisetry:if source.credential_ref:@@ -1092,9 +1622,13 @@ class ModelHubService:self._engine_synced = Truefinally:if restored:- self.revocations.remove(source.id)+ self.revocations.remove(+ source.id,+ source.credential_ref,+ )raise- self.revocations.remove(source.id)+ if source.credential_ref:+ self.revocations.remove(source.id, source.credential_ref)async def test_source(self, source_id: str) -> tuple[dict, int]:async with self._mutation_lock:@@ -1103,9 +1637,23 @@ class ModelHubService:source = self._source(config, source_id)if source.supply_channel == "native_cli":raise ModelHubError("discovery_failed")- model_ids = await self._discover(source)- manual = [model for model in source.models if model.provenance == "manual"]- self._apply_discovered_models(source, manual, model_ids)+ try:+ model_ids = await self._discover(source)+ manual = [+ model+ for model in source.models+ if model.provenance == "manual"+ ]+ self._apply_discovered_models(source, manual, model_ids)+ except ModelHubError as exc:+ if exc.code != "discovery_failed":+ raise+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )+ self.store.save(config)+ raisesource.state = ModelHubSourceStateConfig(status="standby")await self._commit_synced(previous, config)return source.to_payload(), len(model_ids)@@ -1131,10 +1679,30 @@ class ModelHubService:}@staticmethod- def _invalid_source_order(detail: object = None) -> ModelHubError:+ def _invalid_source_order(+ *,+ rejected_keys: list[str] | None = None,+ ) -> ModelHubError:+ safe_rejected = []+ for key in rejected_keys or []:+ safe_rejected.append(+ key+ if (+ 0 < len(key) <= 64+ and key.isascii()+ and key[0].isalpha()+ and all(character.isalnum() or character == "_" for character in key)+ and not contains_credential_material(key)+ )+ else "[redacted]"+ )return ModelHubError("invalid_source_order",- detail=str(detail) if isinstance(detail, str) and detail else None,+ data=(+ {"rejected_keys": safe_rejected}+ if safe_rejected+ else None+ ),)async def set_agent_sources(self, backend: str, payload: object) -> dict:@@ -1143,9 +1711,17 @@ class ModelHubService:policy = payload.get("policy")if policy == "follow":if set(payload) != {"policy"}:- raise self._invalid_source_order()+ rejected = sorted(set(payload) - {"policy"})+ raise self._invalid_source_order(+ rejected_keys=rejected,+ )elif policy == "custom":if set(payload) != {"policy", "order"}:+ rejected = sorted(set(payload) - {"policy", "order"})+ if rejected:+ raise self._invalid_source_order(+ rejected_keys=rejected,+ )raise self._invalid_source_order()else:raise self._invalid_source_order()@@ -1170,7 +1746,7 @@ class ModelHubService:or source_id not in by_idor not self._eligible_for_agent(by_id[source_id], backend)):- raise self._invalid_source_order(source_id)+ raise self._invalid_source_order()seen.add(source_id)agent.sources.policy = "custom"agent.sources.order = list(order)@@ -1418,6 +1994,145 @@ class ModelHubService:def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:return self.events.list(limit=limit, before=before)+ async def reauth_source(self, source_id: str, payload: object) -> dict:+ if (+ not isinstance(payload, dict)+ or set(payload) - {"acknowledge_irreversible"}+ or (+ "acknowledge_irreversible" in payload+ and payload.get("acknowledge_irreversible") is not True+ )+ ):+ raise ModelHubError("reauth_confirmation_required", status=409)++ async with self._mutation_lock:+ config = self.store.load()+ source = self._source(config, source_id)+ if source.kind != "subscription":+ raise ModelHubError("discovery_failed")+ if (+ source.supply_channel == "native_cli"+ and payload.get("acknowledge_irreversible") is not True+ ):+ raise ModelHubError("reauth_confirmation_required", status=409)++ replace_pending_flow_id: str | None = None+ pending = self.oauth_flows.pending_reauth(source.id)+ if pending is not None:+ pending_flow_id, pending_binding = pending+ try:+ pending_flow = await self._oauth_status(+ pending_flow_id,+ pending_binding.channel,+ )+ self._raise_if_flow_expired(pending_flow_id, pending_flow)+ except ModelHubError as error:+ # Hub OAuth flow state is process-local. After a controller+ # restart, its unknown-flow error reaches L2 as engine_down.+ if (+ error.code == "engine_down"+ and pending_binding.channel == "hub"+ ):+ replace_pending_flow_id = pending_flow_id+ elif error.code not in {"flow_expired", "flow_not_found"}:+ raise+ else:+ if pending_flow.state not in {"failed", "cancelled"}:+ return {+ "flow": _oauth_payload(+ pending_flow,+ channel=pending_binding.channel,+ intent="reauth",+ )+ }+ if (+ pending_flow.state == "failed"+ and pending_binding.channel == "hub"+ ):+ config = self._fail_closed_hub_reauth(+ pending_binding,+ config=config,+ )+ source = self._source(config, source_id)+ try:+ self.oauth_flows.forget(pending_flow_id)+ except OSError:+ raise ModelHubError("engine_down", status=503) from None++ channel = cast(OAuthChannel, source.supply_channel)+ oauth_adapter = self._oauth_adapter(channel)+ recovered = source.state.status in {"needs_action", "error"}++ def mark_native_irreversible_start() -> Callable[[], None]:+ previous = self._clone_config(config)+ affected_backend = _NATIVE_VENDOR_BACKENDS[source.vendor]+ for candidate in config.sources:+ if (+ candidate.supply_channel != "native_cli"+ or _NATIVE_VENDOR_BACKENDS.get(candidate.vendor)+ != affected_backend+ ):+ continue+ candidate.models = [+ model+ for model in candidate.models+ if model.provenance == "manual"+ ]+ candidate.account_label = None+ candidate.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ )+ self.store.save(config)++ def restore_after_spawn_failure() -> None:+ self.store.save(previous)++ return restore_after_spawn_failure++ flow = await self._oauth_call(+ (+ self.native_oauth_adapter.start_reauth(+ source.id,+ source.vendor,+ on_irreversible_start=mark_native_irreversible_start,+ )+ if channel == "native_cli"+ else oauth_adapter.start_oauth(source.id, source.vendor)+ )+ )+ if flow.source_id != source.id or flow.vendor != source.vendor:+ if channel == "hub":+ await self._discard_unbound_hub_flow(flow)+ raise ModelHubError("flow_not_found", status=502)+ try:+ self.oauth_flows.remember(+ flow.flow_id,+ channel,+ source.id,+ source.vendor,+ experimental_consent=source.experimental_consent_at is not None,+ intent="reauth",+ recovered=recovered,+ replace_flow_id=replace_pending_flow_id,+ )+ except OSError:+ if channel == "hub":+ await self._discard_unbound_hub_flow(flow)+ else:+ try:+ await self.native_oauth_adapter.cancel_oauth(flow.flow_id)+ except Exception:+ pass+ raise ModelHubError("engine_down", status=503) from None+ return {+ "flow": _oauth_payload(+ flow,+ channel=channel,+ intent="reauth",+ )+ }+async def oauth_start(self, payload: dict) -> dict:vendor = payload.get("vendor") if isinstance(payload, dict) else Nonechannel = payload.get("channel") if isinstance(payload, dict) else None@@ -1458,14 +2173,29 @@ class ModelHubService:*,channel: OAuthChannel,) -> dict:- result = {"flow": _oauth_payload(flow, channel=channel)}+ binding = self._oauth_binding(flow_id)+ result = {+ "flow": _oauth_payload(+ flow,+ channel=channel,+ intent=binding.intent,+ )+ }if flow.state != "success":return result- binding = self._oauth_binding(flow_id)source = self._completed_oauth_source(binding)if source is None:raise ModelHubError("flow_not_found", status=404)- result.update(self._source_creation_result(source.to_payload()))+ if binding.intent == "reauth":+ result.update(+ {+ "source": source.to_payload(),+ "recovered": binding.recovered is True,+ "interrupted_pairs": list(binding.interrupted_pairs),+ }+ )+ else:+ result.update(self._source_creation_result(source.to_payload()))return resultasync def oauth_status(self, flow_id: str) -> dict:@@ -1479,7 +2209,20 @@ class ModelHubService:)flow = await self._oauth_status(flow_id, binding.channel)self._raise_if_flow_expired(flow_id, flow)- flow = await self._materialize_completed_oauth(flow_id, binding, flow)+ flow, repair_result = await self._materialize_completed_oauth(+ flow_id,+ binding,+ flow,+ )+ if repair_result is not None:+ return {+ "flow": _oauth_payload(+ flow,+ channel=binding.channel,+ intent="reauth",+ ),+ **repair_result,+ }return self._oauth_result(flow_id, flow, channel=binding.channel)async def oauth_submit(self, payload: dict) -> dict:@@ -1501,18 +2244,57 @@ class ModelHubService:self._oauth_adapter(binding.channel).submit_oauth(flow_id, value),flow_id=flow_id,)- flow = await self._materialize_completed_oauth(flow_id, binding, flow)+ flow, repair_result = await self._materialize_completed_oauth(+ flow_id,+ binding,+ flow,+ )+ if repair_result is not None:+ return {+ "flow": _oauth_payload(+ flow,+ channel=binding.channel,+ intent="reauth",+ ),+ **repair_result,+ }return self._oauth_result(flow_id, flow, channel=binding.channel)async def oauth_cancel(self, flow_id: object) -> None:if not isinstance(flow_id, str):raise ModelHubError("flow_not_found", status=404)- channel = self._oauth_channel(flow_id)- await self._oauth_call(- self._oauth_adapter(channel).cancel_oauth(flow_id),- flow_id=flow_id,- )- self.oauth_flows.forget(flow_id)+ terminal: tuple[OAuthFlowBinding, OAuthFlowState] | None = None+ async with self._mutation_lock:+ binding = self._oauth_binding(flow_id)+ completed = self._completed_oauth_flow(flow_id, binding)+ if completed is not None:+ return+ flow = await self._oauth_status(flow_id, binding.channel)+ self._raise_if_flow_expired(flow_id, flow)+ if flow.state == "success" or (+ flow.state == "failed"+ and binding.intent == "reauth"+ and binding.channel == "hub"+ ):+ terminal = (binding, flow)+ else:+ await self._oauth_call(+ self._oauth_adapter(binding.channel).cancel_oauth(flow_id),+ flow_id=flow_id,+ )+ self.oauth_flows.forget(flow_id)+ if terminal is not None:+ await self._materialize_completed_oauth(+ flow_id,+ terminal[0],+ terminal[1],+ )+ if terminal[1].state == "failed":+ async with self._mutation_lock:+ try:+ self.oauth_flows.forget(flow_id)+ except OSError:+ raise ModelHubError("engine_down", status=503) from Noneasync def runtime_status(self) -> dict:status = await self._engine_call(self.adapter.status())@@ -1661,6 +2443,15 @@ class ModelHubService:) -> ResolvedInvocation:if backend not in {"claude", "codex", "opencode"}:raise ModelHubError("mapping_target_unavailable")+ engine_prepared = False+ if self.revocations.list():+ try:+ await self._ensure_engine_synced()+ except ModelHubError:+ # Cleanup remains durable and must not invent a supply failure.+ pass+ else:+ engine_prepared = Trueconfig = self.store.load()resolution = resolve_model_hub_turn(config,@@ -1710,12 +2501,6 @@ class ModelHubService:failed_reason: Optional[EventReason] = Nonefor source in candidates:if source.supply_channel == "native_cli":- if self.revocations.list():- try:- await self._ensure_engine_synced()- except ModelHubError:- # Credential cleanup remains durable; native routing is independent.- passself._emit_switch(agent=event_agent,model_id=target_model,@@ -1730,7 +2515,8 @@ class ModelHubService:None,supply_channel="native_cli",)- await self._ensure_engine_synced()+ if not engine_prepared:+ await self._ensure_engine_synced()handle, outcome = await self._invoke(source=source,model_id=target_model,diff --git a/core/internal_server.py b/core/internal_server.pyindex 01cd3324a..92c4c2aca 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -590,6 +590,7 @@ def create_app(controller: "Controller") -> FastAPI:response = {"ok": False, "error": exc.code}if exc.detail:response["detail"] = exc.detail+ response.update(exc.data)return JSONResponse(status_code=exc.status, content=response)return {"ok": True, "result": result}diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 3fceb63f7..c45d330cc 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -79,6 +79,13 @@ order after any mutation; clients never compute partial reorders.`docs(model-hub): freeze interface contracts v3` and announces the commit SHAin every lane brief. From then on: lanes cite, never edit; changes go throughthe orchestrator and bump `contract_version`.+- **Targeted v4 process instance trail — entry 2 (v4b).** Following v4a commit+ `37285675`, the dedicated commit+ `docs(model-hub): scope hub OAuth reauth rollback invariant v4b` is+ orchestrator-authorized, evidence-pinned to review finding `3675168031` and+ `vibe/model_hub_runtime/state.py:135-166`, and owner-vetoable. It corrects only+ the hub-OAuth stable-ref repair invariant; chat messages alone did not unfreeze+ these files.- Contract tests (implementation plan §5) validate both directions againstthese schemas.diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 33bce00d4..1db26dedd 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -234,18 +234,30 @@ exists to repair.## Credential replacement and reauthThe commit point is the single durable write that makes the replacement source state-live. Implementations may sequence adapter calls differently only if all invariants-remain true:+live. Hub OAuth has an earlier credential-irreversibility boundary when new grant+material is written under its identity-bound stable ref; that boundary does not make+the replacement source state live. Implementations may sequence adapter calls+differently only if all invariants remain true:1. **Atomic source state.** Before the commit point, readers see the old source.After it, readers see the replacement credential reference, mask, discoveredmodels, and derived state together.-2. **Rollback before commit.** Any failure before commit preserves the old source and- revokes replacement engine material created by that attempt.+2. **Rollback before commit, scoped to what is preservable.** API-key replacement and+ any repair that receives a distinct replacement ref stay strict: every failure+ before commit preserves the old source and revokes replacement engine material+ created by that attempt. Hub-OAuth re-auth is the deliberate exception because the+ engine binds OAuth identity to a stable ref. Failures before new grant material is+ written under that ref still preserve everything. Once the write occurs, prior+ material is unrecoverable through the ref: a later failure MUST fail the request,+ clear discovered supply, and persist `state.status: needs_action` with+ `state.detail_key: models.source.needs_action.oauth_expired`. The key means the+ convergent remedy is OAuth re-auth; this state is never silently routed.3. **Guard before commit.** Elective API-key replacement evaluates the supply guardagainst the discovered replacement model set before the write.-4. **Per-channel truth.** Hub credentials are engine-owned and transactional.- Native credentials are CLI-owned and replacement is irreversible once login starts.+4. **Per-channel truth.** Hub API-key material is engine-owned and transactional.+ Hub OAuth material is engine-owned but identity-bound to a stable ref, so replacing+ its grant is irreversible once the new material is written. Native credentials are+ CLI-owned and replacement is likewise irreversible once login starts.5. **Server-enforced native acknowledgement.** For a `native_cli` source,`POST …/reauth` requires `{"acknowledge_irreversible": true}`. Missing or falsereturns `reauth_confirmation_required` before any OAuth adapter call. This isdiff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex e5af42403..11ca7c283 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -164,6 +164,7 @@],"properties": {"detail_key": {+ "$comment": "Targeted v4b (finding 3675168031): `models.source.needs_action.oauth_expired` is also the closed, existing classification for a hub-OAuth same-ref re-auth that wrote new grant material and then failed before the source-state commit. The truthful user-facing fact is that OAuth authentication must be re-established; this use does not claim a wall-clock token expiry. Evidence at master 807d1eee: vibe/model_hub_runtime/state.py:135-166 binds OAuth identity to a stable credential_ref and returns the existing ref on a match, so prior grant material cannot be restored after the rewrite. Deliberate non-goal: a two-ref transactional OAuth swap is REJECTED for v2 — the window is rare, the user is already mid-re-auth, one more re-auth is the convergent remedy, and the engine layer stays zero-change in this batch. Revisit only on field evidence.","enum": ["models.source.needs_action.oauth_expired","models.source.needs_action.balance_exhausted",@@ -228,7 +229,7 @@"string","null"],- "description": "i18n key, never raw upstream error text — and as of round 5 that is ENFORCED for every status rather than asserted for some (07-29). Each status closes its own vocabulary, so the union below is the complete set of values this field can ever hold and 'never raw text' is a property of the schema instead of a promise about emitters. For needs_action it names the cause so the row can offer one tap to fix it, and the four keys are required: models.source.needs_action.oauth_expired (re-auth), .balance_exhausted (top up), .credential_revoked (replace key), .account_banned (contact vendor). For cooldown it stays OPTIONAL — a cooling source is already fully described by its `retry_at`, so a cause is useful detail rather than a required one — but the five keys it may carry are now a closed enum, not a `models.source.cooldown.*` prefix: `.network`, `.timeout`, `.rate_limited`, `.quota_exhausted`, `.server_error`. Round 4 wrote that constraint as a prefix pattern with `.+`, which accepted `models.source.cooldown.network: <raw upstream body>` — a naming convention, not a redaction boundary. Null for the two healthy statuses. For `error` — the unclassified failure — the single generic key `models.source.error.unclassified` is REQUIRED: round 4 left this status unconstrained on the grounds that the cause is by definition unknown, which is exactly backwards, since the one status an adapter reaches when it cannot classify a failure is where a raw diagnostic is most likely to land. Not knowing the cause is not permission to widen the channel; the raw text belongs in scrubbed logs. That key is ALSO an event cause as of round 6 (`resolution-event.schema.json` → `reason: unclassified_error`), because a status that never lapses on a timer is a state the user has to be told about; the five non-self-healing keys and the five non-self-healing reasons are a bijection, checked mechanically (api.md → Mechanical guards). VOCABULARY HOME: this field owns these keys — all TEN of them, the five cooldown plus the four needs_action plus this one `error` key — and probe-result.schema.json → `error` mirrors them, because draft-07 gives a bare validator no cross-file `$ref`; the lists are compared mechanically ACROSS files (README.md → vocabulary mirror table, api.md → Serializer completeness). The `examples` list below is part of that comparison and not decoration: round 6 added the `error` key to the three enforcing branches and left `examples` at nine, so the field advertised a nine-key vocabulary while enforcing ten, and round 7 found it. Two things made that survivable and are now closed: this key is pinned as a `const` rather than a one-value `enum`, so a checker that collects only `enum` lists could not see it and its 'examples equal the enforced union' guard passed vacuously; and the comparison ran inside each file rather than between them. `const` now counts as an enum of cardinality one (07-29, review round 7).",+ "description": "i18n key, never raw upstream error text — and as of round 5 that is ENFORCED for every status rather than asserted for some (07-29). Each status closes its own vocabulary, so the union below is the complete set of values this field can ever hold and 'never raw text' is a property of the schema instead of a promise about emitters. For needs_action it names the cause or convergent remedy so the row can offer one tap to fix it, and the four keys are required: models.source.needs_action.oauth_expired (re-auth; also the v4b stable-ref rewrite failure whose only honest recovery is re-auth), .balance_exhausted (top up), .credential_revoked (replace key), .account_banned (contact vendor). For cooldown it stays OPTIONAL — a cooling source is already fully described by its `retry_at`, so a cause is useful detail rather than a required one — but the five keys it may carry are now a closed enum, not a `models.source.cooldown.*` prefix: `.network`, `.timeout`, `.rate_limited`, `.quota_exhausted`, `.server_error`. Round 4 wrote that constraint as a prefix pattern with `.+`, which accepted `models.source.cooldown.network: <raw upstream body>` — a naming convention, not a redaction boundary. Null for the two healthy statuses. For `error` — the unclassified failure — the single generic key `models.source.error.unclassified` is REQUIRED: round 4 left this status unconstrained on the grounds that the cause is by definition unknown, which is exactly backwards, since the one status an adapter reaches when it cannot classify a failure is where a raw diagnostic is most likely to land. Not knowing the cause is not permission to widen the channel; the raw text belongs in scrubbed logs. That key is ALSO an event cause as of round 6 (`resolution-event.schema.json` → `reason: unclassified_error`), because a status that never lapses on a timer is a state the user has to be told about; the five non-self-healing keys and the five non-self-healing reasons are a bijection, checked mechanically (api.md → Mechanical guards). VOCABULARY HOME: this field owns these keys — all TEN of them, the five cooldown plus the four needs_action plus this one `error` key — and probe-result.schema.json → `error` mirrors them, because draft-07 gives a bare validator no cross-file `$ref`; the lists are compared mechanically ACROSS files (README.md → vocabulary mirror table, api.md → Serializer completeness). The `examples` list below is part of that comparison and not decoration: round 6 added the `error` key to the three enforcing branches and left `examples` at nine, so the field advertised a nine-key vocabulary while enforcing ten, and round 7 found it. Two things made that survivable and are now closed: this key is pinned as a `const` rather than a one-value `enum`, so a checker that collects only `enum` lists could not see it and its 'examples equal the enforced union' guard passed vacuously; and the comparison ran inside each file rather than between them. `const` now counts as an enum of cardinality one (07-29, review round 7).","examples": ["models.source.cooldown.network","models.source.cooldown.timeout",diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.pyindex d200334eb..008e77485 100644--- a/tests/scenario_harness/model_hub_native_oauth.py+++ b/tests/scenario_harness/model_hub_native_oauth.py@@ -45,9 +45,18 @@ class FakeAgentAuthService:self.flows: dict[str, SimpleNamespace] = {}self.submissions: list[tuple[str, str]] = []self.cancelled: list[str] = []-- async def start_web_setup(self, backend: str, *, force_reset: bool = True):- assert force_reset is False+ self.start_calls: list[tuple[str, bool]] = []++ async def start_web_setup(+ self,+ backend: str,+ *,+ force_reset: bool = True,+ on_irreversible_start=None,+ ):+ if force_reset and on_irreversible_start is not None:+ on_irreversible_start()+ self.start_calls.append((backend, force_reset))flow_id = f"web_{uuid.uuid4().hex[:8]}"flow = SimpleNamespace(flow_id=flow_id,diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 91346e307..9d3687208 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -8,6 +8,7 @@ capability:shared_harness:- tests/scenario_harness/core.py- tests/scenario_harness/auth_setup.py+ - tests/scenario_harness/model_hub_native_oauth.pystatus_legend:covered: scenario coverage existspartial: unit or contract coverage exists but the closed loop is incomplete@@ -70,6 +71,13 @@ scenarios:layer: scenariobackend: claudetest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_callback_submission_and_fallback_command_do_not_double_consume_claude_flow+ - id: AUTH-SETUP-106+ name: Native Model Hub re-auth confirms before irreversible honest failure+ status: covered+ kind: negative_path+ layer: scenario+ backend: claude+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_native_model_hub_reauth_confirms_before_honest_failure- id: AUTH-SETUP-201name: Re-entering setup replaces the active flowstatus: covered@@ -141,5 +149,4 @@ scenarios:backend: claudetest: tests/test_claude_agent_sessions.py::test_assistant_auth_error_without_is_api_error_flag_still_triggers_recoverynext_priority:- - AUTH-SETUP-106- AUTH-SETUP-301diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex b725fcc3d..b1b36921d 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -1,5 +1,6 @@import asyncioimport sys+import tempfileimport unittestfrom pathlib import Pathfrom types import SimpleNamespace@@ -8,8 +9,15 @@ from unittest.mock import AsyncMockROOT = Path(__file__).resolve().parents[3]sys.path.insert(0, str(ROOT))+from config.v2_config import (+ ModelHubModelConfig,+ ModelHubSourceConfig,+ ModelHubSourceStateConfig,+)+from core.handlers.model_hub.service import ModelHubErrorfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcessfrom tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep+from tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarnessclass _FakeNextTurnRuntime:@@ -42,6 +50,73 @@ class _FakeCodexNextTurnRuntime:class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):+ async def test_native_model_hub_reauth_confirms_before_honest_failure(self):+ """Scenario: AUTH-SETUP-106"""+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = NativeOAuthScenarioHarness(+ Path(state_dir.name),+ )+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ harness.store.config.sources.append(source)+ harness.store.config.refresh_follow_orders()++ with self.assertRaises(ModelHubError) as refused:+ await harness.service.reauth_source(source.id, {})++ self.assertEqual(+ refused.exception.code,+ "reauth_confirmation_required",+ )+ self.assertEqual(harness.agent_auth.flows, {})+ self.assertEqual(harness.store.config.sources[0].state.status, "standby")+ self.assertEqual(+ [model.id for model in harness.store.config.sources[0].models],+ ["claude-opus-4-6"],+ )++ started = await harness.service.reauth_source(+ source.id,+ {"acknowledge_irreversible": True},+ )+ flow_id = started["flow"]["flow_id"]+ self.assertEqual(started["flow"]["intent"], "reauth")+ self.assertEqual(harness.agent_auth.start_calls, [("claude", True)])+ self.assertEqual(+ harness.store.config.sources[0].state.status,+ "needs_action",+ )+ self.assertEqual(harness.store.config.sources[0].models, [])++ harness.agent_auth.timeout(flow_id)+ failed = await harness.service.oauth_status(flow_id)++ self.assertEqual(failed["flow"]["state"], "failed")+ self.assertNotIn("source", failed)+ self.assertEqual(+ harness.store.config.sources[0].state.status,+ "needs_action",+ )+ self.assertEqual(+ harness.service.get_agent_sources("claude")["supply_status"],+ "interrupted",+ )+async def test_codex_failure_scenario_emits_reset_path(self):"""Scenario: AUTH-SETUP-202"""harness = AuthSetupScenarioHarness()diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.pyindex e2a3f5657..c4a60edfb 100644--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py@@ -38,6 +38,7 @@ def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path)base_url=BASE_URL,).get_json()["flow"]assert started["state"] == "awaiting_action"+ assert harness.agent_auth.start_calls == [("claude", False)]assert started["presentation"] == {"auth_url": "https://claude.ai/oauth/authorize?test=true","device_code": None,diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 407ac7e18..b896a07ac 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -11,6 +11,8 @@ from jsonschema import Draft7Validator, FormatCheckerfrom config.v2_config import (ModelHubAgentSupplyConfig,ModelHubConfig,+ ModelHubModelConfig,+ ModelHubSourceConfig,ModelHubSourceStateConfig,)from core.handlers.model_hub.adapter import (@@ -94,6 +96,7 @@ class FakeAdapter:self.fail_cancel = Falseself.native_signed_in = Trueself.native_account_label = None+ self.oauth_start_calls = []async def ensure_installed(self):return await self.status()@@ -161,11 +164,23 @@ class FakeAdapter:)async def start_oauth(self, source_id, vendor):+ self.oauth_start_calls.append((source_id, vendor))flow = self._flow(source_id, f"oaf_{len(self.flows) + 1:08d}")flow = OAuthFlowState(**{**flow.__dict__, "vendor": vendor})self.flows[flow.flow_id] = flowreturn flow+ async def start_reauth(+ self,+ source_id,+ vendor,+ *,+ on_irreversible_start=None,+ ):+ if on_irreversible_start is not None:+ on_irreversible_start()+ return await self.start_oauth(source_id, vendor)+async def oauth_status(self, flow_id):return self.flows[flow_id]@@ -452,12 +467,40 @@ def test_ui_model_hub_rpc_preserves_controller_error_contract():assert exc_info.value.detail == "modelHub.errors.mode_switch_blocked"+def test_ui_model_hub_rpc_preserves_structured_guard_data():+ import httpx++ would_interrupt = [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": ["pm"],+ }+ ]+ response = httpx.Response(+ 409,+ json={+ "ok": False,+ "error": "source_last_supplier",+ "detail": "modelHub.errors.source_last_supplier",+ "would_interrupt": would_interrupt,+ },+ )++ with pytest.raises(ModelHubError) as exc_info:+ _decode(response)++ assert exc_info.value.data == {"would_interrupt": would_interrupt}++@pytest.mark.parametrize(("method", "path"),[("GET", "/api/models/sources"),("POST", "/api/models/sources"),("PATCH", "/api/models/sources/src_test0001"),+ ("PUT", "/api/models/sources/src_test0001/credential"),+ ("POST", "/api/models/sources/src_test0001/reauth"),("DELETE", "/api/models/sources/src_test0001"),("POST", "/api/models/sources/src_test0001/test"),("GET", "/api/models/agents"),@@ -629,6 +672,32 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):_assert_envelope(error, ok=False)assert error["error"] == "invalid_source_order"+ response = client.put(+ "/api/models/agents/claude/sources",+ json={+ "policy": "follow",+ "unexpected": True,+ "another_rejected_key": True,+ },+ headers=headers,+ base_url=base_url,+ )+ error = response.get_json()+ assert error["error"] == "invalid_source_order"+ assert error["detail"] == "modelHub.errors.invalid_source_order"+ assert error["rejected_keys"] == ["another_rejected_key", "unexpected"]++ credential_shaped_key = "sk-secret-material-that-must-not-reflect"+ response = client.put(+ "/api/models/agents/claude/sources",+ json={"policy": "follow", credential_shaped_key: True},+ headers=headers,+ base_url=base_url,+ )+ error = response.get_json()+ assert credential_shaped_key not in json.dumps(error)+ assert error["rejected_keys"] == ["[redacted]"]+response = client.put("/api/models/agents/claude/sources",json={"policy": "custom", "order": []},@@ -664,6 +733,16 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):)_assert_valid("source.schema.json", response.get_json()["source"])+ persisted_source = store.config.sources[0]+ immutable_identity = (+ persisted_source.id,+ persisted_source.created_at,+ persisted_source.credential_ref,+ )+ persisted_source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ )response = client.post(f"/api/models/sources/{source_id}/test",headers=headers,@@ -672,6 +751,12 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):body = response.get_json()_assert_envelope(body)assert body["discovered"] == 2+ assert store.config.sources[0].state.status == "standby"+ assert (+ store.config.sources[0].id,+ store.config.sources[0].created_at,+ store.config.sources[0].credential_ref,+ ) == immutable_identityresponse = client.post("/api/models/custom-models",@@ -887,6 +972,16 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):("path", "method", "error"),[("/api/models/sources/src_test0001", "patch", "discovery_failed"),+ (+ "/api/models/sources/src_test0001/credential",+ "put",+ "discovery_failed",+ ),+ (+ "/api/models/sources/src_test0001/reauth",+ "post",+ "discovery_failed",+ ),("/api/models/agents/claude/sources", "put", "invalid_source_order"),("/api/models/agents/claude/mode", "patch", "mode_switch_blocked"),("/api/models/agents/claude/mappings", "put", "mapping_target_unavailable"),@@ -919,6 +1014,1184 @@ def test_model_hub_routes_reject_non_object_json_with_error_envelope(assert body["error"] == error+def test_native_reauth_route_requires_ack_before_oauth_and_returns_reauth_tail(+ monkeypatch,+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ native = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(native)+ store.config.refresh_follow_orders()+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)++ refused = client.post(+ f"/api/models/sources/{native.id}/reauth",+ json={},+ headers=headers,+ base_url=base_url,+ )++ assert refused.status_code == 409+ assert refused.get_json()["error"] == "reauth_confirmation_required"+ assert adapter.oauth_start_calls == []+ assert store.config.sources[0].state.status == "standby"+ assert [model.id for model in store.config.sources[0].models] == ["claude-opus-4-6"]++ original_start_reauth = adapter.start_reauth++ async def assert_source_unavailable_before_logout(+ source_id,+ vendor,+ *,+ on_irreversible_start=None,+ ):+ persisted = store.config.sources[0]+ assert persisted.state.status == "standby"+ assert [model.id for model in persisted.models] == ["claude-opus-4-6"]+ assert on_irreversible_start is not None+ on_irreversible_start()+ assert persisted.state.status == "needs_action"+ assert persisted.models == []+ return await original_start_reauth(source_id, vendor)++ adapter.start_reauth = assert_source_unavailable_before_logout+ started = client.post(+ f"/api/models/sources/{native.id}/reauth",+ json={"acknowledge_irreversible": True},+ headers=headers,+ base_url=base_url,+ ).get_json()+ flow = started["flow"]++ assert flow["intent"] == "reauth"+ assert adapter.oauth_start_calls == [(native.id, "anthropic")]+ assert store.config.sources[0].state.status == "needs_action"+ assert store.config.sources[0].models == []++ adapter.native_account_label = "[email protected]"+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ }+ )+ completed = client.get(+ f"/api/models/oauth/status/{flow['flow_id']}",+ base_url=base_url,+ ).get_json()++ assert completed["flow"]["intent"] == "reauth"+ assert set(completed) == {+ "ok",+ "contract_version",+ "flow",+ "source",+ "recovered",+ "interrupted_pairs",+ }+ assert completed["recovered"] is False+ assert completed["source"]["account_label"] == "[email protected]"+ assert completed["source"]["state"]["status"] == "standby"+++def test_native_reauth_reuses_pending_flow_per_source(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(source)+ store.config.refresh_follow_orders()+ payload = {"acknowledge_irreversible": True}++ first = asyncio.run(service.reauth_source(source.id, payload))["flow"]+ second = asyncio.run(service.reauth_source(source.id, payload))["flow"]++ assert second["flow_id"] == first["flow_id"]+ assert adapter.oauth_start_calls == [(source.id, "anthropic")]+++def test_native_reauth_post_login_discovery_failure_reports_honest_gaps(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(source)+ store.config.refresh_follow_orders()+ store.requested_model = lambda backend: ("claude-opus-4-6" if backend == "claude" else "")+ 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": "success",+ }+ )++ def fail_completed_status(_flow_id):+ raise RuntimeError("new login cannot be inspected")++ adapter.completed_source_status = fail_completed_status+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "discovery_failed"+ assert exc_info.value.data["interrupted_pairs"] == [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": [],+ }+ ]+ assert store.config.sources[0].models == []+ assert store.config.sources[0].state.status == "error"+++def test_native_reauth_registry_failure_keeps_irreversible_state_honest(+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(source)+ store.config.refresh_follow_orders()++ def fail_remember(*args, **kwargs):+ raise OSError("registry unavailable")++ service.oauth_flows.remember = fail_remember+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.reauth_source(+ source.id,+ {"acknowledge_irreversible": True},+ )+ )++ assert exc_info.value.code == "engine_down"+ assert adapter.oauth_start_calls == [(source.id, "anthropic")]+ assert store.config.sources[0].models == []+ assert store.config.sources[0].state.status == "needs_action"+ assert adapter.cancelled == [next(iter(adapter.flows))]+++def test_native_reauth_invalidates_sibling_sources_for_shared_cli(tmp_path):+ service, store, adapter = _service(tmp_path)+ sources = [+ ModelHubSourceConfig(+ id=f"src_native000{index}",+ kind="subscription",+ vendor="anthropic",+ display_name=f"Claude subscription {index}",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ account_label=f"account-{index}",+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ for index in (1, 2)+ ]+ store.config.sources.extend(sources)+ store.config.refresh_follow_orders()++ flow = asyncio.run(+ service.reauth_source(+ sources[0].id,+ {"acknowledge_irreversible": True},+ )+ )["flow"]++ assert all(source.models == [] for source in store.config.sources)+ assert all(+ source.state.status == "needs_action"+ for source in store.config.sources+ )+ assert all(source.account_label is None for source in store.config.sources)++ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ }+ )+ asyncio.run(service.oauth_status(flow["flow_id"]))++ selected, sibling = store.config.sources+ assert selected.state.status == "standby"+ assert selected.models+ assert all(model.provenance == "discovered" for model in selected.models)+ assert any(model.id == "claude-opus-4-6" for model in selected.models)+ assert sibling.models == []+ assert sibling.state.status == "needs_action"+ assert sibling.account_label is None+++def test_native_reauth_pre_boundary_failure_preserves_prior_supply(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(source)+ store.config.refresh_follow_orders()+ before = json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )++ async def fail_before_logout(+ source_id,+ vendor,+ *,+ on_irreversible_start=None,+ ):+ flow = OAuthFlowState(+ **{+ **adapter._flow(source_id, "oaf_failed01").__dict__,+ "vendor": vendor,+ "state": "failed",+ "error_key": "settings.models.oauth.error.generic",+ }+ )+ adapter.flows[flow.flow_id] = flow+ return flow++ adapter.start_reauth = fail_before_logout+ result = asyncio.run(+ service.reauth_source(+ source.id,+ {"acknowledge_irreversible": True},+ )+ )++ assert result["flow"]["state"] == "failed"+ assert json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ ) == before+++def test_native_reauth_logout_spawn_failure_restores_prior_supply(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ )+ store.config.sources.append(source)+ store.config.refresh_follow_orders()+ before = json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )++ async def fail_logout_spawn(+ source_id,+ vendor,+ *,+ on_irreversible_start=None,+ ):+ assert on_irreversible_start is not None+ restore = on_irreversible_start()+ assert store.config.sources[0].state.status == "needs_action"+ assert restore is not None+ restore()+ flow = OAuthFlowState(+ **{+ **adapter._flow(source_id, "oaf_failed01").__dict__,+ "vendor": vendor,+ "state": "failed",+ "error_key": "settings.models.oauth.error.generic",+ }+ )+ adapter.flows[flow.flow_id] = flow+ return flow++ adapter.start_reauth = fail_logout_spawn+ result = asyncio.run(+ service.reauth_source(+ source.id,+ {"acknowledge_irreversible": True},+ )+ )++ assert result["flow"]["state"] == "failed"+ assert json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ ) == before+++def test_hub_reauth_is_transactional_without_native_acknowledgement(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ ),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_old",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()++ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ assert flow["intent"] == "reauth"+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_new",+ }+ )+ result = asyncio.run(service.oauth_status(flow["flow_id"]))++ assert result["recovered"] is True+ assert result["source"]["credential_ref"] == "cred_hub_new"+ assert result["source"]["state"]["status"] == "standby"+ assert "adopted_by" not in result+ assert adapter.revoked == ["cred_hub_old"]+ assert service.revocations.list() == []+++def test_hub_reauth_replaces_pending_flow_unknown_to_restarted_adapter(+ 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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ first = asyncio.run(service.reauth_source(source.id, {}))["flow"]++ async def restarted_adapter_does_not_know_flow(_flow_id):+ raise RuntimeError("OAuth flow is unknown after restart")++ restarted_adapter = FakeAdapter()+ restarted_adapter.oauth_status = restarted_adapter_does_not_know_flow+ restarted = ModelHubService(+ store=store,+ adapter=restarted_adapter,+ events=BoundedEventLog(tmp_path / "restarted-events.json"),+ native_oauth_adapter=restarted_adapter,+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ )+ second = asyncio.run(restarted.reauth_source(source.id, {}))["flow"]++ assert first["flow_id"] in adapter.flows+ assert second["flow_id"] in restarted_adapter.flows+ replacement_binding = restarted.oauth_flows.binding(second["flow_id"])+ assert replacement_binding is not None+ assert replacement_binding.source_id == source.id+ assert adapter.oauth_start_calls == [(source.id, "anthropic")]+ assert restarted_adapter.oauth_start_calls == [(source.id, "anthropic")]+++def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(+ 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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ ),+ models=[+ ModelHubModelConfig(+ id="stale-entitlement",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()++ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_reused",+ }+ )+ result = asyncio.run(service.oauth_status(flow["flow_id"]))++ assert result["recovered"] is True+ assert result["source"]["state"]["status"] == "standby"+ assert {model["id"] for model in result["source"]["models"]} == {+ "claude-opus-4-6",+ "claude-sonnet-4-6",+ }+ assert adapter.revoked == []+ assert service.revocations.list() == []+++def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):+ async def run_race():+ class BlockingDiscoveryAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.discovery_calls = 0+ self.discovery_started = asyncio.Event()+ self.release_discovery = asyncio.Event()++ async def discover_models(+ self,+ vendor,+ protocol,+ base_url,+ credential_ref,+ ):+ self.discovery_calls += 1+ if self.discovery_calls > 1:+ raise ModelDiscoveryError("duplicate materialization")+ self.discovery_started.set()+ await self.release_discovery.wait()+ return ("claude-opus-4-6",)++ store = MemoryStore()+ adapter = BlockingDiscoveryAdapter()+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ native_oauth_adapter=adapter,+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ )+ source = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()++ flow = (await service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_reused",+ }+ )++ first = asyncio.create_task(service.oauth_status(flow["flow_id"]))+ await adapter.discovery_started.wait()+ second = asyncio.create_task(service.oauth_status(flow["flow_id"]))+ await asyncio.sleep(0)+ adapter.release_discovery.set()+ results = await asyncio.gather(first, second)+ return results, service, store, adapter, flow["flow_id"]++ results, service, store, adapter, flow_id = asyncio.run(run_race())++ assert adapter.discovery_calls == 1+ assert results[0] == results[1]+ assert store.config.sources[0].state.status == "standby"+ binding = service.oauth_flows.binding(flow_id)+ assert binding is not None+ assert binding.completed is True+++def test_failed_undiscriminated_hub_reauth_fails_closed(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "failed",+ "error_key": "models.oauth.binding_failed",+ }+ )++ result = asyncio.run(service.oauth_status(flow["flow_id"]))++ assert result["flow"]["state"] == "failed"+ persisted = store.config.sources[0]+ assert persisted.credential_ref == "cred_hub_existing"+ assert [model.id for model in persisted.models] == ["manual-model"]+ assert persisted.state.status == "needs_action"+ assert persisted.state.detail_key == "models.source.needs_action.oauth_expired"+ assert adapter.revoked == []+ assert service.revocations.list() == []+++def test_hub_reauth_retry_materializes_failed_pending_flow(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ first = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[first["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[first["flow_id"]].__dict__,+ "state": "failed",+ "error_key": "models.oauth.binding_failed",+ }+ )++ second = asyncio.run(service.reauth_source(source.id, {}))["flow"]++ persisted = store.config.sources[0]+ assert [model.id for model in persisted.models] == ["manual-model"]+ assert persisted.state.status == "needs_action"+ assert (+ persisted.state.detail_key+ == "models.source.needs_action.oauth_expired"+ )+ assert service.oauth_flows.binding(first["flow_id"]) is None+ replacement = service.oauth_flows.binding(second["flow_id"])+ assert replacement is not None+ assert replacement.recovered is True++[email protected]("registry_failure", ["missing", "unwritable"])+def test_hub_reauth_returns_terminal_tail_when_registry_completion_fails(+ tmp_path,+ registry_failure,+):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_reused",+ }+ )+ original_complete = service.oauth_flows.complete+ completion_calls = 0++ def fail_registry_complete(*args, **kwargs):+ nonlocal completion_calls+ completion_calls += 1+ if registry_failure == "unwritable":+ raise OSError("registry unavailable")+ if completion_calls == 1:+ service.oauth_flows.path.unlink()+ return original_complete(*args, **kwargs)++ service.oauth_flows.complete = fail_registry_complete+ result = asyncio.run(service.oauth_status(flow["flow_id"]))++ assert result["flow"]["state"] == "success"+ assert result["source"]["state"]["status"] == "standby"+ assert result["recovered"] is False+ assert result["interrupted_pairs"] == []+ assert completion_calls == (2 if registry_failure == "missing" else 1)++[email protected]("failure", ["discovery", "sync"])+def test_failed_same_handle_hub_reauth_requires_user_action(+ tmp_path,+ failure,+):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_reused",+ }+ )++ async def fail_discovery(vendor, protocol, base_url, credential_ref):+ raise ModelDiscoveryError("safe discovery failure")++ if failure == "discovery":+ adapter.discover_models = fail_discovery+ else:+ adapter.fail_sync = True+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == (+ "discovery_failed" if failure == "discovery" else "engine_down"+ )+ persisted = store.config.sources[0]+ assert persisted.credential_ref == "cred_hub_reused"+ assert persisted.models == []+ assert persisted.state.status == "needs_action"+ assert persisted.state.detail_key == "models.source.needs_action.oauth_expired"+ assert adapter.revoked == []+ assert service.revocations.list() == []+ assert service.oauth_flows.binding(flow["flow_id"]) is None+++def test_failed_zero_model_hub_source_is_omitted_from_restart_sync(tmp_path):+ class StrictProjectionAdapter(FakeAdapter):+ async def sync_sources(self, bindings):+ assert all(binding.model_ids for binding in bindings)+ await super().sync_sources(bindings)++ service, store, adapter = _service(tmp_path)+ failed = ModelHubSourceConfig(+ id="src_huboauth01",+ kind="subscription",+ vendor="anthropic",+ display_name="Failed Hub subscription",+ protocol="anthropic",+ supply_channel="hub",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ ),+ models=[],+ credential_ref="cred_hub_reused",+ )+ healthy = ModelHubSourceConfig(+ id="src_hubhealthy01",+ kind="api_key",+ vendor="anthropic",+ display_name="Healthy Hub source",+ protocol="anthropic",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_healthy",+ )+ store.config.sources = [failed, healthy]+ store.config.refresh_follow_orders()+ restarted_adapter = StrictProjectionAdapter()+ restarted = ModelHubService(+ store=store,+ adapter=restarted_adapter,+ events=BoundedEventLog(tmp_path / "restarted-events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),+ revocations=CredentialRevocationJournal(+ tmp_path / "restarted-revocations.json"+ ),+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ )++ resolved = asyncio.run(+ restarted.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert resolved.source_id == healthy.id+ assert [+ tuple(binding.source_id for binding in batch)+ for batch in restarted_adapter.synced+ ] == [(healthy.id,)]+ assert adapter.synced == []+++def test_restart_reconciles_revocation_without_runnable_supply(tmp_path):+ store = MemoryStore()+ journal_path = tmp_path / "revocations.json"+ journal = CredentialRevocationJournal(journal_path)+ journal.add("src_deleted0001", "cred_pending_old")+ adapter = FakeAdapter()+ restarted = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "restarted-events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),+ revocations=CredentialRevocationJournal(journal_path),+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ restarted.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert exc_info.value.code == "mapping_target_unavailable"+ assert adapter.synced == [()]+ assert adapter.revoked == ["cred_pending_old"]+ assert restarted.revocations.list() == []+++def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(+ 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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_new",+ }+ )+ before = json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )++ async def fail_discovery(vendor, protocol, base_url, credential_ref):+ raise ModelDiscoveryError("safe discovery failure")++ adapter.discover_models = fail_discovery+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "discovery_failed"+ assert json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ ) == before+ assert adapter.revoked == ["cred_hub_new"]+ assert service.oauth_flows.binding(flow["flow_id"]) is None+++def test_completed_hub_reauth_revokes_replacement_after_source_disappears(+ 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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ asyncio.run(service.delete_source(source.id, force=True))+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_orphan",+ }+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "source_not_found"+ assert adapter.revoked == ["cred_hub_old", "cred_hub_orphan"]+ assert service.revocations.list() == []+ assert service.oauth_flows.binding(flow["flow_id"]) is None+ with pytest.raises(ModelHubError) as repeated:+ asyncio.run(service.oauth_status(flow["flow_id"]))+ assert repeated.value.code == "flow_not_found"+++def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_new",+ }+ )+ before = json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ original_remove = service.revocations.remove++ def fail_old_journal_cleanup(source_id, credential_ref):+ if credential_ref == "cred_hub_old":+ raise OSError("journal cleanup failed")+ return original_remove(source_id, credential_ref)++ service.revocations.remove = fail_old_journal_cleanup+ adapter.fail_sync = True++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "engine_down"+ assert json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ ) == before+ assert adapter.revoked == ["cred_hub_new"]+ assert service.oauth_flows.binding(flow["flow_id"]) is None+++def test_credential_route_carries_body_force_override_and_structured_guard(+ monkeypatch,+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ provision_count = 0++ async def provision(vendor, protocol, secret, base_url):+ nonlocal provision_count+ provision_count += 1+ adapter.secret_lengths.append(len(secret))+ return f"cred_route_{provision_count}"++ adapter.provision_credential = provision+ created = asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Guarded source",+ "protocol": "anthropic",+ "key": "sk-original-route-key",+ }+ )+ )["source"]+ store.requested_model = lambda backend: (+ "claude-opus-4-6" if backend == "claude" else ""+ )++ async def discover_narrower(vendor, protocol, base_url, credential_ref):+ return ("replacement-only-model",)++ adapter.discover_models = discover_narrower+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)+ request_body = {"key": "sk-narrower-route-key"}++ refused = client.put(+ f"/api/models/sources/{created['id']}/credential",+ json=request_body,+ headers=headers,+ base_url=base_url,+ )++ assert refused.status_code == 409+ refusal = refused.get_json()+ assert refusal["error"] == "source_last_supplier"+ assert refusal["would_interrupt"] == [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": [],+ }+ ]+ committed = client.put(+ f"/api/models/sources/{created['id']}/credential",+ json={**request_body, "force": True},+ headers=headers,+ base_url=base_url,+ ).get_json()++ assert committed["recovered"] is False+ assert committed["interrupted_pairs"] == refusal["would_interrupt"]+ assert committed["source"]["credential_ref"] == "cred_route_3"+ assert adapter.revoked == ["cred_route_2", "cred_route_1"]++def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):service, store, adapter = _service(tmp_path)flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub", "experimental_consent": True}))[@@ -1038,6 +2311,104 @@ def test_failed_oauth_cancel_keeps_flow_retryable(tmp_path):assert adapter.cancelled == [flow_id, flow_id]+def test_cancel_materializes_terminal_successful_hub_reauth(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ billing="monthly",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ ),+ models=[+ ModelHubModelConfig(+ id="stale-entitlement",+ provenance="discovered",+ )+ ],+ credential_ref="cred_hub_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_hub_reused",+ }+ )++ asyncio.run(service.oauth_cancel(flow["flow_id"]))++ persisted = store.config.sources[0]+ assert persisted.state.status == "standby"+ assert {model.id for model in persisted.models} == {+ "claude-opus-4-6",+ "claude-sonnet-4-6",+ }+ binding = service.oauth_flows.binding(flow["flow_id"])+ assert binding is not None+ assert binding.completed is True+ assert adapter.cancelled == []+++def test_cancel_materializes_terminal_failed_hub_reauth(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",+ experimental_consent_at="2026-07-23T02:00:00+00:00",+ 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_reused",+ )+ store.config.sources.append(source)+ store.config.subscription_hub_experimental = True+ store.config.refresh_follow_orders()+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "failed",+ "error_key": "models.oauth.binding_failed",+ }+ )++ asyncio.run(service.oauth_cancel(flow["flow_id"]))++ persisted = store.config.sources[0]+ assert [model.id for model in persisted.models] == ["manual-model"]+ assert persisted.state.status == "needs_action"+ assert (+ persisted.state.detail_key+ == "models.source.needs_action.oauth_expired"+ )+ assert service.oauth_flows.binding(flow["flow_id"]) is None+ assert adapter.cancelled == []++def test_oauth_completion_requires_the_persisted_pending_source_identity(tmp_path):service, store, adapter = _service(tmp_path)flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]diff --git a/tests/test_model_hub_oauth.py b/tests/test_model_hub_oauth.pyindex bfa046957..5dc84e037 100644--- a/tests/test_model_hub_oauth.py+++ b/tests/test_model_hub_oauth.py@@ -51,6 +51,50 @@ def test_flow_registry_defaults_legacy_bindings_to_no_consent(tmp_path):assert binding.completed is False+def test_flow_registry_returns_latest_pending_reauth_for_source(tmp_path):+ registry = OAuthFlowRegistry(tmp_path / "oauth_flows.json")+ registry.remember(+ "oaf_first001",+ "native_cli",+ "src_native001",+ "anthropic",+ intent="reauth",+ )+ registry.remember(+ "oaf_second01",+ "native_cli",+ "src_native001",+ "anthropic",+ intent="reauth",+ )+ registry.remember(+ "oaf_create01",+ "hub",+ "src_native001",+ "anthropic",+ )+ registry.complete("oaf_second01")++ pending = registry.pending_reauth("src_native001")++ assert pending is not None+ assert pending[0] == "oaf_first001"++ registry.remember(+ "oaf_replaced1",+ "native_cli",+ "src_native001",+ "anthropic",+ intent="reauth",+ replace_flow_id="oaf_first001",+ )++ assert registry.binding("oaf_first001") is None+ replaced = registry.pending_reauth("src_native001")+ assert replaced is not None+ assert replaced[0] == "oaf_replaced1"++def test_native_status_trusts_codex_keyring_success_but_not_active_api_keys():assert _signed_in("codex",diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 0fbe4a2ec..2c1efada8 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -23,11 +23,13 @@ from core.handlers.model_hub.adapter import (RawOutcomeKind,)from core.handlers.model_hub.classification import classify_outcome+from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom core.handlers.model_hub.events import BoundedEventLog, build_resolution_eventfrom core.handlers.model_hub.resolver import resolve_model_hub_turnfrom core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import ModelHubError, ModelHubService, _mask_credentialfrom vibe.i18n import t as i18n_t+from vibe.model_hub_runtime.state import EngineStateErrorclass MemoryStore:@@ -639,6 +641,53 @@ def test_native_dispatch_attempts_pending_credential_revoke(tmp_path):assert adapter.invocations == []+def test_pending_revoke_clears_when_credential_is_already_absent(tmp_path):+ class AlreadyRevokedAdapter(FakeAdapter):+ async def revoke_credential(self, credential_ref):+ self.revoked.append(credential_ref)+ raise EngineStateError("credential is unavailable")++ adapter = AlreadyRevokedAdapter(+ [_outcome(RawOutcomeKind.SUCCESS, status=200)]+ )+ service = _service(tmp_path, adapter)+ service.revocations.add("src_deleted", "cred_deleted")++ resolved = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert resolved.source_id == "src_primary01"+ assert adapter.revoked == ["cred_deleted"]+ assert service.revocations.list() == []+++def test_pending_revoke_failure_does_not_block_hub_routing(tmp_path):+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ adapter.fail_revoke = True+ service = _service(tmp_path, adapter)+ service.revocations.add("src_deleted", "cred_deleted")++ resolved = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert resolved.source_id == "src_primary01"+ assert adapter.revoked == ["cred_deleted"]+ assert service.revocations.list()[0].credential_ref == "cred_deleted"+ assert adapter.invocations == [+ ("src_primary01", "claude-opus-4-6", "claude")+ ]++def test_direct_mode_never_enters_hub_resolution(tmp_path):adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])service = _service(tmp_path, adapter)@@ -767,6 +816,60 @@ def test_failed_create_rollback_is_journaled_until_revoke_recovers(tmp_path):assert service.revocations.list() == []+def test_failed_create_rollback_attempts_revoke_when_journal_add_fails(tmp_path):+ adapter = FakeAdapter([])+ adapter.fail_sync = True+ service = _service(tmp_path, adapter)++ def fail_journal_add(source_id, credential_ref):+ raise OSError("journal write failed")++ service.revocations.add = fail_journal_add++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Rollback source",+ "key": "sk-test-transaction-only",+ }+ )+ )++ assert exc_info.value.code == "engine_down"+ assert adapter.revoked == ["cred_test"]+ assert service.revocations.list() == []+++def test_empty_discovery_rejects_source_creation_and_revokes_credential(tmp_path):+ adapter = FakeAdapter([])+ service = _service(tmp_path, adapter)+ before = _serialized_config(service)++ async def empty_discovery(vendor, protocol, base_url, credential_ref):+ return ()++ adapter.discover_models = empty_discovery++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Empty source",+ "key": "sk-test-empty-discovery",+ }+ )+ )++ assert exc_info.value.code == "discovery_failed"+ assert _serialized_config(service) == before+ assert adapter.revoked == ["cred_test"]++def test_subscription_source_rejects_api_key_credentials(tmp_path):adapter = FakeAdapter([])service = _service(tmp_path, adapter)@@ -1042,13 +1145,421 @@ def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):config.agents["claude"].mappings = [ModelHubMappingConfig("claude-native", "claude-opus-4-6", True)]with pytest.raises(ModelHubError) as exc_info:asyncio.run(service.delete_source("src_primary01"))- assert exc_info.value.code == "mode_switch_blocked"+ assert exc_info.value.code == "source_last_supplier"config.agents["claude"].mode = "direct"asyncio.run(service.delete_source("src_primary01"))assert [source.id for source in service.store.load().sources] == ["src_backup001"]+class NarrowingCredentialAdapter(FakeAdapter):+ def __init__(self, outcomes=()):+ super().__init__(outcomes)+ self.provision_count = 0+ self.fail_discovery = False+ self.fail_old_revoke_once = False++ async def provision_credential(self, vendor, protocol, secret, base_url):+ self.provision_count += 1+ credential_ref = f"cred_replacement_{self.provision_count}"+ self.provisioned.append((vendor, protocol, base_url))+ return credential_ref++ async def discover_models(self, vendor, protocol, base_url, credential_ref):+ if self.fail_discovery:+ raise ModelDiscoveryError("safe classified failure")+ return ("replacement-only-model",)++ async def revoke_credential(self, credential_ref):+ self.revoked.append(credential_ref)+ if self.fail_old_revoke_once and credential_ref == "cred_src_primary01":+ self.fail_old_revoke_once = False+ raise RuntimeError("old handle still busy")+++def _repair_guard_service(tmp_path, *, enabled: bool, adapter=None):+ adapter = adapter or NarrowingCredentialAdapter()+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = [ModelHubModelConfig(id="glm-5.2", provenance="discovered")]+ config.sources[1].models = [ModelHubModelConfig(id="claude-haiku-4-5", provenance="discovered")]+ config.agents["claude"].mappings = [+ ModelHubMappingConfig(+ builtin_id="claude-opus-4-6",+ target_model_id="glm-5.2",+ enabled=enabled,+ )+ ]+ service.store.requested_models["claude"] = "claude-haiku-4-5"+ return service, adapter+++ ("route", "enabled", "blocked"),+ [+ ("delete", False, False),+ ("delete", True, True),+ ("credential", False, False),+ ("credential", True, True),+ ],+)+def test_supply_guard_uses_only_enabled_menu_mappings_from_fresh_fixtures(+ tmp_path,+ route,+ enabled,+ blocked,+):+ service, _adapter = _repair_guard_service(+ tmp_path / f"{route}-{enabled}",+ enabled=enabled,+ )++ if blocked:+ with pytest.raises(ModelHubError) as exc_info:+ if route == "delete":+ asyncio.run(service.delete_source("src_primary01"))+ else:+ asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-narrower-replacement"},+ )+ )+ assert exc_info.value.code == "source_last_supplier"+ assert exc_info.value.data["would_interrupt"] == [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": [],+ }+ ]+ elif route == "delete":+ asyncio.run(service.delete_source("src_primary01"))+ assert [source.id for source in service.store.load().sources] == ["src_backup001"]+ else:+ result = asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-narrower-replacement"},+ )+ )+ assert result["interrupted_pairs"] == []+ assert result["source"]["credential_ref"] == "cred_replacement_1"+++def test_supply_guard_reports_menu_identifier_and_effective_named_agents(tmp_path):+ service, _adapter = _repair_guard_service(tmp_path, enabled=True)+ service.named_agents_override = lambda backend: (+ [("pm", None), ("reviewer", "claude-opus-4-6")] if backend == "claude" else []+ )+ service.store.requested_models["claude"] = "claude-opus-4-6"++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.delete_source("src_primary01"))++ assert exc_info.value.data["would_interrupt"] == [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": ["pm", "reviewer"],+ }+ ]+++def test_supply_guard_canonicalizes_opencode_effective_models(tmp_path):+ service, _adapter = _repair_guard_service(tmp_path, enabled=False)+ config = service.store.load()+ config.sources[0].vendor = "zhipuai"+ config.sources[0].models = [+ ModelHubModelConfig(id="glm-5.2", provenance="discovered")+ ]+ config.sources[1].vendor = "anthropic"+ config.sources[1].models = [+ ModelHubModelConfig(id="claude-haiku-4-5", provenance="discovered")+ ]+ config.agents["claude"].mode = "direct"+ config.agents["codex"].mode = "direct"+ config.agents["opencode"].menu.checked = ["zhipuai/glm-5.2"]+ service.named_agents_override = lambda backend: (+ [("builder", "glm-5.2")] if backend == "opencode" else []+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.delete_source("src_primary01"))++ assert exc_info.value.data["would_interrupt"] == [+ {+ "backend": "opencode",+ "model_id": "zhipuai/glm-5.2",+ "agents": ["builder"],+ }+ ]+++def test_credential_force_commits_same_narrowing_request_and_reports_gaps(tmp_path):+ service, adapter = _repair_guard_service(tmp_path, enabled=True)+ before = _serialized_config(service)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-narrower-replacement"},+ )+ )++ assert exc_info.value.code == "source_last_supplier"+ assert _serialized_config(service) == before+ result = asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-narrower-replacement", "force": True},+ )+ )+ assert result["recovered"] is False+ assert result["interrupted_pairs"] == exc_info.value.data["would_interrupt"]+ assert result["source"]["credential_ref"] == "cred_replacement_2"+ assert adapter.revoked == ["cred_replacement_1", "cred_src_primary01"]+++def test_blocked_credential_repair_bypasses_refusal_and_reports_remaining_gaps(+ tmp_path,+):+ service, _adapter = _repair_guard_service(tmp_path, enabled=True)+ service.store.load().sources[0].state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.credential_revoked",+ )++ result = asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-recovery-key"},+ )+ )++ assert result["recovered"] is True+ assert result["source"]["state"]["status"] == "standby"+ assert result["interrupted_pairs"][0]["model_id"] == "claude-opus-4-6"++[email protected]("failure", ["discovery", "sync"])+def test_credential_replacement_failure_preserves_prior_source(tmp_path, failure):+ adapter = NarrowingCredentialAdapter()+ service, _adapter = _repair_guard_service(+ tmp_path,+ enabled=False,+ adapter=adapter,+ )+ before = _serialized_config(service)+ if failure == "discovery":+ adapter.fail_discovery = True+ else:+ adapter.fail_sync = True++ with pytest.raises(ModelHubError):+ asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-failing-replacement"},+ )+ )++ assert _serialized_config(service) == before+ assert "cred_replacement_1" in adapter.revoked+ assert service.revocations.list() == []+++def test_empty_discovery_rejects_credential_replacement(tmp_path):+ adapter = NarrowingCredentialAdapter()+ service, _adapter = _repair_guard_service(+ tmp_path,+ enabled=False,+ adapter=adapter,+ )+ before = _serialized_config(service)++ async def empty_discovery(vendor, protocol, base_url, credential_ref):+ return ()++ adapter.discover_models = empty_discovery++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-empty-replacement"},+ )+ )++ assert exc_info.value.code == "discovery_failed"+ assert _serialized_config(service) == before+ assert adapter.revoked == ["cred_replacement_1"]+ assert service.revocations.list() == []+++def test_credential_replacement_rolls_back_when_old_journal_cleanup_fails(+ tmp_path,+):+ adapter = NarrowingCredentialAdapter()+ service, _adapter = _repair_guard_service(+ tmp_path,+ enabled=False,+ adapter=adapter,+ )+ before = _serialized_config(service)+ original_remove = service.revocations.remove++ def fail_old_journal_cleanup(source_id, credential_ref):+ if credential_ref == "cred_src_primary01":+ raise OSError("journal cleanup failed")+ return original_remove(source_id, credential_ref)++ service.revocations.remove = fail_old_journal_cleanup+ adapter.fail_sync = True++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-failing-replacement"},+ )+ )++ assert exc_info.value.code == "engine_down"+ assert _serialized_config(service) == before+ assert "cred_replacement_1" in adapter.revoked+++def test_failed_old_credential_revoke_reconciles_after_service_restart(tmp_path):+ adapter = NarrowingCredentialAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ adapter.fail_old_revoke_once = True+ service, _adapter = _repair_guard_service(+ tmp_path,+ enabled=False,+ adapter=adapter,+ )++ result = asyncio.run(+ service.replace_credential(+ "src_primary01",+ {"key": "sk-rotated-key"},+ )+ )++ assert result["source"]["credential_ref"] == "cred_replacement_1"+ assert service.revocations.list()[0].credential_ref == "cred_src_primary01"+ restarted_adapter = NarrowingCredentialAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ restarted = ModelHubService(+ store=service.store,+ adapter=restarted_adapter,+ events=BoundedEventLog(tmp_path / "restarted-events.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ )++ resolved = asyncio.run(+ restarted.resolve(+ backend="claude",+ model_id="replacement-only-model",+ request={},+ )+ )++ assert resolved.source_id == "src_primary01"+ assert restarted_adapter.revoked == ["cred_src_primary01"]+ assert restarted.revocations.list() == []+ assert restarted.store.load().sources[0].credential_ref == "cred_replacement_1"+++def test_existing_source_test_clears_blocker_and_restores_runnable_supply(tmp_path):+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ service = _service(tmp_path, adapter)+ config = service.store.load()+ source = config.sources[0]+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ )+ config.sources = [source]+ for agent in config.agents.values():+ agent.sources.order = [source.id]++ updated, discovered = asyncio.run(service.test_source(source.id))+ resolved = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert discovered == 1+ assert updated["state"]["status"] == "standby"+ assert resolved.source_id == source.id+++def test_existing_source_test_persists_safe_error_state_on_discovery_failure(+ tmp_path,+):+ adapter = NarrowingCredentialAdapter()+ adapter.fail_discovery = True+ service = _service(tmp_path, adapter)+ source = service.store.load().sources[0]+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.test_source(source.id))++ assert exc_info.value.code == "discovery_failed"+ assert service.store.load().sources[0].state.status == "error"+ assert service.store.load().sources[0].state.detail_key == (+ "models.source.error.unclassified"+ )+++def test_existing_source_test_rejects_empty_discovery_before_recovery(tmp_path):+ adapter = FakeAdapter([])+ service = _service(tmp_path, adapter)+ source = service.store.load().sources[0]+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ )++ async def empty_discovery(vendor, protocol, base_url, credential_ref):+ return ()++ adapter.discover_models = empty_discovery++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.test_source(source.id))++ assert exc_info.value.code == "discovery_failed"+ persisted = service.store.load().sources[0]+ assert persisted.state.status == "error"+ assert persisted.state.detail_key == "models.source.error.unclassified"+++def test_existing_source_test_preserves_health_on_engine_outage(tmp_path):+ adapter = NarrowingCredentialAdapter()+ service = _service(tmp_path, adapter)+ before = _serialized_config(service)++ async def engine_unavailable(vendor, protocol, base_url, credential_ref):+ raise RuntimeError("engine unavailable")++ adapter.discover_models = engine_unavailable+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.test_source("src_primary01"))++ assert exc_info.value.code == "engine_down"+ assert _serialized_config(service) == before++def test_mapping_write_rejects_disabled_unavailable_target(tmp_path):service = _service(tmp_path, FakeAdapter([]))diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex f424d6d02..4b977ceb4 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -356,6 +356,100 @@ def test_claude_oauth_settings_cleanup_failure_fails_web_start(service._create_claude_control_client.assert_not_awaited()+def test_claude_web_start_checks_prerequisites_before_irreversible_callback(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ irreversible_starts = []+ monkeypatch.setattr(+ "core.agent_auth_service.CLAUDE_SDK_AVAILABLE",+ False,+ )++ flow = _run(+ service.start_web_setup(+ "claude",+ force_reset=True,+ on_irreversible_start=lambda: irreversible_starts.append("started"),+ )+ )++ assert flow.state == "failed"+ assert irreversible_starts == []++[email protected]("backend", ["claude", "codex"])+def test_native_web_start_spawn_failure_preserves_irreversible_callback(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+ backend: str,+) -> None:+ irreversible_transitions = []++ async def fail_spawn(*_args, **_kwargs):+ raise FileNotFoundError("configured CLI is unavailable")++ monkeypatch.setattr(asyncio, "create_subprocess_exec", fail_spawn)+ if backend == "claude":+ monkeypatch.setattr(+ "core.agent_auth_service.CLAUDE_SDK_AVAILABLE",+ True,+ )+ service._create_claude_control_client = AsyncMock(+ side_effect=FileNotFoundError("configured CLI is unavailable")+ )++ def prepare_irreversible_start():+ irreversible_transitions.append("prepared")++ def restore():+ irreversible_transitions.append("restored")++ return restore++ flow = _run(+ service.start_web_setup(+ backend,+ force_reset=True,+ on_irreversible_start=prepare_irreversible_start,+ )+ )++ assert flow.state == "failed"+ assert irreversible_transitions == ["prepared", "restored"]+++def test_utility_start_callback_runs_before_subprocess_creation(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ events = []++ class FakeProcess:+ returncode = 0++ async def communicate(self):+ events.append("communicate")+ return b"", b""++ async def spawn(*_args, **_kwargs):+ events.append("spawn")+ return FakeProcess()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)++ result = _run(+ service._run_utility_command(+ "codex",+ "logout",+ prepare_start=lambda: events.append("callback"),+ )+ )++ assert result == (True, None)+ assert events == ["callback", "spawn", "communicate"]++def test_claude_web_oauth_failures_restore_settings_after_batch_finishes(service: AgentAuthService,) -> None:diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex e4059f15e..1a4576cd9 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -24,9 +24,11 @@ def _decode(response: httpx.Response) -> Any:if response.status_code >= 400 or body.get("ok") is not True:code = body.get("error")detail = body.get("detail")+ data = {key: value for key, value in body.items() if key not in {"ok", "error", "detail", "contract_version"}}error = ModelHubError(code if isinstance(code, str) else "engine_down",status=response.status_code if response.status_code >= 400 else 503,+ data=data,)if isinstance(detail, str):error.detail = detail@@ -86,6 +88,18 @@ class ModelHubRemoteService:async def patch_source(self, source_id: str, payload: dict) -> dict:return await _rpc("patch_source", {"source_id": source_id, "patch": payload})+ async def replace_credential(self, source_id: str, payload: object) -> dict:+ return await _rpc(+ "replace_credential",+ {"source_id": source_id, "credential": payload},+ )++ async def reauth_source(self, source_id: str, payload: object) -> dict:+ return await _rpc(+ "reauth_source",+ {"source_id": source_id, "reauth": payload},+ )+async def delete_source(self, source_id: str, *, force: bool = False) -> None:await _rpc("delete_source", {"source_id": source_id, "force": force})diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ba5820370..59605ffc9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3145,6 +3145,7 @@ def _model_hub_error(exc):body = {"ok": False, "contract_version": CONTRACT_VERSION, "error": exc.code}if exc.detail:body["detail"] = exc.detail+ body.update(exc.data)return jsonify(body), exc.status@@ -3189,6 +3190,34 @@ async def model_hub_sources_patch(source_id):return _model_hub_error(exc)[email protected]("/api/models/sources/<source_id>/credential", methods=["PUT"])+async def model_hub_source_credential_put(source_id):+ from core.handlers.model_hub import ModelHubError++ try:+ result = await _model_hub_service().replace_credential(+ source_id,+ _model_hub_json_object(),+ )+ return _model_hub_success(**result)+ except ModelHubError as exc:+ return _model_hub_error(exc)++[email protected]("/api/models/sources/<source_id>/reauth", methods=["POST"])+async def model_hub_source_reauth_post(source_id):+ from core.handlers.model_hub import ModelHubError++ try:+ result = await _model_hub_service().reauth_source(+ source_id,+ _model_hub_json_object(),+ )+ return _model_hub_success(**result)+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/sources/<source_id>", methods=["DELETE"])async def model_hub_sources_delete(source_id):from core.handlers.model_hub import ModelHubError