Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(model-hub): consume channel-aware repair state (#1108)

Call White09b77e768545
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 3d238c5b4..33ec195ed 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -1,4 +1,19 @@
-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.2 (2026-07-23 11:12 +08:00).
+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.4 (2026-07-30 15:36 +08:00).
+
+v1.4 changelog (ref-keyed cleanup convergence):
+- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an
+ already-converged cleanup, making journal replay idempotent across crashes.
+
+v1.3 changelog (owner-approved channel class pass):
+- ``OAuthFlowState.channel`` makes Hub and native CLI success semantics explicit:
+ Hub success carries an engine credential ref; native success never does.
+- Hub flows expose a total five-way retained-material disposition for repair
+ decisions. Native flows pin that disposition to ``none`` because CLI-owned
+ login material never crosses this engine seam.
+- Retained refs are exposed only for flow-owned or orphaned material. Foreign
+ and unknown placements deliberately expose no actionable handle.
+- ``cleanup_orphaned_oauth_material`` is the ref-keyed retry seam: it confirms
+ both auth-file deletions before revoking the only retained handle.
v1.2 changelog (L1 implementation findings — credential & model lifecycle):
- Secret provisioning path closed: ``provision_credential`` moves an API-key
@@ -14,9 +29,10 @@ v1.2 changelog (L1 implementation findings — credential & model lifecycle):
v1.1 changelog (L1 review findings, routed via orchestrator):
- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes
- the pre-created (pending) ``source_id``; a ``success`` ``OAuthFlowState``
- carries the resulting opaque ``credential_ref``. Concurrent same-vendor
- flows can never cross-bind.
+ the pre-created (pending) ``source_id``; a Hub-channel ``success``
+ ``OAuthFlowState`` carries the resulting opaque ``credential_ref``. The
+ later native channel uses the same flow state without an engine ref.
+ Concurrent same-vendor flows can never cross-bind.
- Client binding made enforceable at the engine boundary:
``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +
``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters
@@ -42,7 +58,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Any, AsyncIterator, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence
class EngineHealth(str, Enum):
@@ -107,14 +123,38 @@ class RawCallOutcome:
source_id: str
+class RetainedMaterialDisposition(str, Enum):
+ NONE = "none"
+ FLOW_SOURCE_REF = "flow_source_ref"
+ ORPHAN_REF = "orphan_ref"
+ FOREIGN_SOURCE_REF = "foreign_source_ref"
+ UNKNOWN = "unknown"
+
+
@dataclass(frozen=True)
class OAuthFlowState:
- """Engine-held (experimental hub-channel) subscription OAuth flow state.
+ """Channel-aware subscription OAuth flow state.
Deterministic binding: the flow is created FOR a pre-existing pending
- ``source_id`` and, on ``state == "success"``, carries the opaque
- ``credential_ref`` of the auth record the engine created — L2 binds it to
- that source and never guesses, even with concurrent same-vendor flows.
+ ``source_id``. On the Hub branch, ``credential_ref`` is non-null exactly
+ on success and names the engine auth record L2 binds to that source. On the
+ native CLI branch it is null at every state, including success, because the
+ sanctioned CLI owns its login material. This split mirrors shipped truth in
+ ``core/handlers/model_hub/native_oauth.py:252-289`` and
+ ``tests/test_model_hub_api.py:1147-1149``.
+
+ ``retained_material_disposition`` is total across every state. For Hub
+ terminal states it reports where grant material written by THIS flow
+ remains: ``none`` means cleanup was confirmed or nothing was written;
+ ``flow_source_ref`` names the flow source's ref; ``orphan_ref`` retains a
+ minted cleanup handle; ``foreign_source_ref`` means the single existing ref
+ belongs to another source; and ``unknown`` is the corrupt/ambiguous-state
+ floor, never a default. ``retained_credential_ref`` is non-null exactly for
+ ``flow_source_ref`` and ``orphan_ref``. Foreign and unknown placements
+ deliberately withhold a ref so consumers cannot act on another source or
+ guess among candidates. Hub success pins ``flow_source_ref`` and equality
+ of both refs. Native pins ``none`` and a null retained ref by construction.
+
Mirrors ``oauth-flow.schema.json`` presentation semantics
(runtime-declared; UI renders from ``expects``).
"""
@@ -129,7 +169,13 @@ class OAuthFlowState:
instructions_key: str | None
error_key: str | None
expires_at_iso: str | None
- credential_ref: str | None # set iff state == "success"
+ credential_ref: str | None
+ # Defaults preserve pre-v1.3 call sites until the follow-up service-consumer
+ # lane supplies the discriminator explicitly. Channel-aware producers MUST
+ # set all three fields.
+ channel: Literal["hub", "native_cli"] = "hub"
+ retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONE
+ retained_credential_ref: str | None = None
class InvokeHandle(Protocol):
@@ -159,8 +205,11 @@ class EngineAdapter(Protocol):
# --- gateway ---------------------------------------------------------
async def gateway_token(self) -> str:
- """Local gateway token for backend injection (the ONLY credential
- backends ever receive)."""
+ """Local gateway token for Hub-channel backend injection.
+
+ This is the only credential the managed engine injects. Native-channel
+ turns bypass this gateway and use the sanctioned CLI's own login.
+ """
...
# --- credential provisioning (engine-owned store) ---------------------
@@ -175,15 +224,31 @@ class EngineAdapter(Protocol):
return the opaque ``credential_ref``.
``secret`` is transient: the adapter must never log it; L2 must never
- persist it (config stores refs only). OAuth credentials never pass
+ persist it (config stores refs only). Hub OAuth credentials never pass
through here — they are created engine-side by the OAuth flow and
- surfaced via ``OAuthFlowState.credential_ref``."""
+ surfaced via ``OAuthFlowState.credential_ref``. Native OAuth material
+ remains CLI-owned and has no ref on this seam."""
...
async def revoke_credential(self, credential_ref: str) -> None:
"""Release the stored credential (source deletion / key replacement)."""
...
+ async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:
+ """Retry cleanup for an ``orphan_ref`` without exposing a filename.
+
+ Return true only after the running-engine auth-file delete (when an
+ engine is running), the local auth-file delete, and ref revocation are
+ all confirmed, or when ``credential_ref`` no longer resolves. Absence
+ is convergence, not a lenient fallback: this operation's ordering
+ invariant revokes the ref only after both auth-file deletions are
+ confirmed, so an absent ref proves that no material remains behind it.
+ A never-created ref satisfies the same postcondition vacuously. Return
+ false on any partial failure and retain the ref for a later retry. The
+ handle must never be destroyed while material may remain behind it.
+ """
+ ...
+
# --- source registry (L2 calls on every config change) ---------------
async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None: ...
@@ -199,7 +264,7 @@ class EngineAdapter(Protocol):
sync); does not require or create a source binding."""
...
- # --- engine-held subscription OAuth (experimental flag only) ----------
+ # --- subscription OAuth (channel-specific ownership) ------------------
async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState: ...
async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...
diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.py
index ec3603f0e..773f816d5 100644
--- a/core/handlers/model_hub/native_oauth.py
+++ b/core/handlers/model_hub/native_oauth.py
@@ -8,7 +8,7 @@ from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Mapping, Protocol
-from .adapter import OAuthFlowState
+from .adapter import OAuthFlowState, RetainedMaterialDisposition
from .events import contains_credential_material
from .oauth import NativeOAuthSourceStatus, NativeOAuthUnavailableError
@@ -286,6 +286,9 @@ class AgentAuthNativeOAuthAdapter:
error_key=error_key,
expires_at_iso=binding.expires_at_iso,
credential_ref=None,
+ channel="native_cli",
+ retained_material_disposition=RetainedMaterialDisposition.NONE,
+ retained_credential_ref=None,
)
async def _read_source_status(self, backend: str) -> NativeOAuthSourceStatus:
diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.py
index 1740d23cc..821067fab 100644
--- a/core/handlers/model_hub/revocations.py
+++ b/core/handlers/model_hub/revocations.py
@@ -8,12 +8,24 @@ import tempfile
import threading
from dataclasses import dataclass
from pathlib import Path
+from typing import Literal
+
+
+RevocationOperation = Literal[
+ "revoke_credential",
+ "cleanup_orphaned_oauth_material",
+]
+_REVOCATION_OPERATIONS = {
+ "revoke_credential",
+ "cleanup_orphaned_oauth_material",
+}
@dataclass(frozen=True)
class PendingCredentialRevocation:
source_id: str
credential_ref: str
+ operation: RevocationOperation = "revoke_credential"
class CredentialRevocationJournal:
@@ -36,17 +48,24 @@ class CredentialRevocationJournal:
PendingCredentialRevocation(
source_id=item["source_id"],
credential_ref=item["credential_ref"],
+ operation=item.get("operation", "revoke_credential"),
)
for item in payload
if isinstance(item, dict)
and isinstance(item.get("source_id"), str)
and isinstance(item.get("credential_ref"), str)
+ and item.get("operation", "revoke_credential")
+ in _REVOCATION_OPERATIONS
]
def _write(self, entries: list[PendingCredentialRevocation]) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
payload = [
- {"source_id": entry.source_id, "credential_ref": entry.credential_ref}
+ {
+ "source_id": entry.source_id,
+ "credential_ref": entry.credential_ref,
+ "operation": entry.operation,
+ }
for entry in entries
]
content = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
@@ -58,10 +77,20 @@ class CredentialRevocationJournal:
os.chmod(temp_name, 0o600)
os.replace(temp_name, self.path)
- def add(self, source_id: str, credential_ref: str) -> None:
+ def add(
+ self,
+ source_id: str,
+ credential_ref: str,
+ *,
+ operation: RevocationOperation = "revoke_credential",
+ ) -> None:
with self._lock:
entries = self._read()
- entry = PendingCredentialRevocation(source_id, credential_ref)
+ entry = PendingCredentialRevocation(
+ source_id,
+ credential_ref,
+ operation,
+ )
if entry not in entries:
entries.append(entry)
self._write(entries)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 1f13d3942..8e0e07026 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -41,6 +41,7 @@ from .adapter import (
OriginNotAllowedError,
RawCallOutcome,
RawOutcomeKind,
+ RetainedMaterialDisposition,
SourceBinding,
)
from .classification import ResolutionDecision, classify_outcome
@@ -581,11 +582,25 @@ class ModelHubService:
except OSError:
pass
continue
- try:
- await self.adapter.revoke_credential(pending.credential_ref)
- except Exception as error:
- if not self._credential_was_already_revoked(error):
+ if pending.operation == "cleanup_orphaned_oauth_material":
+ try:
+ cleaned = (
+ await self.adapter.cleanup_orphaned_oauth_material(
+ pending.credential_ref
+ )
+ )
+ except Exception:
continue
+ if not cleaned:
+ continue
+ else:
+ 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,
@@ -613,6 +628,16 @@ class ModelHubService:
def _oauth_channel(self, flow_id: str) -> OAuthChannel:
return self._oauth_binding(flow_id).channel
+ @staticmethod
+ def _is_hub_unsuccessful_terminal(
+ binding: OAuthFlowBinding,
+ flow: OAuthFlowState,
+ ) -> bool:
+ return (
+ binding.channel == "hub"
+ and flow.state in {"failed", "cancelled"}
+ )
+
def _oauth_binding(self, flow_id: str) -> OAuthFlowBinding:
binding = self.oauth_flows.binding(flow_id)
if binding is None:
@@ -656,7 +681,11 @@ class ModelHubService:
# Resolution telemetry is best effort and must never affect routing.
logger.warning("Failed to persist Model Hub resolution event")
- async def _rollback_credential(self, source_id: str, credential_ref: str) -> None:
+ async def _rollback_credential(
+ self,
+ source_id: str,
+ credential_ref: str,
+ ) -> bool:
journaled = False
try:
self.revocations.add(source_id, credential_ref)
@@ -667,14 +696,15 @@ class ModelHubService:
try:
await self.adapter.revoke_credential(credential_ref)
except Exception:
- return
+ return journaled
if not journaled:
- return
+ return True
try:
self.revocations.remove(source_id, credential_ref)
except OSError:
# A replayed revoke is safer than losing the only durable ref.
pass
+ return True
async def _rollback_replacement(
self,
@@ -692,6 +722,38 @@ class ModelHubService:
if replacement_ref != old_credential_ref:
await self._rollback_credential(source_id, replacement_ref)
+ async def _cleanup_orphaned_hub_material(
+ self,
+ source_id: str,
+ credential_ref: str,
+ ) -> None:
+ journaled = False
+ try:
+ self.revocations.add(
+ source_id,
+ credential_ref,
+ operation="cleanup_orphaned_oauth_material",
+ )
+ except OSError:
+ pass
+ else:
+ journaled = True
+ try:
+ cleaned = await self.adapter.cleanup_orphaned_oauth_material(
+ credential_ref
+ )
+ except Exception:
+ cleaned = False
+ if not cleaned:
+ if not journaled:
+ raise ModelHubError("engine_down", status=503)
+ return
+ if journaled:
+ try:
+ self.revocations.remove(source_id, credential_ref)
+ except OSError:
+ pass
+
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.
@@ -776,10 +838,25 @@ class ModelHubService:
if config.agents[backend].sources.policy == "follow" and source_id in config.effective_source_order(backend)
]
+ def _skipped_by(self, source_id: str) -> list[dict]:
+ config = self.store.load()
+ source = self._source(config, source_id)
+ return [
+ {
+ "backend": backend,
+ "reason": "custom_order",
+ }
+ for backend in MODEL_HUB_BACKENDS
+ if self._eligible_for_agent(source, backend)
+ and config.agents[backend].sources.policy == "custom"
+ and source_id not in config.effective_source_order(backend)
+ ]
+
def _source_creation_result(self, source: dict) -> dict:
return {
"source": source,
"adopted_by": self._adopted_by(source["id"]),
+ "skipped_by": self._skipped_by(source["id"]),
}
async def _create_oauth_source(
@@ -942,7 +1019,22 @@ class ModelHubService:
else None
),
expires_at_iso=None,
- credential_ref=source.credential_ref,
+ credential_ref=(
+ source.credential_ref
+ if binding.channel == "hub"
+ else None
+ ),
+ channel=binding.channel,
+ retained_material_disposition=(
+ RetainedMaterialDisposition.FLOW_SOURCE_REF
+ if binding.channel == "hub"
+ else RetainedMaterialDisposition.NONE
+ ),
+ retained_credential_ref=(
+ source.credential_ref
+ if binding.channel == "hub"
+ else None
+ ),
)
def _completed_reauth_result(
@@ -1202,6 +1294,84 @@ class ModelHubService:
self.store.save(config)
return config
+ async def _materialize_failed_hub_reauth(
+ self,
+ binding: OAuthFlowBinding,
+ flow: OAuthFlowState,
+ *,
+ config: ModelHubConfig | None = None,
+ ) -> ModelHubConfig | None:
+ disposition = flow.retained_material_disposition
+ if disposition in {
+ RetainedMaterialDisposition.NONE,
+ RetainedMaterialDisposition.FOREIGN_SOURCE_REF,
+ }:
+ return config
+ if disposition in {
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ RetainedMaterialDisposition.UNKNOWN,
+ }:
+ return self._fail_closed_hub_reauth(
+ binding,
+ config=config,
+ )
+ if disposition == RetainedMaterialDisposition.ORPHAN_REF:
+ if (
+ binding.source_id is None
+ or flow.retained_credential_ref is None
+ ):
+ raise ModelHubError("engine_down", status=503)
+ await self._cleanup_orphaned_hub_material(
+ binding.source_id,
+ flow.retained_credential_ref,
+ )
+ return config
+ raise ModelHubError("engine_down", status=503)
+
+ async def _materialize_failed_hub_flow(
+ self,
+ binding: OAuthFlowBinding,
+ flow: OAuthFlowState,
+ *,
+ config: ModelHubConfig | None = None,
+ ) -> ModelHubConfig | None:
+ if binding.intent == "reauth":
+ return await self._materialize_failed_hub_reauth(
+ binding,
+ flow,
+ config=config,
+ )
+ if (
+ flow.retained_material_disposition
+ == RetainedMaterialDisposition.FLOW_SOURCE_REF
+ ):
+ if (
+ binding.source_id is None
+ or flow.retained_credential_ref is None
+ ):
+ raise ModelHubError("engine_down", status=503)
+ cleanup_secured = await self._rollback_credential(
+ binding.source_id,
+ flow.retained_credential_ref,
+ )
+ if not cleanup_secured:
+ raise ModelHubError("engine_down", status=503)
+ return config
+ if (
+ flow.retained_material_disposition
+ == RetainedMaterialDisposition.ORPHAN_REF
+ ):
+ if (
+ binding.source_id is None
+ or flow.retained_credential_ref is None
+ ):
+ raise ModelHubError("engine_down", status=503)
+ await self._cleanup_orphaned_hub_material(
+ binding.source_id,
+ flow.retained_credential_ref,
+ )
+ return config
+
async def _materialize_completed_oauth(
self,
flow_id: str,
@@ -1210,15 +1380,14 @@ class ModelHubService:
) -> tuple[OAuthFlowState, dict | None]:
if flow.state != "success":
if (
- flow.state == "failed"
- and binding.intent == "reauth"
- and binding.channel == "hub"
+ self._is_hub_unsuccessful_terminal(binding, flow)
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)
+ await self._materialize_failed_hub_flow(
+ binding,
+ flow,
+ )
return flow, None
if binding.source_id is None or binding.vendor is None:
raise ModelHubError("flow_not_found", status=404)
@@ -1814,6 +1983,58 @@ class ModelHubService:
for model in source.models
}
+ def _mapping_target_sources(
+ self,
+ config: ModelHubConfig,
+ backend: str,
+ model_id: str,
+ ) -> list[str]:
+ by_id = {source.id: source for source in config.sources}
+ return [
+ source_id
+ for source_id in config.recommended_source_order(backend)
+ if any(
+ model.id == model_id
+ for model in by_id[source_id].models
+ )
+ ]
+
+ def _opencode_target_sources(
+ self,
+ config: ModelHubConfig,
+ identifier: str,
+ ) -> list[str]:
+ by_id = {source.id: source for source in config.sources}
+ return [
+ source_id
+ for source_id in config.recommended_source_order("opencode")
+ if any(
+ opencode_model_id(by_id[source_id].vendor, model.id)
+ == identifier
+ for model in by_id[source_id].models
+ )
+ ]
+
+ @staticmethod
+ def _enroll_target_sources(
+ config: ModelHubConfig,
+ agent: ModelHubAgentSupplyConfig,
+ target_source_groups: list[list[str]],
+ ) -> None:
+ effective_order = config.effective_source_order(agent.backend)
+ enrolled = set(effective_order)
+ appended = []
+ for source_ids in target_source_groups:
+ if any(source_id in enrolled for source_id in source_ids):
+ continue
+ selected_source_id = source_ids[0]
+ enrolled.add(selected_source_id)
+ appended.append(selected_source_id)
+ if not appended:
+ return
+ agent.sources.policy = "custom"
+ agent.sources.order = [*effective_order, *appended]
+
def _available_opencode_identifiers(self, config: ModelHubConfig) -> set[str]:
return {
opencode_model_id(source.vendor, model.id)
@@ -1880,12 +2101,36 @@ class ModelHubService:
}
for model_id in menu_model_ids
]
+ selected_model_id = (
+ (resolution.requested_model or None)
+ if agent.mode == "hub"
+ else None
+ )
+ current_chain_source_ids = {
+ source.id
+ for source in resolution.matching_sources
+ }
sources = (
{
"policy": agent.sources.policy,
"order": config.effective_source_order(agent.backend),
"eligibility": [
- self._source_eligibility(source, agent.backend)
+ {
+ **self._source_eligibility(
+ source,
+ agent.backend,
+ ),
+ "in_current_model_chain": (
+ source.id in current_chain_source_ids
+ if selected_model_id is not None
+ else None
+ ),
+ "process_availability_reason": (
+ "native_cli_unavailable"
+ if source.id in unavailable_source_ids
+ else None
+ ),
+ }
for source in sorted(config.sources, key=lambda item: item.id)
],
}
@@ -1924,7 +2169,7 @@ class ModelHubService:
return {
**agent.to_payload(),
"selected_by_agent": selected_by_agent,
- "selected_model_id": (resolution.requested_model or None) if agent.mode == "hub" else None,
+ "selected_model_id": selected_model_id,
"current": current,
"sources": sources,
"supply_status": (
@@ -1962,9 +2207,25 @@ class ModelHubService:
parsed = [ModelHubMappingConfig.from_payload(mapping) for mapping in mappings]
except ValueError as exc:
raise ModelHubError("mapping_target_unavailable") from exc
- available = self._available_model_ids(config, backend)
- if any(mapping.target_model_id not in available for mapping in parsed):
+ target_sources = {
+ mapping.target_model_id: self._mapping_target_sources(
+ config,
+ backend,
+ mapping.target_model_id,
+ )
+ for mapping in parsed
+ }
+ if any(not source_ids for source_ids in target_sources.values()):
raise ModelHubError("mapping_target_unavailable")
+ self._enroll_target_sources(
+ config,
+ agent,
+ [
+ target_sources[mapping.target_model_id]
+ for mapping in parsed
+ if mapping.enabled
+ ],
+ )
agent.mappings = parsed
self.store.save(config)
return self._agent_payload(config, agent)
@@ -1977,9 +2238,23 @@ class ModelHubService:
parsed = ModelHubMenuConfig.from_payload(cast(dict, menu))
except (TypeError, ValueError) as exc:
raise ModelHubError("mapping_target_unavailable") from exc
- available = self._available_opencode_identifiers(config)
- if any(identifier not in available for identifier in parsed.checked):
+ target_sources = {
+ identifier: self._opencode_target_sources(
+ config,
+ identifier,
+ )
+ for identifier in parsed.checked
+ }
+ if any(not source_ids for source_ids in target_sources.values()):
raise ModelHubError("mapping_target_unavailable")
+ self._enroll_target_sources(
+ config,
+ agent,
+ [
+ target_sources[identifier]
+ for identifier in parsed.checked
+ ],
+ )
agent.menu = parsed
self.store.save(config)
return self._agent_payload(config, agent)
@@ -2527,13 +2802,17 @@ class ModelHubService:
intent="reauth",
)
}
- if (
- pending_flow.state == "failed"
- and pending_binding.channel == "hub"
+ if self._is_hub_unsuccessful_terminal(
+ pending_binding,
+ pending_flow,
):
- config = self._fail_closed_hub_reauth(
- pending_binding,
- config=config,
+ config = (
+ await self._materialize_failed_hub_reauth(
+ pending_binding,
+ pending_flow,
+ config=config,
+ )
+ or config
)
source = self._source(config, source_id)
try:
@@ -2753,10 +3032,9 @@ class ModelHubService:
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"
+ if flow.state == "success" or self._is_hub_unsuccessful_terminal(
+ binding,
+ flow,
):
terminal = (binding, flow)
else:
@@ -2764,14 +3042,31 @@ class ModelHubService:
self._oauth_adapter(binding.channel).cancel_oauth(flow_id),
flow_id=flow_id,
)
- self.oauth_flows.forget(flow_id)
+ if binding.channel == "hub":
+ cancelled = await self._oauth_status(
+ flow_id,
+ binding.channel,
+ )
+ if (
+ cancelled.state == "success"
+ or self._is_hub_unsuccessful_terminal(
+ binding,
+ cancelled,
+ )
+ ):
+ terminal = (binding, cancelled)
+ else:
+ self.oauth_flows.forget(flow_id)
+ else:
+ self.oauth_flows.forget(flow_id)
if terminal is not None:
+ binding, flow = terminal
await self._materialize_completed_oauth(
flow_id,
- terminal[0],
- terminal[1],
+ binding,
+ flow,
)
- if terminal[1].state == "failed":
+ if flow.state != "success":
async with self._mutation_lock:
try:
self.oauth_flows.forget(flow_id)
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 01b59155e..f32a7cfa0 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -2,9 +2,10 @@
Status: **FROZEN v4 (targeted)** · 2026-07-30 · change only via orchestrator
Advances `agent-chain`, `probe-result`, and `turn-provenance` from contract
-version 3 to 4. The same-assumption audit makes prose-only corrections in
-`source` and `agent-supply`; the versionless `resolution-event` adds the
-request-scoped `permission_denied` cause.
+version 3 to 4. Later targeted-v4 amendments retain those pins while tightening
+the channel-aware adapter seam and grafting derived truth onto the live
+AgentSupply/source-creation projections. The versionless `resolution-event`
+includes the request-scoped `permission_denied` cause.
Derived from: spec v2 (`../model-hub.md`), implementation plan
(`../model-hub-implementation.md`),
spike S1 engine survey (`docs/plans/model-hub-engine-survey.md`),
@@ -107,6 +108,15 @@ order after any mutation; clients never compute partial reorders.
`permission_denied` is an attempt failure, mirrored into provenance and legal
only on a switch event; it has no Source-state `detail_key` and never mutates
source health.
+- **Targeted v4 process instance trail — entry 4 (channel class pass).** Owner
+ Plan A approval at 2026-07-30 09:47 authorized the class-level correction
+ proved necessary by the five-stop v4c evidence history, rooted in finding
+ `3675528561`. The earlier v4a audit missed `adapter-interface.py` and its
+ global success-implies-ref assertion; this dedicated commit repairs that
+ omission by splitting the seam per channel, carries the retained-material
+ discriminator into both producers, and audits every remaining contract file.
+ It is evidence-pinned, delivered into the implementing lane rather than by
+ chat, and remains owner-vetoable.
- Contract tests (implementation plan §5) validate both directions against
these schemas.
@@ -274,7 +284,7 @@ loads it and mutation-tests every comparable row.
| M5 | the supply-state taxonomy | `agent-supply.schema.json` → `supply_status` | `named_agents[].supply_status`; `agent-chain.schema.json` → `supply_state`; `turn-provenance.schema.json` → `model_supply_state` | `projection` |
| M6 | backend identifiers | `agent-supply.schema.json` → `backend` | `agent-chain.schema.json` and `probe-result.schema.json` → `backend`; `turn-provenance.schema.json` and `resolution-event.schema.json` → `agent` (`system` is the declared event-only extra) | `equality` |
| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; `agent-chain.schema.json` → `chain[].channel`; `probe-result.schema.json` → `channel`; all four turn-provenance attempt slots | `equality` |
-| M8 | native CLI process availability | `agent-chain.schema.json` → `chain[].reason` (`native_cli_unavailable`) | `probe-result.schema.json` → native not-ready `error` (`models.probe.native_cli_unavailable`) | `mapping` |
+| M8 | native CLI process availability | `agent-chain.schema.json` → `chain[].reason` (`native_cli_unavailable`) | `agent-supply.schema.json` → `sources.eligibility[].process_availability_reason` (same bare token); `probe-result.schema.json` → native not-ready `error` (`models.probe.native_cli_unavailable`) | `mapping` |
| N1 | source recommendation rule | `agent-supply.schema.json` → `sources.policy` | — | `none` |
What the rules mean, and why the non-equality rules differ:
@@ -299,9 +309,10 @@ What the rules mean, and why the non-equality rules differ:
`permission_denied` belongs here because it describes the failed request
attempt, but deliberately does not join M4: the preserved machine code does not
prove a source-global credential or account state.
-- **`mapping`** — M8 is one concept in two field conventions: a bare classifier in
- the chain and an i18n key in the probe error slot. The explicit one-to-one map is
- checked in both directions; adding a spelling on either side fails until paired.
+- **`mapping`** — M8 is one concept across two field conventions: the same bare
+ classifier in chain and AgentSupply inventory, plus an i18n key in the probe
+ error slot. Per-target one-to-one maps are checked in both directions; adding a
+ spelling at any of the three surfaces fails until the row binds it.
- **`bijection`** — M4 checks both sets and each explicit cause→detail-key pair;
a permuted pairing therefore fails even when the two sets still match.
- **`none`** — registered as non-comparable, with the reason. N1 is a pointer to a
@@ -312,17 +323,42 @@ What the rules mean, and why the non-equality rules differ:
| File | Consumers |
| --- | --- |
| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action`, immutable `created_at`, optional `usage.projected_exhaust_at`. Targeted v4 audit changes no shape: healthy source state and a lapsed `retry_at` do not assert process-local native CLI availability. No ordering field, ever. |
-| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. Targeted v4 audit changes no shape: `supply_status` is derived from complete process-aware runnability, so unavailable native CLI supply is `interrupted`, not cooldown-only `waiting`. Hub with no pinned selection remains null throughout. |
+| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. The channel class pass extends the complete eligibility inventory with current-chain membership and process availability, retaining non-members so one projection serves both the Agent row and all-sources drawer. |
| `agent-chain.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain and preserves visibility/order for blocked members. Each item now distinguishes source-global `health` from resolve-time channel availability: `runnable = health-permits AND process-available`; Hub availability is definitionally true, while an unavailable native CLI item at any health stays dimmed in place with `reason: native_cli_unavailable`. Cooldown plus unavailable is `interrupted`, not `waiting`. |
| `probe-result.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. The probe selects the first runnable item; unavailable chain items are skipped. Hub keeps v3's completed-request truth table. Native CLI re-verifies process readiness, never claims completion evidence, and pins `latency_ms: null` in both directions. It reads the requested model's `supply_state`, never `supply_status`. |
| `turn-provenance.schema.json` | L2 API, L3 writer. v4 adds request-scoped `permission_denied` to failed attempts without changing the exact-attribution rule. The FSM-truth `canceled` outcome keeps its reason-free `canceled_attempt` slot. Direct and ambiguous absence remain route errors in `api.md`. |
| `resolution-event.schema.json` | L2 emitter, L4 UI. The versionless feed adds `permission_denied` only for a model-scoped switch; it cannot describe cooldown, recovery, or needs-action source state. The record stays single-grained with impact derived live. |
-| `oauth-flow.schema.json` | L2, L4 UI, L1 engine adapter |
+| `oauth-flow.schema.json` | L2, L4 UI. Remains presentation-only: channel is public, while engine credential refs and retained-material disposition stay on the service seam because the UI never consumes them. |
| `migration-scan.schema.json` | L6, L5 UI. Unchanged by the v2 ruling — native-config import is an onboarding feature, not a priority mechanism. |
| `runtime-dependency.schema.json` | L1, L2 status API, L7 guards. **URL policy (orchestrator, 07-23 12:05):** the example URLs are placeholders; L1 ships with upstream release URLs + SHA256 integrity verification. Availability guard = L7/orchestrator deliverable BEFORE GA: mirror the pinned assets into Avibe-owned release storage (same manifest-verified backup/recovery pattern as Show Runtime, per repo release rules), then point the manifest at the mirror with upstream recorded as provenance. SHA256s never change (same bytes). L1 must NOT build the mirror or touch the Show Runtime guard. **Platform expansion (07-23 13:13):** linux-arm64 / darwin-x64 assets get pinned (+ schema platform-enum rev) together with the mirror work at L7; until then unsupported hosts fail closed, Direct = escape hatch (L1's `model_hub_engine_platform_unsupported` coverage is the intended behavior). **Cross-vendor note (07-29):** if the v2.1 cross-vendor spike (spec §10.4) concludes that a conversion pair needs a CPA plugin or a different engine build, that lands here as a pin + SHA256 revision with mirrored assets published before the manifest moves — never as user-facing configuration. |
-| `api.md` | All route and envelope contracts. Targeted v4 keeps the shared envelope at v3 while documenting nested v4 chain/probe channel truth, orthogonal native availability, first-runnable probe selection, and stale readiness re-verification. The remaining route contracts are unchanged. |
+| `api.md` | All route and envelope contracts. Targeted v4 keeps the shared envelope at v3 while documenting channel truth, the five-way OAuth repair partition, complete AgentSupply source signals, explicit skipped custom orders, and mapping/menu enrollment. |
| `opencode-overlay.md` | L3, L7 (identifier-stability tests). Identifiers stay stable across per-agent reordering — a source is never encoded into the provider segment. |
-| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). Dual-copy rule: both lanes copy VERBATIM to `core/handlers/model_hub/adapter.py` in their branches — byte-identical, merge is a no-op. Added 07-23 10:55 after L1 raised the ordering race; **v1.1 07-23 11:05**: +OAuth surface with deterministic source binding (`start_oauth(source_id)` → success carries `credential_ref`), +`allowed_origins`/`invoke(origin)`/`OriginNotAllowedError` (both from L1 review findings). Unchanged by v2: candidate walking and error classification stay Python-side, so moving ordering from global to per-agent needs no adapter or engine change (spec §8). |
+| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). v1.3 makes OAuth flow success channel-aware and adds the total retained-material disposition. The contract and `core/handlers/model_hub/adapter.py` remain byte-identical by mechanical guard. |
+
+## Full channel audit (owner Plan A)
+
+The audit question was fixed: does this file assume every supply/login path is
+Hub-engine-owned, or collapse source-global state into serving-process truth?
+
+| File | Disposition |
+| --- | --- |
+| `README.md` | **Fixed.** Records the missed adapter seam, the owner authorization chain, M8's AgentSupply spelling, and this complete audit. |
+| `adapter-interface.py` | **Fixed.** Replaces global success/ref semantics with Hub and native branches; adds the five retained-material placements. |
+| `agent-chain.schema.json` | **Audited clean.** v4a already keeps channel, health, availability, and runnability orthogonal at every chain position. |
+| `agent-supply.schema.json` | **Fixed.** Complete per-source inventory now carries current-chain membership plus the per-process native blocker without dropping non-members. |
+| `api.md` | **Fixed.** Adds the five-arm repair consumer contract, source-signal grain, `skipped_by`, and mapping enrollment; existing probe text already says readiness is not completion. |
+| `migration-scan.schema.json` | **Audited clean.** Each import item already declares `supply_channel`; scanning native config never claims engine ownership. |
+| `mirror-registry.json` | **Fixed.** M8 binds chain, AgentSupply, and probe spellings as one process-availability concept. |
+| `oauth-flow.schema.json` | **Fixed.** Pins the user-wire/service-seam exclusion and makes source binding channel-neutral; refs remain off the wire. |
+| `opencode-overlay.md` | **Audited clean.** Provider/model identifiers remain source- and channel-independent, so no gateway ownership is implied. |
+| `probe-result.schema.json` | **Audited clean.** Hub records completion evidence; native records readiness with null latency in both directions. |
+| `resolution-event.schema.json` | **Audited clean.** Events classify observed attempts and state changes without deriving process availability from global health. |
+| `runtime-dependency.schema.json` | **Audited clean.** It describes the optional managed Hub engine itself, not native CLI availability or login ownership. |
+| `source.schema.json` | **Fixed.** The existing channel/ref and global-health boundaries hold; `oauth_expired` now explicitly covers unknown retained placement. |
+| `turn-provenance.schema.json` | **Audited clean.** Every attempt-bearing slot already carries `channel`; exact attribution never assumes gateway execution. |
+| `core/handlers/model_hub/adapter.py` | **Fixed mechanically.** Byte-identical v1.3 copy of the contract seam. |
+| `core/handlers/model_hub/native_oauth.py` | **Fixed.** Every produced flow is tagged `native_cli`, carries no engine ref, and pins retained material to `none`. |
+| `vibe/model_hub_runtime/adapter.py` | **Fixed.** Every Hub terminal path reports a proved disposition and cleanup retains the ref until both auth-file deletions are confirmed. |
## Security invariants (from S1/S2, non-negotiable)
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 3d238c5b4..33ec195ed 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -1,4 +1,19 @@
-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.2 (2026-07-23 11:12 +08:00).
+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.4 (2026-07-30 15:36 +08:00).
+
+v1.4 changelog (ref-keyed cleanup convergence):
+- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an
+ already-converged cleanup, making journal replay idempotent across crashes.
+
+v1.3 changelog (owner-approved channel class pass):
+- ``OAuthFlowState.channel`` makes Hub and native CLI success semantics explicit:
+ Hub success carries an engine credential ref; native success never does.
+- Hub flows expose a total five-way retained-material disposition for repair
+ decisions. Native flows pin that disposition to ``none`` because CLI-owned
+ login material never crosses this engine seam.
+- Retained refs are exposed only for flow-owned or orphaned material. Foreign
+ and unknown placements deliberately expose no actionable handle.
+- ``cleanup_orphaned_oauth_material`` is the ref-keyed retry seam: it confirms
+ both auth-file deletions before revoking the only retained handle.
v1.2 changelog (L1 implementation findings — credential & model lifecycle):
- Secret provisioning path closed: ``provision_credential`` moves an API-key
@@ -14,9 +29,10 @@ v1.2 changelog (L1 implementation findings — credential & model lifecycle):
v1.1 changelog (L1 review findings, routed via orchestrator):
- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes
- the pre-created (pending) ``source_id``; a ``success`` ``OAuthFlowState``
- carries the resulting opaque ``credential_ref``. Concurrent same-vendor
- flows can never cross-bind.
+ the pre-created (pending) ``source_id``; a Hub-channel ``success``
+ ``OAuthFlowState`` carries the resulting opaque ``credential_ref``. The
+ later native channel uses the same flow state without an engine ref.
+ Concurrent same-vendor flows can never cross-bind.
- Client binding made enforceable at the engine boundary:
``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +
``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters
@@ -42,7 +58,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Any, AsyncIterator, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence
class EngineHealth(str, Enum):
@@ -107,14 +123,38 @@ class RawCallOutcome:
source_id: str
+class RetainedMaterialDisposition(str, Enum):
+ NONE = "none"
+ FLOW_SOURCE_REF = "flow_source_ref"
+ ORPHAN_REF = "orphan_ref"
+ FOREIGN_SOURCE_REF = "foreign_source_ref"
+ UNKNOWN = "unknown"
+
+
@dataclass(frozen=True)
class OAuthFlowState:
- """Engine-held (experimental hub-channel) subscription OAuth flow state.
+ """Channel-aware subscription OAuth flow state.
Deterministic binding: the flow is created FOR a pre-existing pending
- ``source_id`` and, on ``state == "success"``, carries the opaque
- ``credential_ref`` of the auth record the engine created — L2 binds it to
- that source and never guesses, even with concurrent same-vendor flows.
+ ``source_id``. On the Hub branch, ``credential_ref`` is non-null exactly
+ on success and names the engine auth record L2 binds to that source. On the
+ native CLI branch it is null at every state, including success, because the
+ sanctioned CLI owns its login material. This split mirrors shipped truth in
+ ``core/handlers/model_hub/native_oauth.py:252-289`` and
+ ``tests/test_model_hub_api.py:1147-1149``.
+
+ ``retained_material_disposition`` is total across every state. For Hub
+ terminal states it reports where grant material written by THIS flow
+ remains: ``none`` means cleanup was confirmed or nothing was written;
+ ``flow_source_ref`` names the flow source's ref; ``orphan_ref`` retains a
+ minted cleanup handle; ``foreign_source_ref`` means the single existing ref
+ belongs to another source; and ``unknown`` is the corrupt/ambiguous-state
+ floor, never a default. ``retained_credential_ref`` is non-null exactly for
+ ``flow_source_ref`` and ``orphan_ref``. Foreign and unknown placements
+ deliberately withhold a ref so consumers cannot act on another source or
+ guess among candidates. Hub success pins ``flow_source_ref`` and equality
+ of both refs. Native pins ``none`` and a null retained ref by construction.
+
Mirrors ``oauth-flow.schema.json`` presentation semantics
(runtime-declared; UI renders from ``expects``).
"""
@@ -129,7 +169,13 @@ class OAuthFlowState:
instructions_key: str | None
error_key: str | None
expires_at_iso: str | None
- credential_ref: str | None # set iff state == "success"
+ credential_ref: str | None
+ # Defaults preserve pre-v1.3 call sites until the follow-up service-consumer
+ # lane supplies the discriminator explicitly. Channel-aware producers MUST
+ # set all three fields.
+ channel: Literal["hub", "native_cli"] = "hub"
+ retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONE
+ retained_credential_ref: str | None = None
class InvokeHandle(Protocol):
@@ -159,8 +205,11 @@ class EngineAdapter(Protocol):
# --- gateway ---------------------------------------------------------
async def gateway_token(self) -> str:
- """Local gateway token for backend injection (the ONLY credential
- backends ever receive)."""
+ """Local gateway token for Hub-channel backend injection.
+
+ This is the only credential the managed engine injects. Native-channel
+ turns bypass this gateway and use the sanctioned CLI's own login.
+ """
...
# --- credential provisioning (engine-owned store) ---------------------
@@ -175,15 +224,31 @@ class EngineAdapter(Protocol):
return the opaque ``credential_ref``.
``secret`` is transient: the adapter must never log it; L2 must never
- persist it (config stores refs only). OAuth credentials never pass
+ persist it (config stores refs only). Hub OAuth credentials never pass
through here — they are created engine-side by the OAuth flow and
- surfaced via ``OAuthFlowState.credential_ref``."""
+ surfaced via ``OAuthFlowState.credential_ref``. Native OAuth material
+ remains CLI-owned and has no ref on this seam."""
...
async def revoke_credential(self, credential_ref: str) -> None:
"""Release the stored credential (source deletion / key replacement)."""
...
+ async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:
+ """Retry cleanup for an ``orphan_ref`` without exposing a filename.
+
+ Return true only after the running-engine auth-file delete (when an
+ engine is running), the local auth-file delete, and ref revocation are
+ all confirmed, or when ``credential_ref`` no longer resolves. Absence
+ is convergence, not a lenient fallback: this operation's ordering
+ invariant revokes the ref only after both auth-file deletions are
+ confirmed, so an absent ref proves that no material remains behind it.
+ A never-created ref satisfies the same postcondition vacuously. Return
+ false on any partial failure and retain the ref for a later retry. The
+ handle must never be destroyed while material may remain behind it.
+ """
+ ...
+
# --- source registry (L2 calls on every config change) ---------------
async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None: ...
@@ -199,7 +264,7 @@ class EngineAdapter(Protocol):
sync); does not require or create a source binding."""
...
- # --- engine-held subscription OAuth (experimental flag only) ----------
+ # --- subscription OAuth (channel-specific ownership) ------------------
async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState: ...
async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index ce84b45af..826744019 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -55,7 +55,7 @@
},
"eligibility": {
"type": ["array", "null"],
- "description": "v2: server-authoritative eligibility, one entry per existing source (spec §4.4). Exists so the UI chokepoint isSourceEligible (ui/src/components/settings/models/menus/identifiers.ts, self-documented as ESCALATED) becomes a pure projection instead of a second hand-written copy of the compatibility matrix. Drives the 未启用 / 不适用 sections of the agent drawer. REQUIRED AND NON-NULL whenever `sources` is an object (07-29, review round 5) — see the conditional at the bottom of this file; a null here would hand the matrix back to the UI, which is the duplication this projection deletes. Two coverage rules the schema cannot state and a mechanical guard therefore must (api.md → Serializer completeness): one entry per EXISTING source, and every id in `order` present with `eligible: true`, since a source this backend cannot use must never appear in the order it spends.",
+ "description": "v2: server-authoritative per-source inventory, one entry per existing source (spec §4.4). Eligibility makes the UI chokepoint isSourceEligible (ui/src/components/settings/models/menus/identifiers.ts, self-documented as ESCALATED) a pure projection instead of a second hand-written copy of the compatibility matrix. The channel class pass adds two request-grain signals to the SAME complete inventory: `in_current_model_chain` says whether this source supplies the selected route's current model, and `process_availability_reason` carries the serving process's native CLI readiness blocker. Keeping non-members with `in_current_model_chain: false` is load-bearing: embedding only AgentChain would omit an in-order source that does not supply the current model, taking the drawer's availability fact with it. REQUIRED AND NON-NULL whenever `sources` is an object (07-29, review round 5) — see the conditional at the bottom of this file. Mechanical API guards enforce one row per EXISTING source, every id in `order` present with `eligible: true`, and both new signal fields present on every row once the serializer lands them.",
"items": {
"type": "object",
"required": ["source_id", "eligible"],
@@ -103,6 +103,15 @@
null
],
"description": "Closed i18n-key vocabulary explaining an ineligible source. REQUIRED and non-null when `eligible` is false, null when it is true. A new eligibility cause therefore requires an explicit contract and locale change."
+ },
+ "in_current_model_chain": {
+ "type": ["boolean", "null"],
+ "description": "Membership in the CAPABILITY chain for this AgentSupply record's `selected_model_id`, at the same routed-Agent grain as `current`. true includes blocked members because availability does not change capability; false is the explicit not-supplying-current-model flag that keeps a source visible to the drawer; null exactly when `selected_model_id` is null. OPTIONAL here and REQUIRED at the API boundary with the serializer, so frozen v1 examples remain byte-faithful."
+ },
+ "process_availability_reason": {
+ "enum": ["native_cli_unavailable", null],
+ "$comment": "Owner-approved channel class pass, evidence at master 05f72ae5: core/handlers/model_hub/service.py:469-483 computes the per-backend unavailable native source set independently of source health, and service.py:1843-1891 already computes that set beside the complete eligibility inventory but emits neither fact. This bare token is the AgentSupply spelling of mirror row M8. It is legal only for a native_cli Source at the API assembly boundary; hub is definitionally process-available and therefore null.",
+ "description": "Resolve-time serving-process availability for this source on this backend. `native_cli_unavailable` means this process cannot launch the sanctioned CLI under its own login right now; null means no process blocker. This does not restate source-global health. OPTIONAL here and REQUIRED at the API boundary with the serializer."
}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index ad645fefb..20e699950 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -8,16 +8,17 @@ Failure envelope:
`detail` is always a string. Structured error data lives in a named sibling.
Authentication and CSRF rules are the existing UI-server rules.
-The shared envelope remains v3. The targeted v4 amendment changes only the nested
-`AgentChain` and `ProbeResult` objects, whose own `contract_version` is 4; untouched
-schema objects and every unrelated route remain at version 3.
+The shared envelope remains v3. Targeted v4 amendments version their changed nested
+schema objects independently; the channel class pass also tightens the service-side
+OAuth seam and adds derived fields to the existing AgentSupply/source-creation
+responses without changing the envelope version.
## Route table
| Method and path | Request → response | Normative notes |
| --- | --- | --- |
| GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Array order is never a spend order. |
-| POST `/api/models/sources` | `SourceCreate` → `{source: Source, adopted_by: AdoptedBy[]}` | The server assigns `id` and immutable `created_at`; plaintext keys are transient. |
+| POST `/api/models/sources` | `SourceCreate` → `{source: Source, adopted_by: AdoptedBy[], skipped_by: SkippedBy[]}` | The server assigns `id` and immutable `created_at`; plaintext keys are transient. |
| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?}` → `{source: Source}` | Metadata only. |
| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → `{source, recovered, interrupted_pairs}` | API-key replacement. The optional `force` is a JSON body field, never a query parameter. |
| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | A `native_cli` source requires the acknowledgement before OAuth starts. See repair rules. |
@@ -72,8 +73,8 @@ Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:
"selected_model_id": "claude-opus-4-6",
"current": {
"model_id": "claude-opus-4-6",
- "source_id": "src_claudepro1",
- "channel": "native_cli"
+ "source_id": "src_anthkey01",
+ "channel": "hub"
},
"sources": {
"policy": "follow",
@@ -82,11 +83,27 @@ Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:
{
"source_id": "src_claudepro1",
"eligible": true,
- "reason_key": null
+ "reason_key": null,
+ "in_current_model_chain": true,
+ "process_availability_reason": "native_cli_unavailable"
+ },
+ {
+ "source_id": "src_anthkey01",
+ "eligible": true,
+ "reason_key": null,
+ "in_current_model_chain": true,
+ "process_availability_reason": null
+ },
+ {
+ "source_id": "src_otherkey1",
+ "eligible": true,
+ "reason_key": null,
+ "in_current_model_chain": false,
+ "process_availability_reason": null
}
]
},
- "supply_status": "ok",
+ "supply_status": "degraded",
"model_supply": [
{"model_id": "claude-opus-4-6", "chain_length": 2}
],
@@ -94,7 +111,7 @@ Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:
{
"name": "pm",
"effective_model_id": "claude-opus-4-6",
- "supply_status": "ok"
+ "supply_status": "degraded"
},
{
"name": "reviewer",
@@ -114,6 +131,21 @@ which is a list of bare names inside a mutation result.
Disabled Agents are absent. In Direct mode each named Agent may still have an
effective model, but its Hub `supply_status` is null.
+The `sources.eligibility` inventory is also the one complete source-signal
+projection. Every existing source remains represented, including a source outside
+the selected model's capability chain. `in_current_model_chain` is true or false
+when `selected_model_id` is non-null and is null when no selection exists.
+`process_availability_reason` is `native_cli_unavailable` or null independently of
+membership and source-global health; a Hub source always carries null. This one
+mechanism therefore serves both the Agent row and the all-sources drawer.
+
+The rejected alternative was to embed only the current `AgentChain`: an in-order
+source that does not supply the selected model is absent from that chain, so its
+process-availability fact vanishes at exactly the drawer grain that still renders
+the source. Evidence at master `05f72ae5`: `service.py:1843-1891` computes the
+per-backend unavailable set beside the complete eligibility inventory, while
+`model_supply` carries only `chain_length`.
+
### Honest null selection
Hub mode does not invent a default. When neither the routed Vibe Agent nor the
@@ -131,7 +163,8 @@ backend configuration pins a model:
This means “no pinned selection.” Each turn still resolves against the model carried
by that request, including the CLI's own default. `sources`, `model_supply`, and
-`named_agents` remain present and non-null in Hub mode.
+`named_agents` remain present and non-null in Hub mode. Each eligibility row keeps
+its process availability but carries `in_current_model_chain: null`.
## Per-backend source order
@@ -157,6 +190,21 @@ Request shapes are total:
Eligibility is server-authoritative. An ineligible row carries exactly one closed
`reason_key` from `agent-supply.schema.json`; an eligible row carries null.
+### Mapping and menu enrollment
+
+A mapping or open-menu target is accepted only when its selected source is enrolled
+in the backend's post-mutation effective order. Under `follow`, the effective order
+is `ModelHubConfig.effective_source_order`'s recommendation and is exhaustive over
+eligible sources, so an eligible-but-non-enrolled target is representable only under
+`custom`. Acceptance auto-appends that source to the custom order, and the confirm
+step must surface the append. Acceptance never converts policy: a selection that
+does not change the order is not an order edit. An ineligible source is never
+auto-enrolled and the request fails with `mapping_target_unavailable`. Evidence at
+master `05f72ae5`:
+`service.py:1955-1985` validates targets against eligible inventory but does not
+yet require or edit effective-order enrollment; the follow-up consumer lane owns
+that acceptance change.
+
## Source creation outcome
`AdoptedBy` is:
@@ -169,6 +217,20 @@ Eligibility is server-authoritative. An ineligible row carries exactly one close
eligible `follow` backends that actually adopted the source and is frozen with the
source response. `custom` backends are absent and retain their prior order.
+`SkippedBy` is:
+
+```json
+{"backend": "codex", "reason": "custom_order"}
+```
+
+Its closed backend vocabulary is `claude | codex | opencode`; its reason vocabulary
+has one v2 member, `custom_order`. The array contains every eligible custom backend
+that did not adopt the new source. Ineligible backends appear in neither array, so a
+consumer can distinguish “eligible but deliberately skipped” from “cannot use this
+source” without reimplementing the compatibility matrix. Evidence at master
+`05f72ae5`: `service.py:767-783` emits only follow-policy adoption, collapsing
+eligible custom skips into the same absence as ineligibility.
+
The terminal result of both ordinary API-key creation and OAuth creation is:
```json
@@ -178,6 +240,9 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
"source": {"id": "src_anthkey01", "kind": "api_key"},
"adopted_by": [
{"backend": "claude", "policy": "follow", "position": 2}
+ ],
+ "skipped_by": [
+ {"backend": "codex", "reason": "custom_order"}
]
}
```
@@ -275,6 +340,36 @@ differently only if all invariants remain true:
returning success. A reconstructed service reads the same journal and retries it.
The source remains usable; no state is allowed where the old handle is live and no
durable record names it. Successful reconciliation removes the record.
+8. **Channel-aware OAuth retained-material partition.** A failed Hub flow reports
+ one total `retained_material_disposition` from the adapter seam. `none` preserves
+ the prior source strictly. `flow_source_ref` is the irreversible v4b case:
+ persist `state.status: needs_action` with
+ `state.detail_key: models.source.needs_action.oauth_expired`, clear discovered
+ supply, and never route silently. `orphan_ref` preserves the prior source and
+ records a ref-keyed invariant-7 retry through `retained_credential_ref` and
+ `EngineAdapter.cleanup_orphaned_oauth_material`: the operation returns true
+ only after both auth-file deletions are confirmed and the retained ref is
+ revoked; only then may the journal entry be cleared. `foreign_source_ref`
+ preserves the prior source and
+ schedules neither revocation nor a journal entry; the same-account refresh
+ belongs to the other source's record, whose health reports at its own grain,
+ while this flow retains `models.oauth.binding_failed`. `unknown` treats the flow
+ source like the irreversible case but touches no refs: no handle can be named
+ safely, so loud re-auth is the convergent remedy.
+
+ A failed create flow has no prior `Source` to mark `needs_action`.
+ `flow_source_ref` is durably revoked by its retained ref, `orphan_ref` uses
+ the cleanup retry above, and `none` / `foreign_source_ref` / `unknown` touch
+ no refs; the producer can emit both known-ref and unknown create failures
+ because intent is a service concern outside the adapter seam.
+
+ The consumer does not infer this partition by comparing refs. Hub success pins
+ `flow_source_ref` and equality of `credential_ref` and
+ `retained_credential_ref`. Native CLI success pins `credential_ref: null`,
+ disposition `none`, and a null retained ref because CLI-owned material never
+ enters the engine seam. A two-ref transactional OAuth swap remains a deliberate
+ v2 non-goal: the owner accepted one additional re-auth for this rare, already
+ interactive failure window; revisit only with field evidence.
API-key success:
@@ -304,7 +399,7 @@ does not add a second “recover” endpoint.
`OAuthFlow.intent` makes the terminal shape a function of the flow:
- non-terminal, failed, or canceled → `{flow}`;
-- terminal `intent: "create"` → `{flow, source, adopted_by}`;
+- terminal `intent: "create"` → `{flow, source, adopted_by, skipped_by}`;
- terminal `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}`.
Status and submit return the same terminal shape:
@@ -322,7 +417,8 @@ Status and submit return the same terminal shape:
"source": {"id": "src_claudepro1", "kind": "subscription"},
"adopted_by": [
{"backend": "claude", "policy": "follow", "position": 1}
- ]
+ ],
+ "skipped_by": []
}
```
@@ -518,13 +614,15 @@ contract harness and API-boundary tests enforce:
| every non-null `then` constraint has matching `required`, except a declared fail-safe legacy-example exception | contract harness |
| every `sources.order` id exists, is unique, and is eligible | config loader + source-order route |
| eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler |
+| every AgentSupply eligibility row carries `in_current_model_chain` and `process_availability_reason`; membership nullability follows `selected_model_id`, and only a native source may carry `native_cli_unavailable` | AgentSupply assembler |
| `AgentChain.chain` source ids are unique and preserve effective order, including process-unavailable native CLI items | chain assembler |
| `model_supply` has one row per menu model with unique ids | AgentSupply assembler |
| probe `source_id` names an existing source | probe assembler |
| non-null event endpoints name existing sources at emission time | event emitter |
| `channel_switch.from_source == channel_switch.to_source` | event emitter |
-| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `sources`, `supply_status`, `model_supply`, and `named_agents` | API payload test |
+| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `sources`, `supply_status`, `model_supply`, and `named_agents`; source creation returns both `adopted_by` and `skipped_by` | API payload test |
| every OAuthFlow response includes `intent` | API payload test |
+| contract and in-repo adapter interface copies are byte-identical; the five retained-material enum members and ref-pairing predicates are mutation-tested | contract harness |
Serializer completeness follows the issue #939 pattern. Persisted fields must
round-trip through config serialization. Derived fields are exempt from persistence
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index ef483b243..254cee6ed 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -189,13 +189,23 @@
"schema": "agent-chain.schema.json",
"path": "/properties/chain/items/properties/reason/anyOf/0"
},
- "target": {
- "schema": "probe-result.schema.json",
- "path": "/allOf/6/then/properties/error"
- },
- "mapping": {
- "native_cli_unavailable": "models.probe.native_cli_unavailable"
- }
+ "targets": [
+ {
+ "schema": "agent-supply.schema.json",
+ "path": "/properties/sources/properties/eligibility/items/properties/process_availability_reason",
+ "exclude": [null],
+ "mapping": {
+ "native_cli_unavailable": "native_cli_unavailable"
+ }
+ },
+ {
+ "schema": "probe-result.schema.json",
+ "path": "/allOf/6/then/properties/error",
+ "mapping": {
+ "native_cli_unavailable": "models.probe.native_cli_unavailable"
+ }
+ }
+ ]
},
{
"id": "N1",
diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.json
index 499fd2fff..99a2f12de 100644
--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json
+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json
@@ -3,6 +3,7 @@
"$id": "model-hub/oauth-flow.schema.json",
"title": "OAuthFlow",
"description": "Subscription-connect flow state. RUNTIME-DECLARED presentation (S1 gap ③): the server declares what to show and what it expects back; the UI renders declaratively and never keys off a vendor→form table. UI shell semantics mirror the existing BackendOAuthPanel (2s poll, 15-min timeout, cancel). Forms A/B/C from spec §5 frame 09 are presentation patterns the declaration composes: A = auth_url + expects paste_code; B = auth_url + device_code + expects none; C = auth_url + expects paste_callback_url. Under Option 1, native_cli subscription connect drives the CLI's own login through this same shape.",
+ "$comment": "Owner-approved channel class audit: this is the user-facing presentation wire, not the service-side OAuthFlowState seam. `credential_ref`, `retained_material_disposition`, and `retained_credential_ref` are deliberately excluded because only the service repair consumer acts on them; no UI or wire consumer does. Both channel branches still expose `channel`, and source-bound create/reauth flows carry `source_id`. Evidence at master 05f72ae5: core/handlers/model_hub/native_oauth.py:252-289 produces native success with no engine credential ref, while the HTTP projection publishes presentation fields rather than adapter refs.",
"type": "object",
"required": ["flow_id", "vendor", "channel", "state", "presentation"],
"additionalProperties": false,
@@ -10,9 +11,9 @@
"flow_id": { "type": "string" },
"intent": {
"enum": ["create", "reauth"],
- "description": "v2 (07-29, review round 6): what this flow is FOR, and therefore what its terminal success response carries — `create` → `{flow, source, adopted_by}`, `reauth` → `{flow, source, recovered, interrupted_pairs}` (api.md → OAuth completion responses). Round 5 defined neither, which left the two creation paths inconsistent: `POST /sources` closed the 「so what now?」 loop with `adopted_by` while the OAuth door — the default way a subscription is added — returned only flow state. Declared as a field rather than inferred, for two reasons. `source_id` cannot discriminate: hub-channel CREATE flows also set it, for the pending source they bind to, so both intents can carry one. And the alternative — the client remembering which button it pressed — makes the response shape a function of client state instead of of the payload, which is exactly how a poll that arrives after a page reload ends up parsed as the wrong shape. OPTIONAL here, REQUIRED at the API boundary from v2 on (README → required-vs-optional): the shipped flow payloads are validated against this file by tests/test_model_hub_api.py and predate the field, so a `required` would fail the contract gate instead of tightening it."
+ "description": "v2 (07-29, review round 6), extended by the channel class pass: what this flow is FOR, and therefore what its terminal success response carries — `create` → `{flow, source, adopted_by, skipped_by}`, `reauth` → `{flow, source, recovered, interrupted_pairs}` (api.md → OAuth completion responses). Round 5 defined neither, which left the two creation paths inconsistent: `POST /sources` closed the 「so what now?」 loop with an adoption result while the OAuth door — the default way a subscription is added — returned only flow state. Declared as a field rather than inferred, for two reasons. `source_id` cannot discriminate: both channel branches and both intents bind a pending or existing source. And the alternative — the client remembering which button it pressed — makes the response shape a function of client state instead of of the payload, which is exactly how a poll that arrives after a page reload ends up parsed as the wrong shape. OPTIONAL here, REQUIRED at the API boundary from v2 on (README → required-vs-optional): the shipped flow payloads are validated against this file by tests/test_model_hub_api.py and predate the field, so a `required` would fail the contract gate instead of tightening it."
},
- "source_id": { "type": ["string", "null"], "description": "v1.1: pending Source this flow binds to (deterministic association; hub-channel flows always set it)" },
+ "source_id": { "type": ["string", "null"], "description": "v1.1: pending Source this flow binds to (deterministic association). Both hub and native_cli Model Hub create/reauth flows set it; null remains legal only for legacy presentation payloads." },
"vendor": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"], "description": "where the resulting credential will live; hub-held subscriptions only behind the consent-gated experimental flag (S2)" },
"state": { "enum": ["starting", "awaiting_action", "verifying", "success", "failed", "cancelled"] },
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 3505b0066..2b0d391fb 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -164,7 +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.",
+ "$comment": "Targeted v4b (finding 3675168031), completed by the owner-approved channel class pass: `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, and for retained-material disposition `unknown`, where material may have been rewritten but no ref can be named safely. The truthful user-facing fact is that OAuth authentication must be re-established; this use does not claim a wall-clock token expiry. Evidence: vibe/model_hub_runtime/state.py:135-166 binds OAuth identity to a stable credential_ref and returns the existing ref on a match; state.py:330-341 raises on duplicate auth metadata; neither case permits restoration by guessing a ref. 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. Revisit only on field evidence.",
"enum": [
"models.source.needs_action.oauth_expired",
"models.source.needs_action.balance_exhausted",
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.py
index c4a60edfb..201006799 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
@@ -1,7 +1,10 @@
from __future__ import annotations
+import asyncio
+
import pytest
+from core.handlers.model_hub.adapter import RetainedMaterialDisposition
from tests.scenario_harness.model_hub_native_oauth import (
HubOAuthScenarioHarness,
NativeOAuthScenarioHarness,
@@ -45,6 +48,11 @@ def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path)
"expects": "paste_code",
"instructions_key": "settings.models.oauth.pasteCode.hint",
}
+ started_seam = asyncio.run(harness.adapter.oauth_status(started["flow_id"]))
+ assert started_seam.channel == "native_cli"
+ assert started_seam.credential_ref is None
+ assert started_seam.retained_material_disposition is RetainedMaterialDisposition.NONE
+ assert started_seam.retained_credential_ref is None
invalid = client.post(
"/api/models/oauth/submit",
@@ -66,6 +74,12 @@ def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path)
assert harness.agent_auth.submissions == [(started["flow_id"], "code-value#state-value")]
harness.agent_auth.complete(started["flow_id"])
+ completed_seam = asyncio.run(harness.adapter.oauth_status(started["flow_id"]))
+ assert completed_seam.state == "success"
+ assert completed_seam.channel == "native_cli"
+ assert completed_seam.credential_ref is None
+ assert completed_seam.retained_material_disposition is RetainedMaterialDisposition.NONE
+ assert completed_seam.retained_credential_ref is None
completed = client.get(
f"/api/models/oauth/status/{started['flow_id']}",
base_url=BASE_URL,
@@ -142,6 +156,7 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p
"flow",
"source",
"adopted_by",
+ "skipped_by",
}
completed = completion["flow"]
source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]
@@ -157,6 +172,9 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p
assert source["account_label"] == "[email protected] \u00b7 plus \u00b7 Example Org"
assert source["credential_ref"] is None
assert completion["adopted_by"] == []
+ assert completion["skipped_by"] == [
+ {"backend": "codex", "reason": "custom_order"}
+ ]
assert codex["sources"]["policy"] == "custom"
assert codex["sources"]["order"] == []
assert codex["sources"]["eligibility"] == [
@@ -164,6 +182,8 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p
"source_id": source["id"],
"eligible": True,
"reason_key": None,
+ "in_current_model_chain": None,
+ "process_availability_reason": None,
}
]
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 30ba3b561..26d4f228f 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -21,6 +21,7 @@ from core.handlers.model_hub.adapter import (
OAuthFlowState,
RawCallOutcome,
RawOutcomeKind,
+ RetainedMaterialDisposition,
)
from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
@@ -97,6 +98,9 @@ class FakeAdapter:
self.native_signed_in = True
self.native_account_label = None
self.oauth_start_calls = []
+ self.orphan_cleanup_calls = []
+ self.orphan_cleanup_succeeds = False
+ self.cancel_disposition = RetainedMaterialDisposition.NONE
async def ensure_installed(self):
return await self.status()
@@ -127,6 +131,10 @@ class FakeAdapter:
async def revoke_credential(self, credential_ref):
self.revoked.append(credential_ref)
+ async def cleanup_orphaned_oauth_material(self, credential_ref):
+ self.orphan_cleanup_calls.append(credential_ref)
+ return self.orphan_cleanup_succeeds
+
async def sync_sources(self, bindings):
self.synced.append(tuple(bindings))
if self.fail_sync:
@@ -194,6 +202,16 @@ class FakeAdapter:
self.cancelled.append(flow_id)
if self.fail_cancel:
raise RuntimeError("temporary engine failure")
+ flow = self.flows[flow_id]
+ if flow.state not in {"success", "failed", "cancelled"}:
+ self.flows[flow_id] = OAuthFlowState(
+ **{
+ **flow.__dict__,
+ "state": "cancelled",
+ "retained_material_disposition": self.cancel_disposition,
+ "retained_credential_ref": None,
+ }
+ )
def completed_source_status(self, flow_id):
if flow_id not in self.flows:
@@ -649,12 +667,19 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
assert response.status_code == 201
body = response.get_json()
_assert_envelope(body)
- assert set(body) == {"ok", "contract_version", "source", "adopted_by"}
+ assert set(body) == {
+ "ok",
+ "contract_version",
+ "source",
+ "adopted_by",
+ "skipped_by",
+ }
assert {item["backend"] for item in body["adopted_by"]} == {
"claude",
"codex",
"opencode",
}
+ assert body["skipped_by"] == []
source = body["source"]
_assert_valid("source.schema.json", source)
source_id = source["id"]
@@ -830,6 +855,15 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
"model_supply",
"named_agents",
} <= set(agent)
+ if agent["sources"] is not None:
+ for row in agent["sources"]["eligibility"]:
+ assert set(row) == {
+ "source_id",
+ "eligible",
+ "reason_key",
+ "in_current_model_chain",
+ "process_availability_reason",
+ }
_assert_valid("agent-supply.schema.json", agent)
event_example = _schema("resolution-event.schema.json")["examples"][0]
@@ -932,7 +966,9 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
"contract_version",
"source",
"adopted_by",
+ "skipped_by",
}
+ assert oauth_creation["skipped_by"] == []
consented_source = oauth_creation["source"]
_assert_valid("source.schema.json", consented_source)
assert consented_source["experimental_consent_at"] == "2026-07-23T03:00:00+00:00"
@@ -1673,7 +1709,26 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):
assert binding.completed is True
-def test_failed_undiscriminated_hub_reauth_fails_closed(tmp_path):
+ ("terminal_state", "disposition", "retained_credential_ref"),
+ [
+ (
+ "failed",
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ "cred_hub_existing",
+ ),
+ ("failed", RetainedMaterialDisposition.UNKNOWN, None),
+ ("cancelled", RetainedMaterialDisposition.UNKNOWN, None),
+ ],
+)
[email protected]("entrypoint", ["status", "submit"])
+def test_hub_reauth_irreversible_dispositions_fail_closed(
+ tmp_path,
+ terminal_state,
+ disposition,
+ retained_credential_ref,
+ entrypoint,
+):
service, store, adapter = _service(tmp_path)
source = ModelHubSourceConfig(
id="src_huboauth01",
@@ -1704,24 +1759,427 @@ def test_failed_undiscriminated_hub_reauth_fails_closed(tmp_path):
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
- "state": "failed",
- "error_key": "models.oauth.binding_failed",
+ "state": terminal_state,
+ "error_key": (
+ "models.oauth.binding_failed"
+ if terminal_state == "failed"
+ else None
+ ),
+ "channel": "hub",
+ "retained_material_disposition": disposition,
+ "retained_credential_ref": retained_credential_ref,
}
)
- result = asyncio.run(service.oauth_status(flow["flow_id"]))
+ if entrypoint == "status":
+ result = asyncio.run(service.oauth_status(flow["flow_id"]))
+ else:
+ async def return_terminal(_flow_id, _value):
+ return adapter.flows[flow["flow_id"]]
- assert result["flow"]["state"] == "failed"
+ adapter.submit_oauth = return_terminal
+ result = asyncio.run(
+ service.oauth_submit(
+ {
+ "flow_id": flow["flow_id"],
+ "value": "oauth-code",
+ }
+ )
+ )
+
+ assert result["flow"]["state"] == terminal_state
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 adapter.orphan_cleanup_calls == []
assert service.revocations.list() == []
-def test_hub_reauth_retry_materializes_failed_pending_flow(tmp_path):
+ "disposition",
+ [
+ RetainedMaterialDisposition.NONE,
+ RetainedMaterialDisposition.FOREIGN_SOURCE_REF,
+ ],
+)
+def test_failed_hub_reauth_non_owned_material_preserves_prior_state(
+ tmp_path,
+ disposition,
+):
+ service, store, adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_huboauth01",
+ kind="subscription",
+ vendor="anthropic",
+ display_name="Hub subscription",
+ protocol="anthropic",
+ supply_channel="hub",
+ 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",
+ "channel": "hub",
+ "retained_material_disposition": disposition,
+ "retained_credential_ref": None,
+ }
+ )
+ before = json.dumps(
+ store.config.to_payload(),
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+
+ result = asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert result["flow"]["state"] == "failed"
+ assert json.dumps(
+ store.config.to_payload(),
+ sort_keys=True,
+ separators=(",", ":"),
+ ) == before
+ assert adapter.revoked == []
+ assert adapter.orphan_cleanup_calls == []
+ assert service.revocations.list() == []
+
+
+def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_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="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="claude-opus-4-6",
+ provenance="discovered",
+ )
+ ],
+ 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",
+ "channel": "hub",
+ "retained_material_disposition": RetainedMaterialDisposition.ORPHAN_REF,
+ "retained_credential_ref": "cred_hub_orphan",
+ }
+ )
+ before = json.dumps(
+ store.config.to_payload(),
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+
+ result = asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert result["flow"]["state"] == "failed"
+ assert json.dumps(
+ store.config.to_payload(),
+ sort_keys=True,
+ separators=(",", ":"),
+ ) == before
+ assert adapter.revoked == []
+ assert adapter.orphan_cleanup_calls == ["cred_hub_orphan"]
+ pending = service.revocations.list()
+ assert [
+ (entry.source_id, entry.credential_ref, entry.operation)
+ for entry in pending
+ ] == [
+ (
+ source.id,
+ "cred_hub_orphan",
+ "cleanup_orphaned_oauth_material",
+ )
+ ]
+
+ restarted_adapter = FakeAdapter()
+ restarted_adapter.orphan_cleanup_succeeds = True
+ 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 / "revocations.json"
+ ),
+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ )
+
+ asyncio.run(restarted._ensure_engine_synced())
+
+ assert restarted_adapter.orphan_cleanup_calls == ["cred_hub_orphan"]
+ assert restarted.revocations.list() == []
+
+
+def test_failed_hub_create_orphan_is_journaled_before_flow_can_be_forgotten(
+ tmp_path,
+):
+ service, _, adapter = _service(tmp_path)
+ flow = asyncio.run(
+ service.oauth_start(
+ {
+ "vendor": "anthropic",
+ "channel": "hub",
+ "experimental_consent": True,
+ }
+ )
+ )["flow"]
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "failed",
+ "error_key": "models.oauth.binding_failed",
+ "channel": "hub",
+ "retained_material_disposition": RetainedMaterialDisposition.ORPHAN_REF,
+ "retained_credential_ref": "cred_create_orphan",
+ }
+ )
+
+ result = asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert result["flow"]["state"] == "failed"
+ assert adapter.orphan_cleanup_calls == ["cred_create_orphan"]
+ assert [
+ (entry.source_id, entry.credential_ref, entry.operation)
+ for entry in service.revocations.list()
+ ] == [
+ (
+ flow["source_id"],
+ "cred_create_orphan",
+ "cleanup_orphaned_oauth_material",
+ )
+ ]
+
+ asyncio.run(service.oauth_cancel(flow["flow_id"]))
+
+ assert service.oauth_flows.binding(flow["flow_id"]) is None
+ assert service.revocations.list()
+
+
+def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(
+ tmp_path,
+):
+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+ from vibe.model_hub_runtime.state import EngineStateStore
+
+ class Client:
+ def management_request(
+ self,
+ method,
+ path,
+ *,
+ query=None,
+ payload=None,
+ timeout=None,
+ ):
+ assert (method, path) == ("DELETE", "/auth-files")
+ return {"status": "ok"}
+
+ class Supervisor:
+ def __init__(self, client):
+ self._client = client
+
+ def client_if_running(self):
+ return self._client
+
+ class RuntimeCleanupAdapter(FakeAdapter):
+ def __init__(self, runtime_adapter):
+ super().__init__()
+ self.runtime_adapter = runtime_adapter
+
+ async def cleanup_orphaned_oauth_material(self, credential_ref):
+ self.orphan_cleanup_calls.append(credential_ref)
+ return await self.runtime_adapter.cleanup_orphaned_oauth_material(
+ credential_ref
+ )
+
+ state = EngineStateStore(tmp_path / "runtime-state")
+ state.prepare_instance("install-1")
+ auth_file = state.auth_dir / "claude-account.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o600)
+ credential_ref = state.bind_oauth_credential(
+ "src_pending01",
+ "anthropic",
+ auth_file.name,
+ )
+ runtime_adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(Client()), # type: ignore[arg-type]
+ state_store=state,
+ )
+ journal = CredentialRevocationJournal(tmp_path / "revocations.json")
+ journal.add(
+ "src_pending01",
+ credential_ref,
+ operation="cleanup_orphaned_oauth_material",
+ )
+
+ assert (
+ asyncio.run(
+ runtime_adapter.cleanup_orphaned_oauth_material(credential_ref)
+ )
+ is True
+ )
+ assert journal.list()
+
+ adapter = RuntimeCleanupAdapter(runtime_adapter)
+ service = ModelHubService(
+ store=MemoryStore(),
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth-flows.json"),
+ revocations=journal,
+ )
+
+ asyncio.run(service._ensure_engine_synced())
+
+ assert adapter.orphan_cleanup_calls == [credential_ref]
+ assert journal.list() == []
+
+
+ ("disposition", "retained_credential_ref", "expected_revoked"),
+ [
+ (
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ "cred_create_flow",
+ ["cred_create_flow"],
+ ),
+ (RetainedMaterialDisposition.NONE, None, []),
+ (RetainedMaterialDisposition.FOREIGN_SOURCE_REF, None, []),
+ (RetainedMaterialDisposition.UNKNOWN, None, []),
+ ],
+)
+def test_failed_hub_create_consumes_known_ref_without_fabricating_source_state(
+ tmp_path,
+ disposition,
+ retained_credential_ref,
+ expected_revoked,
+):
+ service, store, adapter = _service(tmp_path)
+ flow = asyncio.run(
+ service.oauth_start(
+ {
+ "vendor": "anthropic",
+ "channel": "hub",
+ "experimental_consent": True,
+ }
+ )
+ )["flow"]
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "failed",
+ "error_key": "models.oauth.binding_failed",
+ "channel": "hub",
+ "retained_material_disposition": disposition,
+ "retained_credential_ref": retained_credential_ref,
+ }
+ )
+
+ result = asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert result["flow"]["state"] == "failed"
+ assert store.config.sources == []
+ assert adapter.revoked == expected_revoked
+ assert adapter.orphan_cleanup_calls == []
+ assert service.revocations.list() == []
+
+
+def test_failed_hub_create_keeps_flow_when_ref_cleanup_is_not_durable(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ flow = asyncio.run(
+ service.oauth_start(
+ {
+ "vendor": "anthropic",
+ "channel": "hub",
+ "experimental_consent": True,
+ }
+ )
+ )["flow"]
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "failed",
+ "error_key": "models.oauth.binding_failed",
+ "channel": "hub",
+ "retained_material_disposition": RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ "retained_credential_ref": "cred_create_flow",
+ }
+ )
+
+ def fail_journal_write(*_args, **_kwargs):
+ raise OSError("journal is unavailable")
+
+ async def fail_revocation(credential_ref):
+ adapter.revoked.append(credential_ref)
+ raise RuntimeError("engine is unavailable")
+
+ service.revocations.add = fail_journal_write
+ adapter.revoke_credential = fail_revocation
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert exc_info.value.code == "engine_down"
+ assert store.config.sources == []
+ assert adapter.revoked == ["cred_create_flow"]
+ assert service.revocations.list() == []
+ assert service.oauth_flows.binding(flow["flow_id"]) is not None
+
+
+ ("terminal_state", "disposition", "retained_credential_ref"),
+ [
+ (
+ "failed",
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ "cred_hub_existing",
+ ),
+ ("cancelled", RetainedMaterialDisposition.UNKNOWN, None),
+ ],
+)
+def test_hub_reauth_retry_materializes_pending_flow(
+ tmp_path,
+ terminal_state,
+ disposition,
+ retained_credential_ref,
+):
service, store, adapter = _service(tmp_path)
source = ModelHubSourceConfig(
id="src_huboauth01",
@@ -1752,8 +2210,15 @@ def test_hub_reauth_retry_materializes_failed_pending_flow(tmp_path):
adapter.flows[first["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[first["flow_id"]].__dict__,
- "state": "failed",
- "error_key": "models.oauth.binding_failed",
+ "state": terminal_state,
+ "error_key": (
+ "models.oauth.binding_failed"
+ if terminal_state == "failed"
+ else None
+ ),
+ "channel": "hub",
+ "retained_material_disposition": disposition,
+ "retained_credential_ref": retained_credential_ref,
}
)
@@ -2420,6 +2885,9 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):
**adapter.flows[flow["flow_id"]].__dict__,
"state": "failed",
"error_key": "models.oauth.binding_failed",
+ "channel": "hub",
+ "retained_material_disposition": RetainedMaterialDisposition.UNKNOWN,
+ "retained_credential_ref": None,
}
)
@@ -2436,6 +2904,56 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):
assert adapter.cancelled == []
+def test_cancel_materializes_post_cancel_unknown_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": "verifying",
+ "channel": "hub",
+ }
+ )
+ adapter.cancel_disposition = RetainedMaterialDisposition.UNKNOWN
+
+ 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 == [flow["flow_id"]]
+
+
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"]
@@ -2659,6 +3177,7 @@ def test_follow_auto_adopts_new_sources_while_custom_stays_frozen(tmp_path):
"codex",
"opencode",
}
+ assert first["skipped_by"] == []
asyncio.run(
service.set_agent_sources(
@@ -2680,6 +3199,9 @@ def test_follow_auto_adopts_new_sources_while_custom_stays_frozen(tmp_path):
assert store.config.agents["claude"].sources.order == [first_id]
assert "claude" not in {item["backend"] for item in second["adopted_by"]}
+ assert second["skipped_by"] == [
+ {"backend": "claude", "reason": "custom_order"}
+ ]
assert set(store.config.effective_source_order("codex")) == {
first_id,
second_id,
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index d1a3ea019..7d84139bb 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -84,12 +84,18 @@ def _validate_mirror_entry(entry: dict, schemas: dict[str, dict]) -> None:
schemas[entry["home"]["schema"]],
[entry["home"]["path"]],
)
- target = _vocabulary(
- schemas[entry["target"]["schema"]],
- [entry["target"]["path"]],
- )
- assert home == set(entry["mapping"])
- assert target == set(entry["mapping"].values())
+ targets = entry.get("targets")
+ if targets is None:
+ targets = [{**entry["target"], "mapping": entry["mapping"]}]
+ for item in targets:
+ target = _vocabulary(
+ schemas[item["schema"]],
+ [item["path"]],
+ exclude=item.get("exclude", ()),
+ )
+ mapping = item["mapping"]
+ assert home == set(mapping)
+ assert target == set(mapping.values())
return
if rule == "partition":
home = _vocabulary(
@@ -216,22 +222,40 @@ def test_v4_mirror_registry_mutation_probes_detect_every_comparable_drift():
for entry in registry["entries"]:
if entry["rule"] == "none":
continue
- mutated = copy.deepcopy(schemas)
if entry["rule"] == "bijection":
- location = entry["target_sets"][0]
- pointer = location["paths"][0]
+ locations = [(location, location["paths"][0]) for location in entry["target_sets"]]
elif entry["rule"] == "equality":
- location = entry["sets"][0]
- pointer = location["paths"][0]
+ locations = [(location, pointer) for location in entry["sets"] for pointer in location["paths"][:1]]
+ elif entry["rule"] == "mapping":
+ targets = entry.get("targets")
+ if targets is None:
+ targets = [entry["target"]]
+ locations = [
+ (entry["home"], entry["home"]["path"]),
+ *[(location, location["path"]) for location in targets],
+ ]
+ elif entry["rule"] == "partition":
+ locations = [
+ (entry["home"], entry["home"]["path"]),
+ (entry["member"], entry["member"]["path"]),
+ ]
else:
- location = entry["home"]
- pointer = location["path"]
- node = _json_pointer(mutated[location["schema"]], pointer)
- assert "enum" in node, entry["id"]
- node["enum"].append(f"mutation_{entry['id'].lower()}")
+ locations = [
+ (entry["home"], entry["home"]["path"]),
+ *[(location, location["path"]) for location in entry["targets"]],
+ ]
- with pytest.raises(AssertionError):
- _validate_mirror_entry(entry, mutated)
+ for location, pointer in locations:
+ mutated = copy.deepcopy(schemas)
+ node = _json_pointer(mutated[location["schema"]], pointer)
+ if "enum" in node:
+ node["enum"].append(f"mutation_{entry['id'].lower()}")
+ else:
+ assert "const" in node, entry["id"]
+ node["const"] = f"mutation_{entry['id'].lower()}"
+
+ with pytest.raises(AssertionError):
+ _validate_mirror_entry(entry, mutated)
def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():
@@ -324,6 +348,57 @@ def test_v4_shape_amendments_reject_the_false_states_they_replace():
with pytest.raises(ValidationError):
supply_validator.validate(invalid_reason)
+ signal_supply = copy.deepcopy(base_supply)
+ signal_supply.update(
+ {
+ "selected_model_id": "claude-opus-4-6",
+ "current": {
+ "model_id": "claude-opus-4-6",
+ "source_id": "src_anthkey01",
+ "channel": "hub",
+ },
+ "supply_status": "degraded",
+ }
+ )
+ signal_supply["sources"] = {
+ "policy": "custom",
+ "order": ["src_anthkey01"],
+ "eligibility": [
+ {
+ "source_id": "src_claudepro1",
+ "eligible": True,
+ "reason_key": None,
+ "in_current_model_chain": True,
+ "process_availability_reason": "native_cli_unavailable",
+ },
+ {
+ "source_id": "src_anthkey01",
+ "eligible": True,
+ "reason_key": None,
+ "in_current_model_chain": True,
+ "process_availability_reason": None,
+ },
+ {
+ "source_id": "src_otherkey1",
+ "eligible": True,
+ "reason_key": None,
+ "in_current_model_chain": False,
+ "process_availability_reason": None,
+ },
+ ],
+ }
+ supply_validator.validate(signal_supply)
+
+ invalid_availability = copy.deepcopy(signal_supply)
+ invalid_availability["sources"]["eligibility"][0]["process_availability_reason"] = "gateway_down"
+ with pytest.raises(ValidationError):
+ supply_validator.validate(invalid_availability)
+
+ invalid_membership = copy.deepcopy(signal_supply)
+ invalid_membership["sources"]["eligibility"][2]["in_current_model_chain"] = "not_supplying"
+ with pytest.raises(ValidationError):
+ supply_validator.validate(invalid_membership)
+
event_validator = Draft7Validator(_schema("resolution-event.schema.json"))
source_wide = _schema("resolution-event.schema.json")["examples"][1]
event_validator.validate(source_wide)
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 36be54f9b..331ae3b8e 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -685,6 +685,60 @@ def test_opencode_unknown_vendor_uses_custom_provider_identifier(tmp_path):
assert resolved.source_id == "src_primary01"
+def test_agent_supply_eligibility_is_complete_chain_and_process_inventory(
+ tmp_path,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ native = config.sources[0]
+ native.kind = "subscription"
+ native.vendor = "anthropic"
+ native.supply_channel = "native_cli"
+ native.credential_ref = None
+ outside_chain = _source("src_outside01", "Outside current chain")
+ outside_chain.models = [
+ ModelHubModelConfig(id="other-model", provenance="discovered")
+ ]
+ config.sources.append(outside_chain)
+ service.native_source_ready = (
+ lambda _backend, source: source.id != native.id
+ )
+
+ agent = service.get_agent_sources("claude")
+ eligibility = {
+ row["source_id"]: row
+ for row in agent["sources"]["eligibility"]
+ }
+
+ assert set(eligibility) == {source.id for source in config.sources}
+ assert eligibility[native.id] == {
+ "source_id": native.id,
+ "eligible": True,
+ "reason_key": None,
+ "in_current_model_chain": True,
+ "process_availability_reason": "native_cli_unavailable",
+ }
+ assert eligibility["src_backup001"]["in_current_model_chain"] is True
+ assert eligibility[outside_chain.id]["in_current_model_chain"] is False
+ assert (
+ eligibility[outside_chain.id]["process_availability_reason"]
+ is None
+ )
+
+ service.store.requested_models["claude"] = ""
+ unselected = service.get_agent_sources("claude")
+ assert unselected["selected_model_id"] is None
+ assert all(
+ row["in_current_model_chain"] is None
+ for row in unselected["sources"]["eligibility"]
+ )
+ assert next(
+ row
+ for row in unselected["sources"]["eligibility"]
+ if row["source_id"] == native.id
+ )["process_availability_reason"] == "native_cli_unavailable"
+
+
def test_opencode_resolution_rejects_models_outside_checked_menu(tmp_path):
adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
service = _service(tmp_path, adapter)
@@ -1390,6 +1444,270 @@ def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):
assert [source.id for source in service.store.load().sources] == ["src_backup001"]
+def test_mapping_auto_enrolls_eligible_non_enrolled_source(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ added = _source("src_mapping01", "Mapping target")
+ added.models = [
+ ModelHubModelConfig(id="mapped-model", provenance="discovered")
+ ]
+ excluded = _source("src_mapping02", "Excluded mapping fallback")
+ excluded.models = [
+ ModelHubModelConfig(id="mapped-model", provenance="discovered")
+ ]
+ config.sources.extend([added, excluded])
+ original_order = list(config.agents["claude"].sources.order)
+
+ agent = asyncio.run(
+ service.set_mappings(
+ "claude",
+ [
+ {
+ "builtin_id": "claude-opus-4-6",
+ "target_model_id": "mapped-model",
+ "enabled": True,
+ }
+ ],
+ )
+ )
+
+ assert agent["sources"]["policy"] == "custom"
+ assert agent["sources"]["order"] == [*original_order, added.id]
+ assert config.agents["claude"].mappings[0].target_model_id == "mapped-model"
+
+
+def test_opencode_menu_auto_enrolls_eligible_non_enrolled_source(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ added = _source("src_openmenu01", "Open menu target")
+ added.vendor = "openrouter"
+ added.models = [
+ ModelHubModelConfig(
+ id="anthropic/claude-sonnet-4",
+ provenance="manual",
+ )
+ ]
+ excluded = _source("src_openmenu02", "Excluded menu fallback")
+ excluded.vendor = "openrouter"
+ excluded.models = [
+ ModelHubModelConfig(
+ id="anthropic/claude-sonnet-4",
+ provenance="manual",
+ )
+ ]
+ config.sources.extend([added, excluded])
+ original_order = list(config.agents["opencode"].sources.order)
+
+ agent = asyncio.run(
+ service.set_opencode_menu(
+ {
+ "view": "featured",
+ "checked": [
+ "openrouter/anthropic/claude-sonnet-4",
+ ],
+ }
+ )
+ )
+
+ assert agent["sources"]["policy"] == "custom"
+ assert agent["sources"]["order"] == [*original_order, added.id]
+ assert agent["menu"]["checked"] == [
+ "openrouter/anthropic/claude-sonnet-4"
+ ]
+
+
[email protected]("mutation", ["mapping", "menu"])
+def test_menu_acceptance_preserves_excluded_supplier_when_target_is_enrolled(
+ tmp_path,
+ mutation,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ excluded = _source("src_excluded01", "Explicitly excluded fallback")
+ config.sources.append(excluded)
+ backend = "claude" if mutation == "mapping" else "opencode"
+ original_order = list(config.agents[backend].sources.order)
+
+ if mutation == "mapping":
+ agent = asyncio.run(
+ service.set_mappings(
+ "claude",
+ [
+ {
+ "builtin_id": "claude-opus-4-6",
+ "target_model_id": "claude-opus-4-6",
+ "enabled": True,
+ }
+ ],
+ )
+ )
+ else:
+ agent = asyncio.run(
+ service.set_opencode_menu(
+ {
+ "view": "featured",
+ "checked": ["anthropic/claude-opus-4-6"],
+ }
+ )
+ )
+
+ assert agent["sources"]["order"] == original_order
+ assert excluded.id not in agent["sources"]["order"]
+
+
[email protected]("mutation", ["mapping", "menu"])
+def test_menu_acceptance_incrementally_deduplicates_selected_supplier(
+ tmp_path,
+ mutation,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ selected = _source("src_multimap01", "Selected supplier")
+ excluded = _source("src_multimap02", "Excluded fallback")
+ for source in (selected, excluded):
+ source.models = [
+ ModelHubModelConfig(id="target-one", provenance="manual"),
+ ModelHubModelConfig(id="target-two", provenance="manual"),
+ ]
+ config.sources.extend([selected, excluded])
+ backend = "claude" if mutation == "mapping" else "opencode"
+ original_order = list(config.agents[backend].sources.order)
+
+ if mutation == "mapping":
+ agent = asyncio.run(
+ service.set_mappings(
+ "claude",
+ [
+ {
+ "builtin_id": "claude-opus-4-6",
+ "target_model_id": "target-one",
+ "enabled": True,
+ },
+ {
+ "builtin_id": "claude-sonnet-4-6",
+ "target_model_id": "target-two",
+ "enabled": True,
+ },
+ ],
+ )
+ )
+ else:
+ agent = asyncio.run(
+ service.set_opencode_menu(
+ {
+ "view": "featured",
+ "checked": [
+ "anthropic/target-one",
+ "anthropic/target-two",
+ ],
+ }
+ )
+ )
+
+ assert agent["sources"]["order"] == [*original_order, selected.id]
+ assert excluded.id not in agent["sources"]["order"]
+
+
+def test_follow_order_exhaustively_enrolls_eligible_sources_and_stays_follow(
+ tmp_path,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ anthropic_native = _source("src_claude01", "Claude native")
+ anthropic_native.kind = "subscription"
+ anthropic_native.supply_channel = "native_cli"
+ anthropic_native.vendor = "anthropic"
+ anthropic_native.credential_ref = None
+ openai_native = _source("src_codex001", "Codex native")
+ openai_native.kind = "subscription"
+ openai_native.supply_channel = "native_cli"
+ openai_native.vendor = "openai"
+ openai_native.credential_ref = None
+ config.sources.extend([anthropic_native, openai_native])
+ for agent in config.agents.values():
+ agent.sources.policy = "follow"
+ agent.sources.order = []
+
+ for backend, agent in config.agents.items():
+ eligible = {
+ source.id
+ for source in config.sources
+ if config.source_eligible_for_backend(source, backend)
+ }
+ assert set(config.effective_source_order(backend)) == eligible
+ assert agent.sources.policy == "follow"
+
+ claude = asyncio.run(
+ service.set_mappings(
+ "claude",
+ [
+ {
+ "builtin_id": "claude-opus-4-6",
+ "target_model_id": "claude-opus-4-6",
+ "enabled": True,
+ }
+ ],
+ )
+ )
+ opencode = asyncio.run(
+ service.set_opencode_menu(
+ {
+ "view": "featured",
+ "checked": ["anthropic/claude-opus-4-6"],
+ }
+ )
+ )
+
+ assert claude["sources"]["policy"] == "follow"
+ assert opencode["sources"]["policy"] == "follow"
+
+
[email protected]("mutation", ["mapping", "menu"])
+def test_menu_mutations_reject_ineligible_sources_without_enrolling(
+ tmp_path,
+ mutation,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ candidate = _source("src_ineligible01", "Ineligible target")
+ candidate.kind = "subscription"
+ candidate.supply_channel = "native_cli"
+ candidate.vendor = "openai"
+ candidate.credential_ref = None
+ candidate.models = [
+ ModelHubModelConfig(id="ineligible-model", provenance="discovered")
+ ]
+ config.sources.append(candidate)
+ before = _serialized_config(service)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ if mutation == "mapping":
+ asyncio.run(
+ service.set_mappings(
+ "claude",
+ [
+ {
+ "builtin_id": "claude-opus-4-6",
+ "target_model_id": "ineligible-model",
+ "enabled": True,
+ }
+ ],
+ )
+ )
+ else:
+ asyncio.run(
+ service.set_opencode_menu(
+ {
+ "view": "featured",
+ "checked": ["openai/ineligible-model"],
+ }
+ )
+ )
+
+ assert exc_info.value.code == "mapping_target_unavailable"
+ assert _serialized_config(service) == before
+
+
class NarrowingCredentialAdapter(FakeAdapter):
def __init__(self, outcomes=()):
super().__init__(outcomes)
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index d5e567bff..7eaa72fc7 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -14,6 +14,7 @@ import time
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
+from types import SimpleNamespace
import pytest
import yaml
@@ -23,6 +24,7 @@ from core.handlers.model_hub.adapter import (
EngineHealth,
OriginNotAllowedError,
RawOutcomeKind,
+ RetainedMaterialDisposition,
SourceBinding,
)
from core.handlers.model_hub.classification import classify_outcome
@@ -103,6 +105,168 @@ def _binding(credential_ref: str, **overrides: object) -> SourceBinding:
return SourceBinding(**payload) # type: ignore[arg-type]
+def test_oauth_retained_material_vocabulary_and_pairing_guard() -> None:
+ assert {item.value for item in RetainedMaterialDisposition} == {
+ "none",
+ "flow_source_ref",
+ "orphan_ref",
+ "foreign_source_ref",
+ "unknown",
+ }
+ flow = SimpleNamespace(
+ retained_material_disposition=RetainedMaterialDisposition.NONE,
+ retained_credential_ref=None,
+ )
+
+ for disposition, credential_ref in (
+ (RetainedMaterialDisposition.NONE, None),
+ (RetainedMaterialDisposition.FLOW_SOURCE_REF, "cred_flow"),
+ (RetainedMaterialDisposition.ORPHAN_REF, "cred_orphan"),
+ (RetainedMaterialDisposition.FOREIGN_SOURCE_REF, None),
+ (RetainedMaterialDisposition.UNKNOWN, None),
+ ):
+ CLIProxyEngineAdapter._set_retained_material( # type: ignore[arg-type]
+ flow,
+ disposition,
+ credential_ref,
+ )
+
+ for disposition, credential_ref in (
+ (RetainedMaterialDisposition.NONE, "cred_invalid"),
+ (RetainedMaterialDisposition.FLOW_SOURCE_REF, None),
+ (RetainedMaterialDisposition.ORPHAN_REF, None),
+ (RetainedMaterialDisposition.FOREIGN_SOURCE_REF, "cred_invalid"),
+ (RetainedMaterialDisposition.UNKNOWN, "cred_invalid"),
+ ):
+ with pytest.raises(AssertionError, match="pairing"):
+ CLIProxyEngineAdapter._set_retained_material( # type: ignore[arg-type]
+ flow,
+ disposition,
+ credential_ref,
+ )
+
+
+def test_orphaned_oauth_cleanup_keeps_ref_until_deletes_are_confirmed(
+ tmp_path: Path,
+) -> None:
+ class Client:
+ fail_delete = True
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ assert (method, path) == ("DELETE", "/auth-files")
+ if self.fail_delete:
+ raise EngineClientError("delete failed")
+ return {"status": "ok"}
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+
+ def client_if_running(self):
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ auth_file = store.auth_dir / "claude-account.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o600)
+ credential_ref = store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ auth_file.name,
+ )
+ client = Client()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ assert await adapter.cleanup_orphaned_oauth_material(credential_ref) is False
+ assert store.credential_metadata(credential_ref)["auth_name"] == auth_file.name
+
+ client.fail_delete = False
+ assert await adapter.cleanup_orphaned_oauth_material(credential_ref) is True
+ with pytest.raises(EngineStateError, match="unavailable"):
+ store.credential_metadata(credential_ref)
+
+ asyncio.run(run())
+
+
+def test_orphaned_oauth_cleanup_retry_converges_after_journal_crash(
+ tmp_path: Path,
+) -> None:
+ class Client:
+ delete_calls = 0
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ assert (method, path) == ("DELETE", "/auth-files")
+ self.delete_calls += 1
+ return {"status": "ok"}
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+
+ def client_if_running(self):
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ auth_file = store.auth_dir / "claude-account.json"
+ auth_file.write_text("{}", encoding="utf-8")
+ auth_file.chmod(0o600)
+ credential_ref = store.bind_oauth_credential(
+ "src_fixture123",
+ "anthropic",
+ auth_file.name,
+ )
+ client = Client()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ cleanup_journal = {credential_ref}
+
+ assert await adapter.cleanup_orphaned_oauth_material(credential_ref) is True
+ assert credential_ref in cleanup_journal # Crash before journal clear.
+ assert await adapter.cleanup_orphaned_oauth_material(credential_ref) is True
+ cleanup_journal.remove(credential_ref)
+
+ assert cleanup_journal == set()
+ assert client.delete_calls == 1
+
+ asyncio.run(run())
+
+
+def test_orphaned_oauth_cleanup_never_existed_ref_is_converged(
+ tmp_path: Path,
+) -> None:
+ class Supervisor:
+ def client_if_running(self):
+ raise AssertionError("an absent ref must not reach the engine")
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ assert (
+ await adapter.cleanup_orphaned_oauth_material(
+ "cred_00000000000000000000000000000000"
+ )
+ is True
+ )
+
+ asyncio.run(run())
+
+
def test_packaged_manifest_matches_frozen_runtime_dependency_values(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -1410,7 +1574,18 @@ def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path)
@pytest.mark.parametrize(
"oauth_record_case",
- ["new", "refresh", "conflict", "patch_failure", "new_patch_failure"],
+ [
+ "new",
+ "refresh",
+ "conflict",
+ "duplicate_binding",
+ "metadata_failure",
+ "patch_failure",
+ "new_patch_failure",
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ "new_patch_revoke_failure",
+ ],
)
def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
tmp_path: Path,
@@ -1425,11 +1600,20 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
def management_request(self, method, path, *, query=None, payload=None, timeout=None):
if path == "/auth-files":
if method == "DELETE":
+ if oauth_record_case == "new_patch_engine_delete_failure":
+ raise EngineClientError("delete failed")
self.deletes.append(str((query or {}).get("name")))
return {"status": "ok"}
self.auth_calls += 1
if self.auth_calls == 1:
- if oauth_record_case in {"new", "new_patch_failure"}:
+ if oauth_record_case in {
+ "new",
+ "metadata_failure",
+ "new_patch_failure",
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ "new_patch_revoke_failure",
+ }:
return {"files": []}
return {
"files": [
@@ -1456,7 +1640,13 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
if path == "/get-auth-status":
return {"status": "ok"}
if path == "/auth-files/fields":
- if oauth_record_case in {"patch_failure", "new_patch_failure"}:
+ if oauth_record_case in {
+ "patch_failure",
+ "new_patch_failure",
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ "new_patch_revoke_failure",
+ }:
raise EngineClientError("patch failed")
self.patches.append(dict(payload or {}))
return {"status": "ok"}
@@ -1483,13 +1673,24 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
(store.auth_dir / "claude-account.json").chmod(0o600)
existing_ref = None
existing_prefix = None
- if oauth_record_case not in {"new", "new_patch_failure"}:
+ if oauth_record_case not in {
+ "new",
+ "metadata_failure",
+ "new_patch_failure",
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ "new_patch_revoke_failure",
+ }:
existing_ref = store.bind_oauth_credential(
"src_other1234" if oauth_record_case == "conflict" else "src_fixture123",
"anthropic",
"claude-account.json",
)
existing_prefix = store.credential_metadata(existing_ref)["prefix"]
+ if oauth_record_case == "duplicate_binding":
+ duplicate_path = store._credential_path(f"cred_{'f' * 32}")
+ duplicate_path.write_bytes(store._credential_path(existing_ref).read_bytes())
+ duplicate_path.chmod(0o600)
if oauth_record_case == "patch_failure":
store.sync_sources(
[
@@ -1502,6 +1703,32 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
)
]
)
+
+ original_metadata = store.credential_metadata
+ original_local_delete = store.delete_oauth_auth_file
+ original_revoke = store.revoke_credential
+ revoke_calls: list[str] = []
+
+ def credential_metadata(credential_ref: str):
+ payload = original_metadata(credential_ref)
+ if oauth_record_case == "metadata_failure" and payload.get("source_id") == "src_fixture123":
+ raise EngineStateError("metadata read failed")
+ return payload
+
+ def delete_oauth_auth_file(auth_name: str) -> None:
+ if oauth_record_case == "new_patch_local_delete_failure":
+ raise EngineStateError("local delete failed")
+ original_local_delete(auth_name)
+
+ def revoke_credential(credential_ref: str) -> None:
+ revoke_calls.append(credential_ref)
+ if oauth_record_case == "new_patch_revoke_failure":
+ raise EngineStateError("revoke failed")
+ original_revoke(credential_ref)
+
+ store.credential_metadata = credential_metadata # type: ignore[method-assign]
+ store.delete_oauth_auth_file = delete_oauth_auth_file # type: ignore[method-assign]
+ store.revoke_credential = revoke_credential # type: ignore[method-assign]
client = Client()
adapter = CLIProxyEngineAdapter(
supervisor=Supervisor(store, client), # type: ignore[arg-type]
@@ -1519,13 +1746,35 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
if oauth_record_case == "conflict":
assert completed.state == "failed"
assert completed.error_key == "models.oauth.binding_failed"
+ assert completed.channel == "hub"
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.FOREIGN_SOURCE_REF
+ assert completed.retained_credential_ref is None
assert concurrent.state == "failed"
retry = await adapter.start_oauth("src_fixture123", "anthropic")
assert retry.state == "awaiting_action"
assert not client.patches
return
- if oauth_record_case in {"patch_failure", "new_patch_failure"}:
+ if oauth_record_case == "duplicate_binding":
+ assert completed.state == "failed"
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.UNKNOWN
+ assert completed.retained_credential_ref is None
+ return
+
+ if oauth_record_case == "metadata_failure":
+ assert completed.state == "failed"
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.FLOW_SOURCE_REF
+ assert completed.retained_credential_ref is not None
+ assert completed.credential_ref is None
+ return
+
+ if oauth_record_case in {
+ "patch_failure",
+ "new_patch_failure",
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ "new_patch_revoke_failure",
+ }:
assert completed.state == "failed"
assert completed.error_key == "models.oauth.binding_failed"
assert concurrent.state == "failed"
@@ -1533,17 +1782,36 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records(
assert store.credential_metadata(existing_ref)["prefix"] == existing_prefix
assert (store.auth_dir / "claude-account.json").exists()
assert not client.deletes
- else:
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.FLOW_SOURCE_REF
+ assert completed.retained_credential_ref == existing_ref
+ elif oauth_record_case == "new_patch_failure":
assert client.deletes == ["claude-account.json"]
assert not (store.auth_dir / "claude-account.json").exists()
assert not list((store.root / "credentials").glob("*.json"))
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.NONE
+ assert completed.retained_credential_ref is None
+ assert len(revoke_calls) == 1
+ else:
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.ORPHAN_REF
+ assert completed.retained_credential_ref is not None
+ assert store._credential_path(completed.retained_credential_ref).exists()
+ if oauth_record_case in {
+ "new_patch_engine_delete_failure",
+ "new_patch_local_delete_failure",
+ }:
+ assert revoke_calls == []
+ else:
+ assert revoke_calls == [completed.retained_credential_ref]
retry = await adapter.start_oauth("src_fixture123", "anthropic")
assert retry.state == "awaiting_action"
return
assert completed.state == "success"
+ assert completed.channel == "hub"
assert completed.source_id == "src_fixture123"
assert completed.credential_ref and completed.credential_ref.startswith("cred_")
+ assert completed.retained_material_disposition is RetainedMaterialDisposition.FLOW_SOURCE_REF
+ assert completed.retained_credential_ref == completed.credential_ref
if oauth_record_case == "refresh":
assert completed.credential_ref == existing_ref
assert concurrent.credential_ref == completed.credential_ref
@@ -1609,6 +1877,8 @@ def test_oauth_flow_releases_provider_after_engine_failure_or_expiry(tmp_path: P
failed = await adapter.oauth_status(failed_flow.flow_id)
assert failed.state == "failed"
assert failed.error_key == "models.oauth.engine_unavailable"
+ assert failed.retained_material_disposition is RetainedMaterialDisposition.NONE
+ assert failed.retained_credential_ref is None
supervisor.unavailable = False
expiring_flow = await adapter.start_oauth("src_other1234", "anthropic")
@@ -1618,6 +1888,57 @@ def test_oauth_flow_releases_provider_after_engine_failure_or_expiry(tmp_path: P
expired = await adapter.oauth_status(expiring_flow.flow_id)
assert expired.state == "failed"
assert expired.error_key == "models.oauth.expired"
+ assert expired.retained_material_disposition is RetainedMaterialDisposition.NONE
+ assert expired.retained_credential_ref is None
+
+ asyncio.run(run())
+
+
+def test_oauth_terminal_uncertainty_never_claims_cleanup(tmp_path: Path) -> None:
+ class Client:
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ if path == "/auth-files":
+ return {"files": []}
+ if path == "/anthropic-auth-url":
+ return {"state": "browser-state", "url": "https://example.test/oauth"}
+ if path == "/codex-auth-url":
+ return {
+ "state": "device-state",
+ "flow": "device",
+ "user_code": "ABCD-EFGH",
+ "url": "https://example.test/device",
+ }
+ if path == "/oauth-callback":
+ raise EngineClientError("response lost after submission")
+ raise AssertionError((method, path, query, payload, timeout))
+
+ class Supervisor:
+ def __init__(self, store: EngineStateStore, client: Client) -> None:
+ self.state_store = store
+ self._client = client
+
+ def client(self):
+ return self._client
+
+ async def run() -> None:
+ store = EngineStateStore(tmp_path / "state")
+ adapter = CLIProxyEngineAdapter(
+ supervisor=Supervisor(store, Client()), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ browser = await adapter.start_oauth("src_fixture123", "anthropic")
+ failed = await adapter.submit_oauth(browser.flow_id, "callback-code")
+ assert failed.state == "failed"
+ assert failed.retained_material_disposition is RetainedMaterialDisposition.UNKNOWN
+ assert failed.retained_credential_ref is None
+
+ device = await adapter.start_oauth("src_other1234", "openai")
+ adapter._oauth_flows[device.flow_id].expires_at_iso = "2000-01-01T00:00:00+00:00"
+ expired = await adapter.oauth_status(device.flow_id)
+ assert expired.state == "failed"
+ assert expired.retained_material_disposition is RetainedMaterialDisposition.UNKNOWN
+ assert expired.retained_credential_ref is None
asyncio.run(run())
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 05d8d3bd9..a2a446732 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -15,6 +15,7 @@ from core.handlers.model_hub.adapter import (
OriginNotAllowedError,
RawCallOutcome,
RawOutcomeKind,
+ RetainedMaterialDisposition,
SourceBinding,
)
from core.handlers.model_hub.errors import ModelDiscoveryError
@@ -68,6 +69,10 @@ class _OAuthFlow:
state: str = "awaiting_action"
error_key: str | None = None
credential_ref: str | None = None
+ retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONE
+ retained_credential_ref: str | None = None
+ grant_write_possible: bool = False
+ retained_material_decided: bool = False
operation_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
def snapshot(self) -> OAuthFlowState:
@@ -83,6 +88,9 @@ class _OAuthFlow:
error_key=self.error_key,
expires_at_iso=self.expires_at_iso,
credential_ref=self.credential_ref,
+ channel="hub",
+ retained_material_disposition=self.retained_material_disposition,
+ retained_credential_ref=self.retained_credential_ref,
)
@@ -197,6 +205,33 @@ class CLIProxyEngineAdapter:
await asyncio.to_thread(self.supervisor.invalidate_configs)
await asyncio.to_thread(self.state_store.revoke_credential, credential_ref)
+ async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:
+ try:
+ await asyncio.to_thread(
+ self.state_store.assert_credential_unbound,
+ credential_ref,
+ )
+ metadata = await asyncio.to_thread(
+ self.state_store.credential_metadata_if_present,
+ credential_ref,
+ )
+ except EngineStateError:
+ return False
+ # Revocation is ordered after both auth-file deletions. Therefore an
+ # absent ref proves cleanup already converged, including never-created
+ # refs whose postcondition held vacuously.
+ if metadata is None:
+ return True
+ auth_name = metadata.get("auth_name") if metadata["kind"] == "oauth" else None
+ if not isinstance(auth_name, str) or not auth_name:
+ return False
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ return await self._cleanup_oauth_material(
+ client,
+ auth_name,
+ credential_ref,
+ )
+
async def discover_models(
self,
vendor: str,
@@ -278,6 +313,7 @@ class CLIProxyEngineAdapter:
device_code=device_code,
expires_at_iso=(datetime.now(timezone.utc) + timedelta(seconds=expires_in)).isoformat(),
before_auth_fingerprints={identity: record.fingerprint for identity, record in before.items()},
+ grant_write_possible=expects == "none",
)
except Exception:
with self._oauth_lock:
@@ -323,6 +359,9 @@ class CLIProxyEngineAdapter:
submitted = value.strip()
if not submitted:
raise EngineStateError("OAuth submission is empty")
+ # A transport failure after submission begins cannot prove whether
+ # the engine wrote grant material.
+ flow.grant_write_possible = True
payload: dict[str, str] = {
"provider": flow.callback_provider,
"state": flow.engine_state,
@@ -361,6 +400,7 @@ class CLIProxyEngineAdapter:
)
except (EngineClientError, EngineUnavailableError):
pass
+ self._mark_retention_unknown_if_needed(flow)
flow.state = "cancelled"
self._release_provider(flow)
@@ -408,6 +448,7 @@ class CLIProxyEngineAdapter:
)
async def _complete_oauth(self, flow: _OAuthFlow, client: EngineClient) -> None:
+ flow.grant_write_possible = True
inventory = await asyncio.to_thread(_auth_inventory, client)
provider_records = [record for record in inventory.values() if record.provider == flow.auth_provider]
candidates = [
@@ -421,6 +462,7 @@ class CLIProxyEngineAdapter:
if not candidates:
flow.state = "verifying"
return
+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)
self._fail_flow(flow, "models.oauth.ambiguous_engine_binding")
return
auth = candidates[0]
@@ -429,17 +471,64 @@ class CLIProxyEngineAdapter:
self.state_store.oauth_credential_ref,
auth.name,
)
+ except EngineStateError:
+ # The grant changed but duplicate persisted metadata means no single
+ # ref can be named safely.
+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)
+ self._fail_flow(flow, "models.oauth.binding_failed")
+ return
+
+ existing_source_id: str | None = None
+ if existing_credential_ref is not None:
+ try:
+ existing_credential = await asyncio.to_thread(
+ self.state_store.credential_metadata,
+ existing_credential_ref,
+ )
+ except EngineStateError:
+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)
+ self._fail_flow(flow, "models.oauth.binding_failed")
+ return
+ value = existing_credential.get("source_id")
+ existing_source_id = str(value) if value else None
+
+ try:
credential_ref = await asyncio.to_thread(
self.state_store.bind_oauth_credential,
flow.source_id,
flow.vendor,
auth.name,
)
+ except EngineStateError:
+ if existing_credential_ref is None or existing_source_id is None:
+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)
+ elif existing_source_id == flow.source_id:
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ existing_credential_ref,
+ )
+ else:
+ # The existing ref belongs to another source. Withhold it so a
+ # consumer cannot revoke or journal foreign material.
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.FOREIGN_SOURCE_REF,
+ )
+ self._fail_flow(flow, "models.oauth.binding_failed")
+ return
+
+ try:
credential = await asyncio.to_thread(
self.state_store.credential_metadata,
credential_ref,
)
except EngineStateError:
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ credential_ref,
+ )
self._fail_flow(flow, "models.oauth.binding_failed")
return
try:
@@ -451,37 +540,83 @@ class CLIProxyEngineAdapter:
)
await asyncio.to_thread(self.state_store.audit_auth_permissions, enforce=True)
except (EngineClientError, EngineStateError):
- if existing_credential_ref is None:
- if auth.identity not in flow.before_auth_fingerprints:
- try:
- await asyncio.to_thread(
- client.management_request,
- "DELETE",
- "/auth-files",
- query={"name": auth.name},
- )
- except EngineClientError:
- pass
- try:
- await asyncio.to_thread(
- self.state_store.delete_oauth_auth_file,
- auth.name,
- )
- except EngineStateError:
- pass
- try:
- await asyncio.to_thread(
- self.state_store.revoke_credential,
+ if existing_credential_ref is not None:
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ credential_ref,
+ )
+ else:
+ # Never destroy the only cleanup handle while grant material
+ # may remain behind it. Both auth-file deletions must be
+ # confirmed before revocation can discard the minted ref.
+ if auth.identity not in flow.before_auth_fingerprints and await self._cleanup_oauth_material(
+ client,
+ auth.name,
+ credential_ref,
+ ):
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.NONE,
+ )
+ else:
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.ORPHAN_REF,
credential_ref,
)
- except EngineStateError:
- pass
self._fail_flow(flow, "models.oauth.binding_failed")
return
flow.credential_ref = credential_ref
+ self._set_retained_material(
+ flow,
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ credential_ref,
+ )
flow.state = "success"
self._release_provider(flow)
+ async def _cleanup_oauth_material(
+ self,
+ client: EngineClient | None,
+ auth_name: str,
+ credential_ref: str,
+ ) -> bool:
+ engine_delete_succeeded = client is None
+ if client is not None:
+ try:
+ await asyncio.to_thread(
+ client.management_request,
+ "DELETE",
+ "/auth-files",
+ query={"name": auth_name},
+ )
+ except EngineClientError:
+ engine_delete_succeeded = False
+ else:
+ engine_delete_succeeded = True
+
+ try:
+ await asyncio.to_thread(
+ self.state_store.delete_oauth_auth_file,
+ auth_name,
+ )
+ except EngineStateError:
+ local_delete_succeeded = False
+ else:
+ local_delete_succeeded = True
+
+ if not (engine_delete_succeeded and local_delete_succeeded):
+ return False
+ try:
+ await asyncio.to_thread(
+ self.state_store.revoke_credential,
+ credential_ref,
+ )
+ except EngineStateError:
+ return False
+ return True
+
def _get_flow(self, flow_id: str) -> _OAuthFlow:
with self._oauth_lock:
self._expire_oauth_flows_locked()
@@ -491,10 +626,32 @@ class CLIProxyEngineAdapter:
return flow
def _fail_flow(self, flow: _OAuthFlow, error_key: str) -> None:
+ self._mark_retention_unknown_if_needed(flow)
flow.state = "failed"
flow.error_key = error_key
self._release_provider(flow)
+ @staticmethod
+ def _set_retained_material(
+ flow: _OAuthFlow,
+ disposition: RetainedMaterialDisposition,
+ credential_ref: str | None = None,
+ ) -> None:
+ carries_ref = disposition in {
+ RetainedMaterialDisposition.FLOW_SOURCE_REF,
+ RetainedMaterialDisposition.ORPHAN_REF,
+ }
+ if carries_ref != (credential_ref is not None):
+ raise AssertionError("retained material disposition/ref pairing is invalid")
+ flow.retained_material_disposition = disposition
+ flow.retained_credential_ref = credential_ref
+ flow.retained_material_decided = True
+
+ @classmethod
+ def _mark_retention_unknown_if_needed(cls, flow: _OAuthFlow) -> None:
+ if flow.grant_write_possible and not flow.retained_material_decided:
+ cls._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)
+
def _release_provider(self, flow: _OAuthFlow) -> None:
with self._oauth_lock:
self._active_oauth_providers.discard(flow.auth_provider)
@@ -520,6 +677,7 @@ class CLIProxyEngineAdapter:
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
if expires_at <= now:
+ self._mark_retention_unknown_if_needed(flow)
flow.state = "failed"
flow.error_key = "models.oauth.expired"
self._active_oauth_providers.discard(flow.auth_provider)
@@ -570,11 +728,7 @@ def _model_ids(payload: Mapping[str, Any]) -> tuple[str, ...]:
return ()
result: list[str] = []
for item in models:
- value = (
- item.get("id") or item.get("alias") or item.get("name")
- if isinstance(item, dict)
- else item
- )
+ value = item.get("id") or item.get("alias") or item.get("name") if isinstance(item, dict) else item
if isinstance(value, str) and value and value not in result:
result.append(value)
return tuple(result)
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index dca835be4..55d7adef4 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -250,19 +250,29 @@ class EngineStateStore:
return updated_record
def credential_metadata(self, credential_ref: str) -> dict[str, Any]:
- path = self._credential_path(credential_ref)
- try:
- mode = path.lstat().st_mode
- except FileNotFoundError:
- mode = 0
- if mode and (not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600):
- raise EngineStateError("credential permissions are unsafe")
- payload = self._read_json(path)
- kind = payload.get("kind") if payload else None
- if kind not in {"api_key", "oauth"}:
+ payload = self.credential_metadata_if_present(credential_ref)
+ if payload is None:
raise EngineStateError("credential is unavailable")
return payload
+ def credential_metadata_if_present(
+ self,
+ credential_ref: str,
+ ) -> dict[str, Any] | None:
+ with self._lock:
+ path = self._credential_path(credential_ref)
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ return None
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise EngineStateError("credential permissions are unsafe")
+ payload = self._read_json(path)
+ kind = payload.get("kind") if payload else None
+ if kind not in {"api_key", "oauth"}:
+ raise EngineStateError("credential is unavailable")
+ return payload
+
def validate_api_key_target(
self,
credential_ref: str,