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.

fix(config): recover legacy model hub files on load (#1345)

Call Whitebbbf30a04557
diff --git a/config/v2_config.py b/config/v2_config.py
index 6edda44cf..4974457c3 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1,14 +1,16 @@
+import copy
import ipaddress
import json
import logging
import os
import re
+import shutil
import tempfile
import threading
from dataclasses import dataclass, field, fields
from datetime import datetime
from pathlib import Path
-from typing import List, Literal, Mapping, Optional, Union
+from typing import ClassVar, List, Literal, Mapping, Optional, Union
from urllib.parse import parse_qsl, urlsplit, urlunsplit
from config import paths
@@ -116,6 +118,16 @@ DEFAULT_AGENT_PROGRESS_STYLE = "off"
MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
MODEL_HUB_BACKENDS = ("claude", "codex", "opencode")
MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"
+_LEGACY_CLAUDE_FAMILY_ALIASES = {
+ "opus": "opus",
+ "opus[1m]": "opus",
+ "sonnet": "sonnet",
+ "sonnet[1m]": "sonnet",
+ "haiku": "haiku",
+}
+_LEGACY_CLAUDE_MODEL_ID = re.compile(
+ r"^claude-(?P<family>opus|sonnet|haiku|fable)-(?P<version>\d+(?:-\d+)*?)(?:-(?P<date>\d{8}))?$"
+)
def normalize_model_hub_vendor_id(value: object) -> str:
@@ -212,6 +224,786 @@ def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:
return migrated_payload
+def _legacy_source_eligible_for_backend(source: object, backend: str) -> bool:
+ if not isinstance(source, dict):
+ return False
+ if source.get("kind") == "api_key":
+ return source.get("supply_channel") == "hub"
+ expected_backend = {"anthropic": "claude", "openai": "codex"}.get(source.get("vendor"))
+ return expected_backend == backend
+
+
+def _legacy_recommended_source_order(
+ sources: dict[str, dict],
+ backend: str,
+) -> list[str]:
+ def sort_key(source: dict) -> tuple[object, ...]:
+ if source.get("kind") == "subscription":
+ return (
+ 0,
+ 0 if source.get("supply_channel") == "native_cli" else 1,
+ str(source.get("id") or ""),
+ )
+ created_at = str(source.get("created_at") or MODEL_HUB_LEGACY_CREATED_AT)
+ try:
+ created_timestamp = datetime.fromisoformat(created_at.replace("Z", "+00:00")).timestamp()
+ except (TypeError, ValueError, OverflowError):
+ created_timestamp = 0
+ return (1, created_timestamp, str(source.get("id") or ""))
+
+ return [
+ str(source.get("id"))
+ for source in sorted(sources.values(), key=sort_key)
+ if _legacy_source_eligible_for_backend(source, backend)
+ ]
+
+
+def _legacy_source_order(
+ model_hub: dict,
+ sources: dict[str, dict],
+ agent: dict,
+ backend: str,
+) -> list[str]:
+ source_settings = agent.get("sources")
+ if isinstance(source_settings, dict):
+ policy = source_settings.get("policy")
+ order = source_settings.get("order")
+ if policy is None and isinstance(order, list):
+ return [
+ source_id
+ for source_id in order
+ if isinstance(source_id, str)
+ and source_id in sources
+ and _legacy_source_eligible_for_backend(sources[source_id], backend)
+ ]
+ if policy == "custom" and isinstance(order, list):
+ return [
+ source_id
+ for source_id in order
+ if isinstance(source_id, str)
+ and source_id in sources
+ and _legacy_source_eligible_for_backend(sources[source_id], backend)
+ ]
+ if policy == "follow":
+ return _legacy_recommended_source_order(sources, backend)
+
+ priority_order = model_hub.get("priority_order")
+ if isinstance(priority_order, list):
+ ordered = [
+ source_id
+ for source_id in priority_order
+ if isinstance(source_id, str)
+ and source_id in sources
+ and _legacy_source_eligible_for_backend(sources[source_id], backend)
+ ]
+ if ordered:
+ return ordered
+ return _legacy_recommended_source_order(sources, backend)
+
+
+def _legacy_source_order_setting_is_valid(value: object, *, required: bool = False) -> bool:
+ """Validate the pre-v5 source-order shape before migration can infer hops."""
+
+ if not isinstance(value, dict):
+ return False
+ if set(value) - {"policy", "order"}:
+ return False
+ policy = value.get("policy")
+ if policy is not None and not isinstance(policy, str):
+ return False
+ if policy not in {None, "custom", "follow"}:
+ return False
+ if required and not isinstance(value.get("order"), list):
+ return False
+ order = value.get("order")
+ if order is None:
+ return not required
+ return (
+ isinstance(order, list)
+ and all(isinstance(source_id, str) for source_id in order)
+ and len(order) == len(set(order))
+ )
+
+
+def _legacy_mapping_is_valid(value: object) -> bool:
+ """Match the pre-v5 mapping parser's required fields and types."""
+
+ if (
+ not isinstance(value, dict)
+ or set(value) - {"builtin_id", "target_model_id", "enabled"}
+ or not isinstance(value.get("builtin_id"), str)
+ or not value["builtin_id"]
+ or not isinstance(value.get("enabled"), bool)
+ ):
+ return False
+ target_model_id = value.get("target_model_id")
+ if value["enabled"]:
+ return isinstance(target_model_id, str) and bool(target_model_id)
+ return target_model_id is None or isinstance(target_model_id, str)
+
+
+def _legacy_claude_matching_model_id(source: dict, requested_model: str) -> str | None:
+ """Resolve the pre-v5 Claude aliases against discovered native models.
+
+ Claude's old native CLI resolver treated ``opus``/``sonnet``/``haiku`` as
+ family selectors and persisted the newest concrete model it observed. Keep
+ that behavior at the disk migration boundary; the current runtime resolver
+ intentionally only follows persisted exact hops.
+ """
+
+ if source.get("vendor") != "anthropic":
+ return None
+ observed_models = [
+ model
+ for model in source.get("models") or []
+ if isinstance(model, dict)
+ and model.get("origin", model.get("provenance")) == "discovered"
+ ]
+ family = _LEGACY_CLAUDE_FAMILY_ALIASES.get(requested_model)
+ requested_version: tuple[int, ...] | None = None
+ match = _LEGACY_CLAUDE_MODEL_ID.fullmatch(requested_model)
+ requested_date: int | None = None
+ if family is None and match is not None:
+ family = match.group("family")
+ requested_version = tuple(int(part) for part in match.group("version").split("-"))
+ requested_date = int(match.group("date")) if match.group("date") else None
+ if family is None:
+ return None
+ if requested_date is not None:
+ return next(
+ (
+ model.get("id")
+ for model in observed_models
+ if model.get("id") == requested_model
+ ),
+ None,
+ )
+
+ matches: list[tuple[tuple[int, ...], int, str]] = []
+ for model in observed_models:
+ model_id = model.get("id")
+ if not isinstance(model_id, str):
+ continue
+ parsed = _LEGACY_CLAUDE_MODEL_ID.fullmatch(model_id)
+ if parsed is None or parsed.group("family") != family:
+ continue
+ version = tuple(int(part) for part in parsed.group("version").split("-"))
+ if requested_version is not None and version != requested_version:
+ continue
+ date = int(parsed.group("date")) if parsed.group("date") else 0
+ matches.append((version, date, model_id))
+ return max(matches)[2] if matches else None
+
+
+def _legacy_route_hops(
+ sources: dict[str, dict],
+ source_order: list[str],
+ backend: str,
+ target_model_id: str,
+) -> list[dict[str, str]]:
+ provider: Optional[str] = None
+ bare_target = backend == "opencode" and "/" not in target_model_id
+ if backend == "opencode":
+ if not bare_target:
+ try:
+ provider, target_model_id = canonical_opencode_menu_identity(target_model_id)
+ except ValueError:
+ return []
+ hops: list[dict[str, str]] = []
+ bare_matches: list[dict[str, str]] = []
+ for source_id in source_order:
+ source = sources[source_id]
+ legacy_claude_model_id = (
+ _legacy_claude_matching_model_id(source, target_model_id)
+ if backend == "claude"
+ else None
+ )
+ if legacy_claude_model_id is not None:
+ hops.append({"source_id": source_id, "model_id": legacy_claude_model_id})
+ continue
+ for model in source.get("models") or []:
+ if not isinstance(model, dict) or not isinstance(model.get("id"), str):
+ continue
+ model_id = model["id"]
+ if provider is not None:
+ try:
+ source_provider, source_model_id = canonical_opencode_menu_identity(
+ f"{source.get('vendor') or ''}/{model_id}"
+ )
+ except ValueError:
+ try:
+ source_provider, source_model_id = canonical_opencode_menu_identity(
+ f"custom/{model_id}"
+ )
+ except ValueError:
+ continue
+ if (source_provider, source_model_id) != (provider, target_model_id):
+ continue
+ hops.append({"source_id": source_id, "model_id": model_id})
+ continue
+ if bare_target:
+ try:
+ _, source_model_id = canonical_opencode_menu_identity(
+ f"{source.get('vendor') or ''}/{model_id}"
+ )
+ except ValueError:
+ try:
+ _, source_model_id = canonical_opencode_menu_identity(
+ f"custom/{model_id}"
+ )
+ except ValueError:
+ continue
+ if source_model_id == target_model_id or source_model_id.endswith(
+ f"/{target_model_id}"
+ ):
+ bare_matches.append({"source_id": source_id, "model_id": model_id})
+ continue
+ if model_id == target_model_id:
+ hops.append({"source_id": source_id, "model_id": model_id})
+ if bare_target and len(bare_matches) == 1:
+ return bare_matches
+ return hops
+
+
+def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
+ """Convert the pre-v5 Model Hub shape before the strict parser runs.
+
+ The final parser intentionally rejects retired fields. Disk loading is the
+ compatibility boundary, so old ``mappings`` are converted into exact route
+ hops when the old model inventory identifies their source unambiguously.
+ Unrepresentable mappings remain in the untouched backup and produce a load
+ warning instead of silently selecting a different source.
+ """
+
+ model_hub = payload.get("model_hub")
+ if not isinstance(model_hub, dict):
+ return payload, False, ()
+ agents = model_hub.get("agents")
+ if not isinstance(agents, dict):
+ return payload, False, ()
+ if set(agents) - set(MODEL_HUB_BACKENDS):
+ return payload, False, ()
+ raw_sources = model_hub.get("sources")
+ if raw_sources is not None and not isinstance(raw_sources, list):
+ return payload, False, ()
+ if "priority_order" in model_hub and not _legacy_source_order_setting_is_valid(
+ {"order": model_hub["priority_order"]}
+ ):
+ return payload, False, ()
+ if (
+ "subscription_hub_experimental" in model_hub
+ and not isinstance(model_hub["subscription_hub_experimental"], bool)
+ ):
+ return payload, False, ()
+ legacy_sources_by_id = {
+ source.get("id"): source
+ for source in raw_sources or []
+ if isinstance(source, dict) and isinstance(source.get("id"), str)
+ }
+ if "priority_order" in model_hub and any(
+ source_id not in legacy_sources_by_id
+ for source_id in model_hub["priority_order"]
+ ):
+ return payload, False, ()
+ for source in raw_sources or []:
+ if not isinstance(source, dict):
+ return payload, False, ()
+ models = source.get("models")
+ if "models" in source and not isinstance(models, list):
+ return payload, False, ()
+ if isinstance(models, list) and any(not isinstance(model, dict) for model in models):
+ return payload, False, ()
+ for model in models or []:
+ if "provenance" not in model:
+ continue
+ provenance = model["provenance"]
+ if not isinstance(provenance, str) or provenance not in {"discovered", "manual"}:
+ return payload, False, ()
+ if "origin" in model and model["origin"] != provenance:
+ return payload, False, ()
+ if "experimental_consent_at" in source:
+ try:
+ _validate_optional_datetime(
+ source["experimental_consent_at"],
+ "model_hub.sources.experimental_consent_at",
+ )
+ except (TypeError, ValueError):
+ return payload, False, ()
+ for backend, agent in agents.items():
+ if not isinstance(agent, dict):
+ return payload, False, ()
+ if set(agent) - {
+ "backend",
+ "mode",
+ "menu_kind",
+ "sources",
+ "mappings",
+ "routes",
+ "menu",
+ }:
+ return payload, False, ()
+ expected_menu_kind = "open" if backend == "opencode" else "fixed"
+ if agent.get("backend") != backend or agent.get("menu_kind") != expected_menu_kind:
+ return payload, False, ()
+ if "mode" in agent:
+ mode = agent["mode"]
+ if not isinstance(mode, str) or mode not in {"hub", "direct"}:
+ return payload, False, ()
+ mappings = agent.get("mappings")
+ if "mappings" in agent and not isinstance(mappings, list):
+ return payload, False, ()
+ if isinstance(mappings, list) and any(
+ not _legacy_mapping_is_valid(mapping) for mapping in mappings
+ ):
+ return payload, False, ()
+ if backend in {"claude", "codex"}:
+ fixed_menu_ids = set(model_hub_fixed_menu_ids(backend))
+ if any(
+ mapping["enabled"] and mapping["builtin_id"] not in fixed_menu_ids
+ for mapping in mappings or []
+ ):
+ return payload, False, ()
+ if "routes" in agent and not isinstance(agent["routes"], dict):
+ return payload, False, ()
+ menu = agent.get("menu")
+ if isinstance(menu, dict) and "checked" in menu and not isinstance(menu["checked"], list):
+ return payload, False, ()
+ if "sources" in agent:
+ source_settings = agent["sources"]
+ if not _legacy_source_order_setting_is_valid(
+ source_settings,
+ required=isinstance(source_settings, dict)
+ and source_settings.get("policy") == "custom",
+ ):
+ return payload, False, ()
+ if (
+ isinstance(source_settings, dict)
+ and source_settings.get("policy") in {None, "custom"}
+ and isinstance(source_settings.get("order"), list)
+ and any(
+ source_id not in legacy_sources_by_id
+ or not _legacy_source_eligible_for_backend(
+ legacy_sources_by_id[source_id],
+ backend,
+ )
+ for source_id in source_settings["order"]
+ )
+ ):
+ return payload, False, ()
+ has_legacy_shape = bool(
+ {"priority_order", "subscription_hub_experimental"} & set(model_hub)
+ or any(isinstance(agent, dict) and "mappings" in agent for agent in agents.values())
+ or any(
+ isinstance(source, dict)
+ and "experimental_consent_at" in source
+ for source in raw_sources or []
+ )
+ or any(
+ isinstance(source, dict)
+ and any(
+ isinstance(model, dict)
+ and ("provenance" in model or "reasoning_efforts" not in model)
+ for model in source.get("models") or []
+ )
+ for source in raw_sources or []
+ )
+ )
+ if not has_legacy_shape:
+ return payload, False, ()
+
+ migrated_payload = copy.deepcopy(payload)
+ migrated_model_hub = migrated_payload["model_hub"]
+ migrated_model_hub.pop("priority_order", None)
+ migrated_model_hub.pop("subscription_hub_experimental", None)
+
+ raw_sources = migrated_model_hub.get("sources") or []
+ sources_by_id: dict[str, dict] = {}
+ for source in raw_sources:
+ if not isinstance(source, dict):
+ continue
+ source.pop("experimental_consent_at", None)
+ for model in source.get("models") or []:
+ if not isinstance(model, dict):
+ continue
+ if "provenance" in model:
+ if "origin" not in model:
+ model["origin"] = model["provenance"]
+ model.pop("provenance", None)
+ if "reasoning_efforts" not in model:
+ model["reasoning_efforts"] = []
+ source_id = source.get("id")
+ if isinstance(source_id, str):
+ sources_by_id[source_id] = source
+
+ warnings: list[str] = []
+ migrated_agents: dict[str, object] = {}
+ for backend in MODEL_HUB_BACKENDS:
+ raw_agent = agents.get(backend)
+ if not isinstance(raw_agent, dict):
+ continue
+
+ agent = copy.deepcopy(raw_agent)
+ source_order = _legacy_source_order(migrated_model_hub, sources_by_id, agent, backend)
+ source_settings = {"order": source_order}
+ route_ids: list[str]
+ if backend in {"claude", "codex"}:
+ route_ids = list(model_hub_fixed_menu_ids(backend))
+ else:
+ menu = agent.get("menu")
+ checked = menu.get("checked") if isinstance(menu, dict) else []
+ route_ids = [item for item in checked if isinstance(item, str)]
+
+ if isinstance(agent.get("routes"), dict):
+ routes = copy.deepcopy(agent["routes"])
+ else:
+ old_mappings = agent.get("mappings")
+ mappings = old_mappings if isinstance(old_mappings, list) else []
+ # The legacy resolver selected the first enabled mapping in list
+ # order. Disabled duplicates must not shadow an earlier active one.
+ mapping_by_menu: dict[str, dict] = {}
+ for item in mappings:
+ if not isinstance(item, dict) or item.get("enabled") is not True:
+ continue
+ builtin_id = item.get("builtin_id")
+ if isinstance(builtin_id, str) and builtin_id not in mapping_by_menu:
+ mapping_by_menu[builtin_id] = item
+ if backend == "opencode":
+ route_ids.extend(
+ builtin_id
+ for builtin_id, mapping in mapping_by_menu.items()
+ if builtin_id not in route_ids and mapping.get("enabled") is True
+ )
+ routes = {}
+ for model_id in route_ids:
+ mapping = mapping_by_menu.get(model_id)
+ target_model_id = model_id
+ if isinstance(mapping, dict) and mapping.get("enabled") is True:
+ target = mapping.get("target_model_id")
+ if isinstance(target, str) and target:
+ target_model_id = target
+ hops = _legacy_route_hops(
+ sources_by_id,
+ source_order,
+ backend,
+ target_model_id,
+ )
+ if isinstance(mapping, dict) and mapping.get("enabled") is True and not hops:
+ warnings.append(
+ f"Model Hub route {backend}/{model_id} could not be mapped to a persisted source model"
+ )
+ routes[model_id] = {"hops": hops}
+
+ allowed_agent = {
+ key: value
+ for key, value in agent.items()
+ if key in {"backend", "mode", "menu_kind", "menu"}
+ }
+ allowed_agent["backend"] = backend
+ agent_mode = agent.get("mode")
+ allowed_agent["mode"] = agent_mode if isinstance(agent_mode, str) and agent_mode in {"hub", "direct"} else "direct"
+ allowed_agent["menu_kind"] = "open" if backend == "opencode" else "fixed"
+ allowed_agent["sources"] = source_settings
+ allowed_agent["routes"] = routes
+ migrated_agents[backend] = allowed_agent
+
+ migrated_model_hub["agents"] = migrated_agents
+ migrated_payload["model_hub"] = migrated_model_hub
+ return migrated_payload, True, tuple(warnings)
+
+
+def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
+ migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)
+ migrated = _migrate_fixed_menu_routes_on_load(migrated)
+ return migrated, changed, warnings
+
+
+def _recovery_section_for_error(error: BaseException) -> Optional[str]:
+ message = str(error)
+ match = re.search(r"Config '([^']+)'", message)
+ if match:
+ path = match.group(1)
+ if path == "platform":
+ return "platforms"
+ if path.startswith("agents."):
+ backend = path.split(".", 2)[1]
+ if backend in MODEL_HUB_BACKENDS or backend == "avault":
+ return f"agents.{backend}"
+ return path.split(".", 1)[0]
+
+ lowered = message.lower()
+ if "unsupported enabled platform" in lowered:
+ return "platforms"
+ for platform_id in supported_platform_ids():
+ if f"invalid {platform_id.lower()}" in lowered:
+ return platform_id
+ if any(
+ marker in lowered
+ for marker in (
+ "source state",
+ "hub sources",
+ "engine credential ref",
+ "native source",
+ "api-key source",
+ "manual model",
+ "subscription source",
+ "opencode model identifier",
+ )
+ ):
+ return "model_hub"
+ for section in (
+ "model_hub",
+ "memory",
+ "remote_access",
+ "audio_asr",
+ "runtime",
+ "agents",
+ "platforms",
+ "update",
+ "ui",
+ ):
+ if section in lowered:
+ return section
+ return None
+
+
+def _reset_recoverable_config_section(payload: dict, section: str) -> bool:
+ """Replace one independently recoverable section with its safe default.
+
+ This is deliberately outside ``V2Config.from_payload``. Direct callers and
+ API writes still get strict validation; only disk loading may enter this
+ loss-avoiding recovery path, and the original file is backed up first.
+ """
+
+ if section == "runtime":
+ # Keep this in sync with ``V2Config.default``. RuntimeConfig has a
+ # required cwd, so an empty object would make the recovery loop fail a
+ # second time and discard otherwise valid settings.
+ payload[section] = {"default_cwd": str(Path.home() / "work")}
+ return True
+ if section in {
+ "model_hub",
+ "memory",
+ "ui",
+ "remote_access",
+ "audio_asr",
+ "update",
+ }:
+ payload[section] = {}
+ return True
+ if section == "agents":
+ defaults = V2Config.default().agents
+ payload[section] = {
+ "opencode": dict(defaults.opencode.__dict__),
+ "claude": dict(defaults.claude.__dict__),
+ "codex": dict(defaults.codex.__dict__),
+ "avault": dict(defaults.avault.__dict__),
+ }
+ return True
+ if section == "gateway":
+ payload[section] = None
+ return True
+ if section == "mode":
+ payload[section] = "self_host"
+ return True
+ if section == "platforms":
+ payload["platforms"] = {"enabled": [], "primary": WORKBENCH_PLATFORM_ID}
+ payload["platform"] = WORKBENCH_PLATFORM_ID
+ return True
+ if section in {"ack_mode", "language", "agent_progress_style"}:
+ payload[section] = {
+ "ack_mode": "typing",
+ "language": "en",
+ "agent_progress_style": DEFAULT_AGENT_PROGRESS_STYLE,
+ }[section]
+ return True
+ if section in {
+ "show_duration",
+ "include_time_info",
+ "include_user_info",
+ "reply_enhancements",
+ "show_pages_prompt",
+ "setup_completed",
+ }:
+ payload[section] = {
+ "show_duration": False,
+ "include_time_info": True,
+ "include_user_info": True,
+ "reply_enhancements": True,
+ "show_pages_prompt": True,
+ "setup_completed": False,
+ }[section]
+ return True
+ if section in {"agent_status_heartbeat_ms", "agent_status_no_output_ms"}:
+ payload.pop(section, None)
+ return True
+ if section.startswith("agents."):
+ agent_name = section.split(".", 1)[1]
+ agents_payload = payload.get("agents")
+ if not isinstance(agents_payload, dict):
+ return False
+ if agent_name == "codex":
+ # Codex is opt-in in the canonical first-run/recovery config.
+ agents_payload[agent_name] = dict(V2Config.default().agents.codex.__dict__)
+ else:
+ agents_payload[agent_name] = {}
+ return True
+ if section in set(supported_platform_ids()) | {WORKBENCH_PLATFORM_ID}:
+ payload[section] = {}
+ platforms_payload = payload.get("platforms")
+ if not isinstance(platforms_payload, dict):
+ platforms_payload = {"enabled": [], "primary": WORKBENCH_PLATFORM_ID}
+ enabled = platforms_payload.get("enabled")
+ if not isinstance(enabled, list):
+ enabled = []
+ enabled = [item for item in enabled if item != section]
+ primary = platforms_payload.get("primary")
+ if primary == section or primary not in enabled:
+ primary = enabled[0] if enabled else WORKBENCH_PLATFORM_ID
+ payload["platforms"] = {"enabled": enabled, "primary": primary}
+ if payload.get("platform") == section:
+ payload["platform"] = primary
+ return True
+ return False
+
+
+def _backup_config_file(
+ path: Path,
+ label: str,
+ *,
+ content: bytes | None = None,
+) -> Optional[Path]:
+ if content is None and not path.exists():
+ return None
+ try:
+ if content is None:
+ content = path.read_bytes()
+ existing = sorted(
+ path.parent.glob(f"{path.name}.bak-{label}-*"),
+ key=lambda candidate: candidate.stat().st_mtime,
+ reverse=True,
+ )
+ for candidate in existing:
+ try:
+ if candidate.read_bytes() == content:
+ candidate.chmod(0o600)
+ return candidate
+ except OSError:
+ continue
+ except OSError:
+ pass
+
+ stamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
+ backup = path.with_name(f"{path.name}.bak-{label}-{stamp}")
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ try:
+ file_descriptor = os.open(backup, flags, 0o600)
+ with os.fdopen(file_descriptor, "wb") as destination:
+ if content is None:
+ with path.open("rb") as source:
+ shutil.copyfileobj(source, destination)
+ else:
+ destination.write(content)
+ destination.flush()
+ os.fsync(destination.fileno())
+ except OSError as exc:
+ logger.warning("Could not back up config before recovery (%s): %s", path, exc)
+ try:
+ backup.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return None
+ return backup
+
+
+def _config_file_lock(path: Path):
+ """Return the shared cross-process lock for one config path."""
+
+ # Import lazily because storage's package initializer imports V2Config.
+ from storage.lock import MigrationFileLock
+
+ return MigrationFileLock(path.with_name(f".{path.name}.lock"))
+
+
+def _write_config_payload(path: Path, payload: dict) -> None:
+ content = json.dumps(payload, indent=2)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with CONFIG_LOCK:
+ with _config_file_lock(path):
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ os.replace(temp_name, path)
+
+
+def _write_config_payload_if_unchanged(
+ path: Path,
+ payload: dict,
+ expected_raw: str,
+) -> bool:
+ """Replace a config only if the final pre-replace snapshot still matches."""
+
+ content = json.dumps(payload, indent=2)
+ temp_name: str | None = None
+ with CONFIG_LOCK:
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=path.parent,
+ delete=False,
+ ) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ current_raw = path.read_text(encoding="utf-8")
+ if current_raw != expected_raw:
+ return False
+ os.replace(temp_name, path)
+ temp_name = None
+ return True
+ except (OSError, UnicodeDecodeError):
+ return False
+ finally:
+ if temp_name is not None:
+ try:
+ Path(temp_name).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def _persist_migrated_config_payload(
+ path: Path,
+ expected_raw: str,
+ payload: dict,
+) -> tuple[Optional[Path], Optional[str]]:
+ """Persist a migration only when the snapshot read at load is unchanged."""
+
+ try:
+ with CONFIG_LOCK:
+ with _config_file_lock(path):
+ try:
+ current_raw = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ return None, f"Could not verify config before migration persistence: {exc}"
+ if current_raw != expected_raw:
+ return None, "Skipped config migration because the file changed during load"
+ backup = _backup_config_file(
+ path,
+ "model-hub-migration",
+ content=expected_raw.encode("utf-8"),
+ )
+ if backup is None:
+ return None, "Skipped config migration because the original file could not be backed up"
+ if not _write_config_payload_if_unchanged(path, payload, expected_raw):
+ return backup, "Skipped config migration because the file changed before replacement"
+ return backup, None
+ except TimeoutError as exc:
+ return None, f"Could not acquire config migration lock: {exc}"
+
+
_MODEL_HUB_CREDENTIAL_QUERY_KEYS = {
"access_token",
"api_key",
@@ -757,7 +1549,7 @@ class ModelHubModelConfig:
discovered_at = payload.get("discovered_at")
if not isinstance(model_id, str) or not model_id or _contains_model_hub_credential_material(model_id):
raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")
- if origin not in {"discovered", "manual"}:
+ if not isinstance(origin, str) or origin not in {"discovered", "manual"}:
raise ValueError("Config 'model_hub.sources.models.origin' is invalid")
if (
not isinstance(reasoning_efforts, list)
@@ -811,7 +1603,13 @@ class ModelHubSourceStateConfig:
status = payload.get("status")
retry_at = payload.get("retry_at")
detail_key = payload.get("detail_key")
- if status not in {"active", "standby", "cooldown", "needs_action", "error"}:
+ if not isinstance(status, str) or status not in {
+ "active",
+ "standby",
+ "cooldown",
+ "needs_action",
+ "error",
+ }:
raise ValueError("Config 'model_hub.sources.state.status' is invalid")
if detail_key is not None and not isinstance(detail_key, str):
raise ValueError("Config 'model_hub.sources.state.detail_key' must be a string or null")
@@ -952,16 +1750,20 @@ class ModelHubSourceConfig:
billing = payload.get("billing")
if not isinstance(source_id, str) or re.fullmatch(r"src_[a-z0-9]{8,}", source_id) is None:
raise ValueError("Config 'model_hub.sources.id' is invalid")
- if kind not in {"subscription", "api_key"}:
+ if not isinstance(kind, str) or kind not in {"subscription", "api_key"}:
raise ValueError("Config 'model_hub.sources.kind' is invalid")
vendor = normalize_model_hub_vendor_id(vendor)
if not isinstance(display_name, str) or not display_name or len(display_name) > 64:
raise ValueError("Config 'model_hub.sources.display_name' is invalid")
- if protocol not in {"anthropic", "openai_responses", "openai_chat"}:
+ if not isinstance(protocol, str) or protocol not in {
+ "anthropic",
+ "openai_responses",
+ "openai_chat",
+ }:
raise ValueError("Config 'model_hub.sources.protocol' is invalid")
- if supply_channel not in {"native_cli", "hub"}:
+ if not isinstance(supply_channel, str) or supply_channel not in {"native_cli", "hub"}:
raise ValueError("Config 'model_hub.sources.supply_channel' is invalid")
- if billing not in {"monthly", "metered"}:
+ if not isinstance(billing, str) or billing not in {"monthly", "metered"}:
raise ValueError("Config 'model_hub.sources.billing' is invalid")
models_payload = payload.get("models")
if not isinstance(models_payload, list):
@@ -1109,7 +1911,7 @@ class ModelHubMenuConfig:
raise ValueError("Config 'model_hub.agents.menu' contains unknown fields")
view = payload.get("view")
checked = payload.get("checked")
- if view not in {"featured", "full"}:
+ if not isinstance(view, str) or view not in {"featured", "full"}:
raise ValueError("Config 'model_hub.agents.menu.view' is invalid")
if not isinstance(checked, list) or not all(isinstance(item, str) for item in checked):
raise ValueError("Config 'model_hub.agents.menu.checked' must be an array of strings")
@@ -1172,17 +1974,18 @@ class ModelHubAgentSupplyConfig:
raise ValueError("Config 'model_hub.agents' entries must be objects")
if set(payload) - {"backend", "mode", "menu_kind", "sources", "routes", "menu"}:
raise ValueError("Config 'model_hub.agents' contains unknown fields")
- backend = payload.get("backend") or expected_backend
+ raw_backend = payload.get("backend")
+ backend = expected_backend if raw_backend is None else raw_backend
mode = payload.get("mode")
menu_kind = payload.get("menu_kind")
- if backend not in {"claude", "codex", "opencode"} or (
+ if not isinstance(backend, str) or backend not in {"claude", "codex", "opencode"} or (
expected_backend is not None and backend != expected_backend
):
raise ValueError("Config 'model_hub.agents.backend' is invalid")
- if mode not in {"hub", "direct"}:
+ if not isinstance(mode, str) or mode not in {"hub", "direct"}:
raise ValueError("Config 'model_hub.agents.mode' is invalid")
expected_menu_kind = "open" if backend == "opencode" else "fixed"
- if menu_kind != expected_menu_kind:
+ if not isinstance(menu_kind, str) or menu_kind != expected_menu_kind:
raise ValueError("Config 'model_hub.agents.menu_kind' is invalid for backend")
routes_payload = payload.get("routes", {})
if not isinstance(routes_payload, dict):
@@ -1548,16 +2351,131 @@ class V2Config:
# into the wizard). Legacy configs that predate the flag have it derived in
# ``from_payload`` from the old condition.
setup_completed: bool = False
+ # Non-persisted diagnostics from disk migration/recovery. They let callers
+ # surface a repair notice without weakening the strict write validator.
+ load_warnings: ClassVar[tuple[str, ...]] = ()
+
+ @classmethod
+ def default(cls) -> "V2Config":
+ """Return the minimal safe config used for first-run and recovery."""
+
+ return cls(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token="", app_token=""),
+ platforms=PlatformsConfig(enabled=[], primary=WORKBENCH_PLATFORM_ID),
+ runtime=RuntimeConfig(default_cwd=str(Path.home() / "work")),
+ agents=AgentsConfig(
+ opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),
+ claude=ClaudeConfig(enabled=True, cli_path="claude"),
+ codex=CodexConfig(enabled=False, cli_path="codex"),
+ ),
+ model_hub=ModelHubConfig(),
+ platform=WORKBENCH_PLATFORM_ID,
+ )
@classmethod
- def load(cls, config_path: Optional[Path] = None) -> "V2Config":
+ def load(
+ cls,
+ config_path: Optional[Path] = None,
+ *,
+ _migration_reload_depth: int = 0,
+ ) -> "V2Config":
paths.ensure_data_dirs()
path = config_path or paths.get_config_path()
with CONFIG_LOCK:
if not path.exists():
raise FileNotFoundError(f"Config not found: {path}")
- payload = json.loads(path.read_text(encoding="utf-8"))
- return cls.from_payload(_migrate_fixed_menu_routes_on_load(payload))
+ raw_bytes = b""
+ try:
+ raw_bytes = path.read_bytes()
+ raw = raw_bytes.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ backup = _backup_config_file(path, "invalid-encoding", content=raw_bytes)
+ warning = f"Config is not valid UTF-8; using recovery defaults: {exc.reason}"
+ logger.error("%s (backup=%s)", warning, backup)
+ config = cls.default()
+ config.load_warnings = (warning,)
+ return config
+
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ backup = _backup_config_file(path, "invalid-json", content=raw_bytes)
+ warning = f"Config JSON could not be parsed; using recovery defaults: {exc.msg}"
+ logger.error("%s (backup=%s)", warning, backup)
+ config = cls.default()
+ config.load_warnings = (warning,)
+ return config
+
+ if not isinstance(payload, dict):
+ backup = _backup_config_file(path, "invalid-root", content=raw_bytes)
+ warning = "Config root is not an object; using recovery defaults"
+ logger.error("%s (backup=%s)", warning, backup)
+ config = cls.default()
+ config.load_warnings = (warning,)
+ return config
+
+ migrated_payload, migrated, migration_warnings = _migrate_config_payload_on_load(payload)
+ candidate = migrated_payload
+ recovery_warnings: list[str] = []
+ recovered_sections: set[str] = set()
+ while True:
+ try:
+ config = cls.from_payload(candidate)
+ break
+ except (TypeError, ValueError) as exc:
+ section = _recovery_section_for_error(exc)
+ if section is None or section in recovered_sections:
+ warning = f"Config could not be loaded; using recovery defaults: {exc}"
+ logger.error("%s", warning)
+ config = cls.default()
+ recovery_warnings.append(warning)
+ break
+ if not _reset_recoverable_config_section(candidate, section):
+ warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
+ logger.error("%s", warning)
+ config = cls.default()
+ recovery_warnings.append(warning)
+ break
+ recovered_sections.add(section)
+ recovery_warnings.append(f"Recovered invalid config section '{section}': {exc}")
+
+ all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
+ if migrated and not migration_warnings and not recovery_warnings:
+ persisted_payload = copy.deepcopy(payload)
+ persisted_payload["model_hub"] = config.model_hub.to_payload()
+ try:
+ backup, persistence_warning = _persist_migrated_config_payload(
+ path,
+ raw,
+ persisted_payload,
+ )
+ except OSError as exc:
+ persistence_warning = f"Model Hub config migration could not be persisted: {exc}"
+ if persistence_warning:
+ all_warnings = tuple(dict.fromkeys((*all_warnings, persistence_warning)))
+ logger.warning("%s (%s)", persistence_warning, path)
+ if "file changed" in persistence_warning and _migration_reload_depth == 0:
+ winning_config = cls.load(
+ config_path=path,
+ _migration_reload_depth=1,
+ )
+ winning_config.load_warnings = tuple(
+ dict.fromkeys((*winning_config.load_warnings, persistence_warning))
+ )
+ return winning_config
+ else:
+ logger.info("Migrated Model Hub config in place (backup=%s)", backup)
+ elif migration_warnings or recovery_warnings:
+ label = "model-hub-migration" if migration_warnings and not recovery_warnings else "recovery"
+ backup = _backup_config_file(path, label, content=raw_bytes)
+ logger.warning(
+ "Started with a recovered config; original file preserved at %s",
+ backup,
+ )
+ config.load_warnings = all_warnings
+ return config
@classmethod
def from_payload(cls, payload: dict) -> "V2Config":
@@ -1565,23 +2483,40 @@ class V2Config:
raise ValueError("Config payload must be an object")
mode = payload.get("mode")
- if mode not in {"self_host", "saas"}:
+ if not isinstance(mode, str) or mode not in {"self_host", "saas"}:
raise ValueError("Config 'mode' must be 'self_host' or 'saas'")
- platform = payload.get("platform") or "slack"
- try:
- get_platform_descriptor(platform)
- except ValueError as err:
- supported_text = "', '".join(supported_platform_ids())
- raise ValueError(f"Config 'platform' must be one of: '{supported_text}'") from err
-
+ raw_platform = payload.get("platform")
platforms_payload = payload.get("platforms")
if platforms_payload is not None and not isinstance(platforms_payload, dict):
raise ValueError("Config 'platforms' must be an object")
+ if platforms_payload is None:
+ if raw_platform is not None and not isinstance(raw_platform, str):
+ raise ValueError("Config 'platform' must be a string")
+ platform = raw_platform or "slack"
+ try:
+ get_platform_descriptor(platform)
+ except ValueError as err:
+ supported_text = "', '".join(supported_platform_ids())
+ raise ValueError(f"Config 'platform' must be one of: '{supported_text}'") from err
+ else:
+ # ``platforms`` is the current source of truth. A stale legacy
+ # compatibility field must not disable otherwise valid transports.
+ platform = platforms_payload.get("primary") or "slack"
if platforms_payload:
+ enabled_payload = platforms_payload.get("enabled")
+ if enabled_payload is not None and not isinstance(enabled_payload, list):
+ raise ValueError("Config 'platforms.enabled' must be an array")
+ if isinstance(enabled_payload, list) and any(
+ not isinstance(item, str) for item in enabled_payload
+ ):
+ raise ValueError("Config 'platforms.enabled' entries must be strings")
+ primary_payload = platforms_payload.get("primary")
+ if primary_payload is not None and not isinstance(primary_payload, str):
+ raise ValueError("Config 'platforms.primary' must be a string")
platforms = PlatformsConfig(
- enabled=list(platforms_payload.get("enabled") or []),
- primary=platforms_payload.get("primary") or platform,
+ enabled=list(enabled_payload or []),
+ primary=primary_payload or platform,
)
else:
platforms = PlatformsConfig(enabled=[platform], primary=platform)
@@ -1608,7 +2543,23 @@ class V2Config:
platform_configs[descriptor.id] = None
continue
- platform_configs[descriptor.id] = descriptor.create_config(platform_payload)
+ for credential_field in descriptor.credential_fields:
+ credential_value = platform_payload.get(credential_field)
+ if credential_value is not None and not isinstance(credential_value, str):
+ raise ValueError(
+ f"Config '{descriptor.config_key}.{credential_field}' must be a string"
+ )
+
+ try:
+ platform_configs[descriptor.id] = descriptor.create_config(platform_payload)
+ except (AttributeError, TypeError) as exc:
+ # Platform validators may call string methods or compare enum
+ # values before the dataclass layer can validate their types.
+ # Convert those payload errors into a qualified config error so
+ # disk loading can recover only the affected platform section.
+ raise ValueError(
+ f"Config '{descriptor.config_key}' contains invalid field types"
+ ) from exc
# Avibe runs in-process with no credentials — auto-populate its
# config when missing so legacy ``platforms.enabled`` lists that
@@ -1828,7 +2779,7 @@ class V2Config:
update = UpdateConfig(**_filter_dataclass_fields(UpdateConfig, update_payload))
ack_mode = payload.get("ack_mode", "typing")
- if ack_mode not in {"reaction", "message", "typing"}:
+ if not isinstance(ack_mode, str) or ack_mode not in {"reaction", "message", "typing"}:
raise ValueError("Config 'ack_mode' must be 'reaction', 'message', or 'typing'")
show_duration = payload.get("show_duration", False)
@@ -1920,6 +2871,11 @@ class V2Config:
return config
def save(self, config_path: Optional[Path] = None) -> None:
+ if self.load_warnings:
+ raise ValueError(
+ "Config was loaded with recovery warnings; repair the backed-up "
+ "config before saving changes"
+ )
paths.ensure_data_dirs()
path = config_path or paths.get_config_path()
self.platforms.validate()
@@ -1985,15 +2941,7 @@ class V2Config:
"agent_status_no_output_ms": self.agent_status_no_output_ms,
"setup_completed": self.setup_completed,
}
- content = json.dumps(payload, indent=2)
- path.parent.mkdir(parents=True, exist_ok=True)
- with CONFIG_LOCK:
- with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as tmp:
- tmp.write(content)
- tmp.flush()
- os.fsync(tmp.fileno())
- temp_name = tmp.name
- os.replace(temp_name, path)
+ _write_config_payload(path, payload)
def enabled_platforms(self) -> list[str]:
return list(self.platforms.enabled)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 888bf7317..5f3b72a6a 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -143,6 +143,14 @@ class V2ModelHubConfigStore:
except FileNotFoundError:
return default_config().model_hub
+ def ensure_writable(self) -> None:
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ return
+ if config.load_warnings:
+ raise ModelHubError("config_recovery", status=409)
+
def save(self, model_hub: ModelHubConfig) -> None:
model_hub = ModelHubConfig.from_payload(model_hub.to_payload())
with CONFIG_LOCK:
@@ -616,6 +624,23 @@ class ModelHubService:
self.store.save(canonical)
return canonical
+ def _save_runtime_config(self, config: ModelHubConfig) -> bool:
+ """Best-effort persistence for runtime state during config recovery."""
+
+ try:
+ self._save_config(config)
+ except ValueError as exc:
+ if "recovery warnings" not in str(exc):
+ raise
+ logger.warning("Skipped Model Hub runtime-state persistence during config recovery")
+ return False
+ return True
+
+ def _ensure_config_writable(self) -> None:
+ ensure_writable = getattr(self.store, "ensure_writable", None)
+ if callable(ensure_writable):
+ ensure_writable()
+
async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:
bindings = self._bindings(config)
has_hub_sources = any(
@@ -1234,6 +1259,7 @@ class ModelHubService:
# Claim and consume a completed flow under the aggregate lock. This
# prevents a duplicate browser retry from revoking the winning source's
# credential while still retaining rollback ownership before discovery.
+ self._ensure_config_writable()
async with self._mutation_lock:
rollback_credential_ref: Optional[str] = None
source_id = ""
@@ -1520,6 +1546,7 @@ class ModelHubService:
binding: OAuthFlowBinding,
flow: OAuthFlowState,
) -> dict:
+ self._ensure_config_writable()
if binding.source_id is None or binding.vendor is None:
raise ModelHubError("flow_not_found", status=404)
@@ -3194,8 +3221,8 @@ class ModelHubService:
status=status,
detail_key=detail_key,
)
- self._save_config(config)
- if not unchanged:
+ persisted = self._save_runtime_config(config)
+ if persisted and not unchanged:
self._record_event(
agent=cast(EventAgent, backend),
kind="needs_action",
@@ -3582,6 +3609,7 @@ class ModelHubService:
except ValueError:
raise ModelHubError("flow_not_found", status=400) from None
oauth_channel = cast(OAuthChannel, channel)
+ self._ensure_config_writable()
if oauth_channel == "native_cli":
backend = _NATIVE_VENDOR_BACKENDS.get(vendor)
if backend is not None:
@@ -3679,6 +3707,7 @@ class ModelHubService:
value = payload.get("value") if isinstance(payload, dict) else None
if not isinstance(flow_id, str) or not isinstance(value, str):
raise ModelHubError("flow_not_found", status=404)
+ self._ensure_config_writable()
binding = self._oauth_binding(flow_id)
completed = self._completed_oauth_flow(flow_id, binding)
if completed is not None:
@@ -3813,6 +3842,7 @@ class ModelHubService:
async with self._mutation_lock:
config = self.store.load()
config_changed = False
+ recovered_sources: list[ModelHubSourceConfig] = []
for source_id in resolution.recoverable_source_ids:
source = next(
(item for item in config.sources if item.id == source_id),
@@ -3825,17 +3855,19 @@ class ModelHubService:
continue
source.state = recovered_source.state
config_changed = True
- self._record_event(
- agent=cast(EventAgent, resolution.backend),
- kind="recover",
- model_id=resolution.requested_model,
- reason="recovery",
- to_source=source.id,
- to_label=source.display_name,
- now=self.now(),
- )
+ recovered_sources.append(source)
if config_changed:
- self._save_config(config)
+ if self._save_runtime_config(config):
+ for source in recovered_sources:
+ self._record_event(
+ agent=cast(EventAgent, resolution.backend),
+ kind="recover",
+ model_id=resolution.requested_model,
+ reason="recovery",
+ to_source=source.id,
+ to_label=source.display_name,
+ now=self.now(),
+ )
async def _cooldown(
self,
@@ -3858,8 +3890,8 @@ class ModelHubService:
retry_at=(self.now() + timedelta(seconds=decision.cooldown_seconds)).isoformat(),
detail_key=detail_key or f"models.source.cooldown.{decision.reason}",
)
- self._save_config(config)
- if not already_cooling:
+ persisted = self._save_runtime_config(config)
+ if persisted and not already_cooling:
self._record_event(
agent=agent,
kind="cooldown",
diff --git a/core/services/settings.py b/core/services/settings.py
index 68d76c3ad..9538deffe 100644
--- a/core/services/settings.py
+++ b/core/services/settings.py
@@ -26,16 +26,7 @@ from pathlib import Path
from typing import Callable, Optional
from config import SettingsStore, paths
-from config.platform_registry import WORKBENCH_PLATFORM_ID
from config.v2_config import (
- AgentsConfig,
- ClaudeConfig,
- CodexConfig,
- ModelHubConfig,
- OpenCodeConfig,
- PlatformsConfig,
- RuntimeConfig,
- SlackConfig,
V2Config,
)
@@ -61,26 +52,7 @@ def default_config() -> V2Config:
starts workbench-only (no external IM enabled) — see below.
"""
- return V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(bot_token="", app_token=""),
- # Workbench-only first-run state. The always-on Avibe Workbench is the
- # sole inbound surface and no external IM is enabled yet, so ``enabled``
- # MUST start empty — overriding the PlatformsConfig ``["slack"]``
- # dataclass default. Otherwise a fresh install (or the wizard's "skip
- # chat platforms" path) would persist a setup-completed config with
- # Slack enabled and empty credentials — a phantom transport. ``primary``
- # anchors to the workbench; the user adds real IMs explicitly later.
- platforms=PlatformsConfig(enabled=[], primary=WORKBENCH_PLATFORM_ID),
- runtime=RuntimeConfig(default_cwd=str(Path.home() / "work")),
- agents=AgentsConfig(
- opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),
- claude=ClaudeConfig(enabled=True, cli_path="claude"),
- codex=CodexConfig(enabled=False, cli_path="codex"),
- ),
- model_hub=ModelHubConfig(),
- )
+ return V2Config.default()
def load_config(
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index 060150bf8..29326362d 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -924,7 +924,7 @@ the implementing lane receives the evidence rather than a paraphrase.
| Review thread | AC / disposition | Landing point | Responsible lane |
| --- | --- | --- | --- |
-| `3742846987` | Owner ruling 2026-08-09: no internal v4-to-v5 data migration; the finding's upgraded-install premise is superseded and no compatibility loader is permitted | Final-contract handoff and `config/v2_config.py` absence proof | K1 ruling only; no implementation lane |
+| `3742846987` | Historical owner ruling 2026-08-09: no internal v4-to-v5 data migration. Superseded by the 3.0.10 upgraded-install incident: `V2Config.load` now performs a disk-boundary migration and preserves strict `from_payload` validation; unrecoverable sections start with safe defaults while the original file is backed up. | Final-contract handoff and `config/v2_config.py` load boundary | K1 ruling superseded; migration/recovery is owned by `config/v2_config.py` |
| `3742846989` | AC-22; valid prelaunch consumer gap | Agent projection/write flow in `service.py` and Models route editor | I1 + I4 |
| `3742846991` | AC-26; valid prelaunch consumer gap | Source serializer plus all Models `SuppliedModel` consumers and mocks | I1 + I4 |
| `3742846992` | AC-30; valid prelaunch consumer gap | No-candidate provenance producer, runtime blocker propagation, and pull-surface rendering | I1 + I2 + I4 |
diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.py
index 9352a688d..fad89e1fe 100644
--- a/tests/test_codex_api_auth.py
+++ b/tests/test_codex_api_auth.py
@@ -113,3 +113,41 @@ def test_save_codex_auth_falls_back_to_v2config_when_disk_empty(
auth = json.loads((tmp_path / ".codex" / "auth.json").read_text(encoding="utf-8"))
assert auth["OPENAI_API_KEY"] == "sk-from-cache"
+
+
+def test_save_codex_auth_blocks_recovery_before_external_mutation(monkeypatch) -> None:
+ fake_config = types.SimpleNamespace(load_warnings=("recovery required",), language="zh")
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ applied: list[dict] = []
+ monkeypatch.setattr(
+ "vibe.codex_config.apply_codex_auth",
+ lambda **kwargs: applied.append(kwargs),
+ )
+
+ result = api.save_codex_auth(
+ {"auth_mode": "api_key", "api_key": "sk-new", "base_url": "https://example.invalid"}
+ )
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert applied == []
+
+
+def test_remove_codex_api_key_blocks_recovery_before_external_mutation(monkeypatch) -> None:
+ fake_config = types.SimpleNamespace(load_warnings=("recovery required",))
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ applied: list[dict] = []
+ monkeypatch.setattr(
+ "vibe.codex_config.apply_codex_auth",
+ lambda **kwargs: applied.append(kwargs),
+ )
+
+ result = api.remove_backend_api_key("codex")
+
+ assert result == {
+ "ok": False,
+ "error": "config_recovery",
+ "message": "Config was loaded with recovery warnings; repair the backed-up config before changing backend credentials",
+ }
+ assert applied == []
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 4d45fa05c..269d38a5b 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -74,6 +74,7 @@ class MemoryStore:
}
)
self.requested_models = {}
+ self.recovery = False
def load(self):
return self.config
@@ -81,6 +82,10 @@ class MemoryStore:
def save(self, config):
self.config = config
+ def ensure_writable(self):
+ if self.recovery:
+ raise ModelHubError("config_recovery", status=409)
+
def requested_model(self, backend):
return self.requested_models.get(backend, "")
@@ -986,6 +991,26 @@ def test_oauth_start_normalizes_vendor_before_singleton_and_adapter(tmp_path):
assert adapter.oauth_start_calls == [(flow["source_id"], "anthropic")]
+def test_model_hub_oauth_blocks_recovery_before_external_auth(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ flow = asyncio.run(
+ service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
+ )["flow"]
+ store.recovery = True
+
+ with pytest.raises(ModelHubError) as start_error:
+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
+ assert start_error.value.code == "config_recovery"
+ assert len(adapter.oauth_start_calls) == 1
+
+ with pytest.raises(ModelHubError) as submit_error:
+ asyncio.run(
+ service.oauth_submit({"flow_id": flow["flow_id"], "value": "auth-code"})
+ )
+ assert submit_error.value.code == "config_recovery"
+ assert adapter.secret_lengths == []
+
+
def test_chain_route_reorders_exact_persisted_hops(monkeypatch, tmp_path):
service, _, _ = _service(tmp_path)
first = asyncio.run(
@@ -1697,6 +1722,43 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(
assert service.revocations.list() == []
+def test_completed_hub_reauth_blocks_recovery_before_discovery(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_huboauth01",
+ kind="subscription",
+ vendor="anthropic",
+ display_name="Hub subscription",
+ protocol="anthropic",
+ supply_channel="hub",
+ billing="monthly",
+ state=ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
+ ),
+ models=[ModelHubModelConfig(id="stale-entitlement", provenance="discovered")],
+ credential_ref="cred_hub_reused",
+ )
+ store.config.sources.append(source)
+ _refresh_fixture_routes(store.config)
+ flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "success",
+ "credential_ref": "cred_hub_reused",
+ }
+ )
+ store.recovery = True
+
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.oauth_status(flow["flow_id"]))
+
+ assert error.value.code == "config_recovery"
+ assert adapter.secret_lengths == []
+ assert store.config.sources[0].models[0].id == "stale-entitlement"
+
+
def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):
async def run_race():
class BlockingDiscoveryAdapter(FakeAdapter):
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 647662c1a..faa68d0c1 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import copy
import json
import re
+import stat
from dataclasses import fields
from itertools import product
from pathlib import Path
@@ -10,6 +11,7 @@ from pathlib import Path
import pytest
from jsonschema import Draft7Validator, FormatChecker, ValidationError
+import config.v2_config as v2_config
from config.v2_config import (
MODEL_HUB_ENABLED_ENV,
MODEL_HUB_LEGACY_CREATED_AT,
@@ -1269,6 +1271,941 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
assert api.config_to_payload(updated)["model_hub"] == api_payload["model_hub"]
+def _legacy_model_hub_payload(current: dict) -> dict:
+ """Build the persisted v3.0.9 Model Hub shape from a current fixture."""
+
+ agents = {}
+ for backend, agent in current["agents"].items():
+ agents[backend] = {
+ "backend": agent["backend"],
+ "mode": agent["mode"],
+ "menu_kind": agent["menu_kind"],
+ "sources": {"policy": "follow", "order": []},
+ "mappings": [],
+ "menu": agent.get("menu"),
+ }
+ return {
+ "sources": [],
+ "priority_order": [],
+ "agents": agents,
+ "subscription_hub_experimental": False,
+ }
+
+
+def test_config_reload_migrates_v3_model_hub_shape_and_persists_backup(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = _legacy_model_hub_payload(payload["model_hub"])
+ payload["migration_sentinel"] = {"keep": True}
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.load_warnings == ()
+ assert set(loaded.model_hub.agents["claude"].routes) == set(
+ ModelHubConfig().agents["claude"].routes
+ )
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert persisted["migration_sentinel"] == {"keep": True}
+ backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))
+ assert backups
+ assert stat.S_IMODE(backups[0].stat().st_mode) == 0o600
+
+
+def test_config_reload_recovers_malformed_legacy_collections(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ malformed_values = [
+ 42,
+ [dict(source, models=42)],
+ ]
+
+ for index, malformed_sources in enumerate(malformed_values):
+ payload = copy.deepcopy(current)
+ payload["show_duration"] = True
+ malformed = copy.deepcopy(legacy)
+ malformed["sources"] = malformed_sources
+ payload["model_hub"] = malformed
+ config_path = tmp_path / f"config-{index}.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+ "invalid_platform",
+ [
+ "enabled",
+ "enabled-type",
+ "enabled-entry-type",
+ "primary-type",
+ "legacy",
+ "legacy-type",
+ ],
+)
+def test_config_reload_recovers_invalid_platform_metadata_only(monkeypatch, tmp_path, invalid_platform):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ if invalid_platform == "enabled":
+ payload["platforms"]["enabled"] = ["not-a-platform"]
+ payload["platforms"]["primary"] = "not-a-platform"
+ elif invalid_platform == "enabled-type":
+ payload["platforms"]["enabled"] = {"slack": True}
+ elif invalid_platform == "enabled-entry-type":
+ payload["platforms"]["enabled"] = [{}]
+ elif invalid_platform == "primary-type":
+ payload["platforms"]["primary"] = {}
+ elif invalid_platform == "legacy":
+ payload.pop("platforms", None)
+ payload["platform"] = "not-a-platform"
+ else:
+ payload.pop("platforms", None)
+ payload["platform"] = {}
+ config_path = tmp_path / f"{invalid_platform}-platform.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.platforms.enabled == []
+ assert loaded.platform == "avibe"
+ assert loaded.load_warnings and "platforms" in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+ ("platform", "invalid_fields"),
+ [
+ ("slack", {"bot_token": "invalid"}),
+ ("slack", {"bot_token": 123}),
+ ("slack", {"app_token": 123}),
+ ("discord", {"thread_auto_archive_minutes": 1}),
+ ("discord", {"bot_token": {}}),
+ ("telegram", {"bot_token": "invalid"}),
+ ("lark", {"domain": "invalid"}),
+ ("lark", {"app_id": 123}),
+ ],
+)
+def test_config_reload_recovers_invalid_platform_adapter_only(
+ monkeypatch,
+ tmp_path,
+ platform,
+ invalid_fields,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ payload["platform"] = platform
+ payload["platforms"] = {"enabled": [platform], "primary": platform}
+ platform_payload = dict(payload.get(platform) or {})
+ platform_payload.update(invalid_fields)
+ payload[platform] = platform_payload
+ config_path = tmp_path / f"{platform}-adapter.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.platforms.enabled == []
+ assert loaded.platform == "avibe"
+ assert loaded.load_warnings and platform in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_config_reload_ignores_stale_legacy_platform_when_platforms_are_valid(monkeypatch):
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["platform"] = "removed-platform"
+ payload["platforms"] = {"enabled": ["slack"], "primary": "slack"}
+
+ loaded = V2Config.from_payload(payload)
+
+ assert loaded.platform == "slack"
+ assert loaded.platforms.enabled == ["slack"]
+
+
+ ("field", "value"),
+ [
+ ("mode", {}),
+ ("ack_mode", []),
+ ],
+)
+def test_config_reload_recovers_invalid_scalar_enum_only(monkeypatch, tmp_path, field, value):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ payload[field] = value
+ config_path = tmp_path / f"{field}-scalar.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.platform == payload["platform"]
+ assert loaded.load_warnings and field in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_backup_deduplication_repairs_permissions(tmp_path):
+ config_path = tmp_path / "config.json"
+ content = b"sensitive config"
+ config_path.write_bytes(content)
+ backup = config_path.with_name("config.json.bak-test-existing")
+ backup.write_bytes(content)
+ backup.chmod(0o644)
+
+ result = v2_config._backup_config_file(config_path, "test", content=content)
+
+ assert result == backup
+ assert stat.S_IMODE(backup.stat().st_mode) == 0o600
+
+
+def test_config_reload_does_not_replace_file_when_migration_backup_fails(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = _legacy_model_hub_payload(payload["model_hub"])
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+ monkeypatch.setattr(v2_config, "_backup_config_file", lambda *args, **kwargs: None)
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.to_payload() != payload["model_hub"]
+ assert config_path.read_text(encoding="utf-8") == original
+ assert loaded.load_warnings and "could not be backed up" in loaded.load_warnings[0]
+
+
+def test_config_reload_recovery_backs_up_original_snapshot(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = {"sources": "invalid", "agents": {}}
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload).encode("utf-8")
+ config_path.write_bytes(original)
+ original_backup = v2_config._backup_config_file
+
+ def replace_before_backup(path, label, *, content=None):
+ path.write_text(json.dumps(api.config_to_payload(default_config())), encoding="utf-8")
+ return original_backup(path, label, content=content)
+
+ monkeypatch.setattr(v2_config, "_backup_config_file", replace_before_backup)
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.load_warnings
+ backups = list(config_path.parent.glob("config.json.bak-recovery-*"))
+ assert len(backups) == 1
+ assert backups[0].read_bytes() == original
+
+
+def test_config_reload_migrates_legacy_mapping_to_exact_route_hop(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ source["supply_channel"] = "native_cli"
+ source["models"][0]["provenance"] = source["models"][0].pop("origin")
+ model_id = source["models"][0]["id"]
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["claude"]["mode"] = "hub"
+ legacy["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ legacy["agents"]["claude"]["mappings"] = [
+ {
+ "builtin_id": model_id,
+ "target_model_id": model_id,
+ "enabled": True,
+ }
+ ]
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ route = loaded.model_hub.agents["claude"].routes[model_id]
+ assert route.hops[0].source_id == source["id"]
+ assert route.hops[0].model_id == model_id
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.sources[0].models[0].reasoning_efforts == []
+
+
+def test_config_reload_recovers_dangling_legacy_custom_source_order(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["agents"]["claude"]["mode"] = "hub"
+ legacy["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": ["src_missing123"],
+ }
+ current["model_hub"] = legacy
+ config_path = tmp_path / "dangling-source-order.json"
+ original = json.dumps(current)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_config_reload_recovers_backend_ineligible_legacy_custom_source_order(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ for model in source["models"]:
+ model["provenance"] = model.pop("origin")
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["codex"]["mode"] = "hub"
+ legacy["agents"]["codex"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ current["model_hub"] = legacy
+ config_path = tmp_path / "ineligible-source-order.json"
+ original = json.dumps(current)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_config_reload_preserves_enabled_unchecked_legacy_opencode_mapping(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][1])
+ source["models"][0]["provenance"] = source["models"][0].pop("origin")
+ source["models"][0].pop("reasoning_efforts")
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["opencode"]["mode"] = "hub"
+ legacy["agents"]["opencode"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ legacy["agents"]["opencode"]["menu"] = {"view": "featured", "checked": []}
+ legacy["agents"]["opencode"]["mappings"] = [
+ {
+ "builtin_id": "custom/glm-5.2-air",
+ "target_model_id": "glm-5.2-air",
+ "enabled": True,
+ }
+ ]
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ route = loaded.model_hub.agents["opencode"].routes["custom/glm-5.2-air"]
+ assert [(hop.source_id, hop.model_id) for hop in route.hops] == [
+ (source["id"], source["models"][0]["id"]),
+ ]
+ assert loaded.load_warnings == ()
+
+
+def test_config_reload_keeps_legacy_hub_subscription_backend_specific(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ source["supply_channel"] = "hub"
+ source["credential_ref"] = "cred_anthropic_hub"
+ for model in source["models"]:
+ model["provenance"] = model.pop("origin")
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["claude"]["mode"] = "hub"
+ legacy["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ legacy["agents"]["codex"]["mode"] = "hub"
+ legacy["agents"]["codex"]["sources"] = {
+ "policy": "follow",
+ "order": [],
+ }
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.agents["claude"].sources.order == [source["id"]]
+ assert loaded.model_hub.agents["codex"].sources.order == []
+ assert loaded.load_warnings == ()
+
+
[email protected]("supply_channel", ["native_cli", "hub"])
+def test_config_reload_preserves_legacy_claude_alias_resolution(
+ monkeypatch,
+ tmp_path,
+ supply_channel,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ source["supply_channel"] = supply_channel
+ if supply_channel == "hub":
+ source["credential_ref"] = "cred_anthropic_hub"
+ older = source["models"][0]
+ newer = {
+ **older,
+ "id": "claude-opus-5-20260724",
+ "display_name": "Opus 5",
+ }
+ source["models"] = [older, newer]
+ for model in source["models"]:
+ model["provenance"] = model.pop("origin")
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["claude"]["mode"] = "hub"
+ legacy["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ route = loaded.model_hub.agents["claude"].routes["opus"]
+ assert [(hop.source_id, hop.model_id) for hop in route.hops] == [
+ (source["id"], newer["id"]),
+ ]
+ assert loaded.load_warnings == ()
+
+
+def test_config_reload_defaults_omitted_legacy_backend_entries(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["agents"].pop("codex")
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.agents["codex"].mode == "direct"
+ assert loaded.load_warnings == ()
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ assert "codex" in persisted["model_hub"]["agents"]
+
+
+def test_config_reload_uses_first_enabled_duplicate_legacy_mapping(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ first_target = source["models"][0]["id"]
+ later_target = "claude-opus-5-20260724"
+ source["models"].append(
+ {
+ **source["models"][0],
+ "id": later_target,
+ "display_name": "Opus 5",
+ }
+ )
+ for model in source["models"]:
+ model["provenance"] = model.pop("origin")
+ current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(current["model_hub"])
+ legacy["sources"] = [source]
+ legacy["agents"]["claude"]["mode"] = "hub"
+ legacy["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ legacy["agents"]["claude"]["mappings"] = [
+ {"builtin_id": "opus", "target_model_id": later_target, "enabled": False},
+ {"builtin_id": "opus", "target_model_id": first_target, "enabled": True},
+ {"builtin_id": "opus", "target_model_id": later_target, "enabled": True},
+ ]
+ current["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(current), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ route = loaded.model_hub.agents["claude"].routes["opus"]
+ assert [(hop.source_id, hop.model_id) for hop in route.hops] == [
+ (source["id"], first_target),
+ ]
+
+
+ "invalid_invariant",
+ [
+ "healthy-detail",
+ "hub-credential",
+ "manual-discovered-at",
+ "subscription-api-key",
+ "opencode-identity",
+ ],
+)
+def test_config_reload_recovers_inner_model_hub_invariant_only(
+ monkeypatch,
+ tmp_path,
+ invalid_invariant,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ if invalid_invariant == "healthy-detail":
+ source["state"]["detail_key"] = "models.source.invalid"
+ elif invalid_invariant == "hub-credential":
+ source["supply_channel"] = "hub"
+ source["credential_ref"] = None
+ elif invalid_invariant == "manual-discovered-at":
+ source["models"][0]["origin"] = "manual"
+ elif invalid_invariant == "subscription-api-key":
+ source["base_url"] = "https://api.anthropic.com"
+ else:
+ payload["model_hub"]["agents"]["opencode"]["menu"] = {
+ "view": "featured",
+ "checked": ["invalid-opencode-identity"],
+ }
+ if invalid_invariant != "opencode-identity":
+ payload["model_hub"]["sources"] = [source]
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]
+ if invalid_invariant == "opencode-identity":
+ assert persisted["agents"]["opencode"]["menu"]["checked"] == [
+ "invalid-opencode-identity"
+ ]
+ else:
+ assert persisted["sources"] == [source]
+
+
+def test_config_reload_allows_empty_target_on_disabled_legacy_mapping(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(payload["model_hub"])
+ legacy["agents"]["claude"]["mappings"] = [
+ {"builtin_id": "opus", "target_model_id": "", "enabled": False}
+ ]
+ payload["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.agents["claude"].routes["opus"].hops == ()
+
+
+def test_invalid_json_recovery_backs_up_the_original_snapshot(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+ malformed = b'{"mode": '
+ config_path.write_bytes(malformed)
+ original_backup = v2_config._backup_config_file
+
+ def replace_before_backup(path, label, *, content=None):
+ path.write_text(json.dumps(api.config_to_payload(default_config())), encoding="utf-8")
+ return original_backup(path, label, content=content)
+
+ monkeypatch.setattr(v2_config, "_backup_config_file", replace_before_backup)
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.load_warnings and "JSON" in loaded.load_warnings[0]
+ backups = list(config_path.parent.glob("config.json.bak-invalid-json-*"))
+ assert len(backups) == 1
+ assert backups[0].read_bytes() == malformed
+
+
+def test_config_reload_does_not_overwrite_config_changed_during_migration(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = _legacy_model_hub_payload(payload["model_hub"])
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+ concurrent_payload = {**payload, "show_duration": True}
+ original_persist = v2_config._persist_migrated_config_payload
+
+ def persist_after_concurrent_save(path, expected_raw, migrated_payload):
+ path.write_text(json.dumps(concurrent_payload), encoding="utf-8")
+ return original_persist(path, expected_raw, migrated_payload)
+
+ monkeypatch.setattr(
+ v2_config,
+ "_persist_migrated_config_payload",
+ persist_after_concurrent_save,
+ )
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ assert persisted["show_duration"] is True
+ assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert loaded.load_warnings and "changed during load" in loaded.load_warnings[0]
+
+
+def test_config_reload_does_not_overwrite_config_changed_before_replace(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = _legacy_model_hub_payload(payload["model_hub"])
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+ concurrent_payload = {**payload, "show_duration": True}
+ original_write = v2_config._write_config_payload_if_unchanged
+
+ def write_after_concurrent_save(path, migrated_payload, expected_raw):
+ path.write_text(json.dumps(concurrent_payload), encoding="utf-8")
+ return original_write(path, migrated_payload, expected_raw)
+
+ monkeypatch.setattr(
+ v2_config,
+ "_write_config_payload_if_unchanged",
+ write_after_concurrent_save,
+ )
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ assert persisted["show_duration"] is True
+ assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert loaded.load_warnings and "before replacement" in " ".join(loaded.load_warnings)
+ backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))
+ assert backups and any(backup.read_text(encoding="utf-8") == original for backup in backups)
+
+
+def test_config_reload_recovers_invalid_optional_section_without_overwriting_file(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"] = {"sources": "invalid", "agents": {}}
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
+ recovery = api.client_config_payload(loaded)["config_recovery"]
+ assert recovery["required"] is True
+ assert recovery["warnings"]
+ assert recovery["warnings"] != list(loaded.load_warnings)
+ assert json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]["sources"] == "invalid"
+ assert list(config_path.parent.glob("config.json.bak-recovery-*"))
+ V2Config.load(config_path=config_path)
+ assert len(list(config_path.parent.glob("config.json.bak-recovery-*"))) == 1
+
+ monkeypatch.setattr(api, "load_config", lambda: loaded)
+ with pytest.raises(ValueError, match="recovery warnings"):
+ api.save_config({"show_duration": True})
+ with pytest.raises(ValueError, match="recovery warnings"):
+ loaded.save(config_path)
+
+
+ "mutate",
+ [
+ lambda source: source["state"].update({"status": {}}),
+ lambda source: source.update({"kind": []}),
+ lambda source: source.update({"protocol": {}}),
+ ],
+ ids=["state-status", "source-kind", "source-protocol"],
+)
+def test_config_reload_recovers_non_scalar_model_hub_enums(monkeypatch, tmp_path, mutate):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ mutate(source)
+ payload["model_hub"]["sources"] = [source]
+ payload["show_duration"] = True
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
+
+
+def test_client_config_recovery_projection_redacts_validator_details(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["platforms"] = {"enabled": ["sk-leaked-platform-token"], "primary": "avibe"}
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+ raw_warnings = json.dumps(loaded.load_warnings)
+ projected = api.client_config_payload(loaded)
+
+ assert "sk-leaked-platform-token" in raw_warnings
+ assert "sk-leaked-platform-token" not in json.dumps(projected)
+ assert projected["config_recovery"]["warnings"]
+
+
+def test_config_reload_recovers_runtime_with_the_canonical_default(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["runtime"] = {"log_level": "DEBUG"}
+ payload["show_duration"] = True
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.runtime.default_cwd == str(Path.home() / "work")
+ assert loaded.runtime.log_level == "INFO"
+ assert loaded.show_duration is True
+ assert loaded.load_warnings and "runtime" in loaded.load_warnings[0]
+
+
+ "mutate",
+ [
+ lambda hub: hub["agents"]["claude"].update({"sources": "invalid"}),
+ lambda hub: hub["agents"]["claude"].update(
+ {"sources": {"policy": "custom", "order": "invalid"}}
+ ),
+ lambda hub: hub["agents"]["claude"].update(
+ {"sources": {"order": ["src_missing001"]}}
+ ),
+ lambda hub: hub["agents"]["claude"].update(
+ {"sources": {"policy": {}, "order": []}}
+ ),
+ lambda hub: hub.update({"priority_order": {"invalid": True}}),
+ lambda hub: hub.update({"priority_order": ["src_missing001"]}),
+ lambda hub: hub.update({"subscription_hub_experimental": "false"}),
+ lambda hub: hub["sources"].append({"experimental_consent_at": 1}),
+ lambda hub: hub["sources"].append(
+ {
+ "models": [
+ {
+ "id": "legacy-model",
+ "origin": "manual",
+ "provenance": "discovered",
+ "reasoning_efforts": [],
+ }
+ ]
+ }
+ ),
+ lambda hub: hub["agents"]["claude"].update({"mappings": ["invalid"]}),
+ lambda hub: hub["agents"]["claude"].update(
+ {
+ "mappings": [
+ {
+ "builtin_id": "",
+ "target_model_id": "claude-opus-4-5",
+ "enabled": True,
+ }
+ ]
+ }
+ ),
+ lambda hub: hub["agents"]["claude"].update({"mode": "hbu"}),
+ lambda hub: hub["agents"]["claude"].update({"mode": []}),
+ lambda hub: hub["agents"].update({"future-backend": {"mode": "hub"}}),
+ lambda hub: hub["agents"]["claude"].update({"future-field": True}),
+ lambda hub: hub["agents"]["claude"].update({"backend": "codex"}),
+ lambda hub: hub["agents"]["claude"].pop("backend"),
+ lambda hub: hub["agents"]["claude"].update({"menu_kind": "open"}),
+ lambda hub: hub["agents"]["claude"].pop("menu_kind"),
+ lambda hub: hub["agents"]["claude"].update(
+ {
+ "mappings": [
+ {
+ "builtin_id": "opus",
+ "target_model_id": "claude-opus-4-5",
+ "enabled": True,
+ "future_field": True,
+ }
+ ]
+ }
+ ),
+ lambda hub: hub["agents"]["claude"].update({"routes": "invalid"}),
+ lambda hub: hub["agents"]["claude"].update(
+ {"mappings": [{"builtin_id": "opus", "enabled": True}]}
+ ),
+ lambda hub: hub["agents"]["claude"].update(
+ {
+ "mappings": [
+ {
+ "builtin_id": "retired-model",
+ "target_model_id": "claude-opus-4-6",
+ "enabled": True,
+ }
+ ]
+ }
+ ),
+ lambda hub: hub["agents"]["claude"].update(
+ {
+ "mappings": [
+ {
+ "builtin_id": "opus",
+ "target_model_id": "claude-opus-4-5",
+ "enabled": "yes",
+ }
+ ]
+ }
+ ),
+ ],
+ ids=[
+ "sources-not-object",
+ "custom-order-not-array",
+ "order-only-dangling",
+ "policy-not-scalar",
+ "priority-order-not-array",
+ "priority-order-dangling",
+ "subscription-hub-experimental-not-bool",
+ "experimental-consent-not-date-time",
+ "provenance-conflict",
+ "mapping-not-object",
+ "mapping-empty-builtin",
+ "agent-invalid-mode",
+ "agent-non-scalar-mode",
+ "agent-unknown-backend",
+ "agent-unknown-field",
+ "agent-backend-mismatch",
+ "agent-backend-missing",
+ "agent-menu-kind-mismatch",
+ "agent-menu-kind-missing",
+ "mapping-unknown-field",
+ "routes-not-object",
+ "mapping-missing-target",
+ "mapping-retired-menu",
+ "mapping-enabled-not-boolean",
+ ],
+)
+def test_config_reload_does_not_infer_malformed_legacy_source_order(
+ monkeypatch,
+ tmp_path,
+ mutate,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ legacy = _legacy_model_hub_payload(payload["model_hub"])
+ mutate(legacy)
+ payload["model_hub"] = legacy
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
+ assert config_path.read_text(encoding="utf-8") == original
+ assert list(config_path.parent.glob("config.json.bak-recovery-*"))
+
+
+def test_config_reload_recovers_invalid_codex_agent_with_disabled_default(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ payload["agents"]["codex"] = "invalid"
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.agents.codex.enabled is False
+ assert loaded.agents.claude.enabled is True
+ assert loaded.load_warnings and "agents.codex" in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_config_reload_recovers_invalid_agents_with_canonical_defaults(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["show_duration"] = True
+ payload["agents"] = "invalid"
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.agents.opencode.enabled is True
+ assert loaded.agents.claude.enabled is True
+ assert loaded.agents.codex.enabled is False
+ assert loaded.agents.avault.cli_path == "avault"
+ assert loaded.load_warnings and "agents" in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == original
+
+
+def test_config_reload_recovers_invalid_json_with_backup(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+ config_path.write_text('{"mode": ', encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.mode == "self_host"
+ assert loaded.platform == "avibe"
+ assert loaded.load_warnings and "JSON" in loaded.load_warnings[0]
+ assert config_path.read_text(encoding="utf-8") == '{"mode": '
+ assert list(config_path.parent.glob("config.json.bak-invalid-json-*"))
+
+
+def test_config_reload_recovers_invalid_encoding_with_backup(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config.json"
+ config_path.write_bytes(b"\xff\xfe")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.mode == "self_host"
+ assert loaded.load_warnings and "UTF-8" in loaded.load_warnings[0]
+ assert config_path.read_bytes() == b"\xff\xfe"
+ assert list(config_path.parent.glob("config.json.bak-invalid-encoding-*"))
+
+
def test_legacy_and_fresh_configs_both_default_direct():
payload = api.config_to_payload(default_config(), include_secrets=True)
payload.pop("model_hub")
@@ -1301,6 +2238,22 @@ def test_final_config_rejects_retired_consent_metadata():
ModelHubConfig.from_payload(payload)
+def test_config_reload_drops_valid_retired_consent_metadata(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][1])
+ source["experimental_consent_at"] = "2026-07-23T03:00:00Z"
+ payload["model_hub"]["sources"] = [source]
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.load_warnings == ()
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ assert "experimental_consent_at" not in persisted["model_hub"]["sources"][0]
+
+
def test_final_config_rejects_retired_global_priority_key():
payload = ModelHubConfig().to_payload()
payload["priority_order"] = {"legacy": "shape-does-not-matter"}
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index dd0c1204b..7fa843025 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -50,11 +50,16 @@ class MemoryStore:
def __init__(self, config: ModelHubConfig):
self.config = config
self.requested_models = {"claude": "claude-opus-4-6"}
+ self.recovery = False
def load(self) -> ModelHubConfig:
return self.config
def save(self, config: ModelHubConfig) -> None:
+ if self.recovery:
+ raise ValueError(
+ "Config was loaded with recovery warnings; repair the backed-up config before saving changes"
+ )
self.config = config
def requested_model(self, backend: str) -> str:
@@ -497,6 +502,57 @@ def test_runtime_skips_later_hops_after_a_source_global_failure(tmp_path):
assert resolved.model_id == "upstream-third"
+def test_runtime_fallback_continues_when_recovery_blocks_runtime_state_save(tmp_path):
+ first = _source("src_recovery001", ("upstream-first",))
+ second = _source("src_recovery002", ("upstream-second",))
+ config = _config([first, second])
+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(
+ hops=(
+ ModelHubRouteHopConfig(first.id, "upstream-first"),
+ ModelHubRouteHopConfig(second.id, "upstream-second"),
+ )
+ )
+ adapter = FakeAdapter()
+ adapter.outcomes.extend(
+ (
+ RawCallOutcome(
+ kind=RawOutcomeKind.HTTP_ERROR,
+ http_status=429,
+ error_code="rate_limit_error",
+ redacted_message=None,
+ stream_started=False,
+ model_id="upstream-first",
+ source_id=first.id,
+ ),
+ RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS,
+ http_status=200,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ model_id="upstream-second",
+ source_id=second.id,
+ ),
+ )
+ )
+ service, store, _ = _service(tmp_path, config, adapter)
+ store.recovery = True
+
+ resolved = asyncio.run(
+ service.resolve(
+ backend="claude",
+ model_id="claude-opus-4-6",
+ request={},
+ )
+ )
+
+ assert adapter.invocations == [
+ (first.id, "upstream-first"),
+ (second.id, "upstream-second"),
+ ]
+ assert resolved.source_id == second.id
+
+
def test_static_api_key_401_falls_through_without_retry(tmp_path):
first = _source(
"src_static401a",
diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.py
index 9f9873dd8..95dc676b7 100644
--- a/tests/test_save_opencode_provider_auth.py
+++ b/tests/test_save_opencode_provider_auth.py
@@ -403,6 +403,47 @@ def test_delete_provider_auth_removes_opencode_json_options_key(fake_save_env) -
assert read_opencode_provider_base_url("poe", home=home) == "https://poe-relay.example/v1"
+def test_delete_provider_auth_blocks_recovery_before_external_mutation(fake_save_env, monkeypatch) -> None:
+ server, _home = fake_save_env
+ monkeypatch.setattr(
+ api,
+ "load_config",
+ lambda: type("Config", (), {"load_warnings": ("recovery required",)})(),
+ )
+
+ result = asyncio.run(api.delete_opencode_provider_auth_async("poe"))
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert server.remove_calls == []
+
+
+def test_delete_custom_provider_blocks_recovery_before_external_mutation(fake_save_env, monkeypatch) -> None:
+ from vibe.opencode_config import read_opencode_custom_providers
+
+ server, home = fake_save_env
+ assert _save_custom(
+ {
+ "provider_id": "my-relay",
+ "name": "My Relay",
+ "adapter": "openai-compatible",
+ "base_url": "https://relay.example/v1",
+ }
+ )["ok"] is True
+ monkeypatch.setattr(
+ api,
+ "load_config",
+ lambda: type("Config", (), {"load_warnings": ("recovery required",)})(),
+ )
+
+ result = _delete_custom("my-relay")
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "my-relay" in read_opencode_custom_providers(home=home)
+ assert server.remove_calls == []
+
+
def test_delete_provider_auth_clears_options_cache(fake_save_env) -> None:
from vibe.opencode_config import upsert_opencode_provider_api_key
@@ -547,6 +588,32 @@ def test_save_custom_provider_persists_config_and_key(fake_save_env) -> None:
assert config["provider"]["my-relay"]["options"]["apiKey"] == "sk-relay"
+def test_save_custom_provider_blocks_recovery_before_external_mutation(fake_save_env, monkeypatch) -> None:
+ from vibe.opencode_config import read_opencode_custom_providers
+
+ server, home = fake_save_env
+ monkeypatch.setattr(
+ api,
+ "load_config",
+ lambda: type("Config", (), {"load_warnings": ("recovery required",)})(),
+ )
+
+ result = _save_custom(
+ {
+ "provider_id": "my-relay",
+ "name": "My Relay",
+ "adapter": "openai-compatible",
+ "base_url": "https://relay.example/v1",
+ "api_key": "sk-relay",
+ }
+ )
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert read_opencode_custom_providers(home=home) == {}
+ assert server.set_calls == []
+
+
def test_save_custom_provider_rejects_clearing_base_url(fake_save_env) -> None:
from vibe.opencode_config import (
read_opencode_provider_base_url,
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index 7432bcb24..d3446a996 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -511,6 +511,57 @@ def test_claude_settings_json_takes_precedence_over_legacy_v2config(
assert state["settings_conflict"] is False
+def test_save_claude_auth_blocks_recovery_before_external_mutation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe import api
+
+ fake_config = type("Config", (), {"load_warnings": ("recovery required",), "language": "zh"})()
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ applied: list[dict] = []
+ monkeypatch.setattr(
+ "vibe.claude_config.apply_claude_auth",
+ lambda **kwargs: applied.append(kwargs),
+ )
+
+ result = api.save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "api_key": "sk-new",
+ "credential_type": "api_key",
+ "base_url": "https://example.invalid",
+ }
+ )
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert applied == []
+
+
+def test_remove_claude_api_key_blocks_recovery_before_external_mutation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from vibe import api
+
+ fake_config = type("Config", (), {"load_warnings": ("recovery required",)})()
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ applied: list[dict] = []
+ monkeypatch.setattr(
+ "vibe.claude_config.apply_claude_auth",
+ lambda **kwargs: applied.append(kwargs),
+ )
+
+ result = api.remove_backend_api_key("claude")
+
+ assert result == {
+ "ok": False,
+ "error": "config_recovery",
+ "message": "Config was loaded with recovery warnings; repair the backed-up config before changing backend credentials",
+ }
+ assert applied == []
+
+
def test_save_claude_explicit_auth_token_clears_v2_secret(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index bd2dce624..eabfa0858 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1306,6 +1306,62 @@ def test_sync_start_oauth_web_keeps_background_tasks_on_persistent_loop(monkeypa
assert flow.waiter_task.done()
+def test_start_oauth_web_blocks_recovery_before_service_mutation(monkeypatch):
+ fake_config = SimpleNamespace(load_warnings=("recovery required",), language="zh")
+ service_calls = []
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service_calls.append(True))
+
+ result = asyncio.run(api.start_oauth_web_async("codex"))
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert service_calls == []
+
+
+def test_submit_oauth_web_code_rechecks_recovery_before_service_mutation(monkeypatch):
+ fake_config = SimpleNamespace(load_warnings=("recovery required",), language="zh")
+ service_calls = []
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service_calls.append(True))
+
+ result = asyncio.run(api.submit_oauth_web_code_async("flow-1", "code-1"))
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert service_calls == []
+
+
+def test_remove_backend_auth_blocks_recovery_before_service_mutation(monkeypatch):
+ fake_config = SimpleNamespace(load_warnings=("recovery required",), language="zh")
+ service_calls = []
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service_calls.append(True))
+
+ result = asyncio.run(api.remove_backend_auth_async("codex"))
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert service_calls == []
+
+
+def test_remove_claude_oauth_credentials_blocks_recovery_before_service_mutation(monkeypatch):
+ fake_config = SimpleNamespace(load_warnings=("recovery required",), language="zh")
+ service_calls = []
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service_calls.append(True))
+
+ result = asyncio.run(api.remove_claude_oauth_credentials_async())
+
+ assert result["ok"] is False
+ assert result["error"] == "config_recovery"
+ assert "配置加载时发生了恢复" in result["message"]
+ assert service_calls == []
+
+
def test_detect_cli_prefers_claude_local(monkeypatch, tmp_path):
claude_path = tmp_path / ".claude" / "local" / "claude"
claude_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index e8eb12c87..769e6ed07 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -284,6 +284,41 @@ def test_doctor_reports_degraded_show_checkpoints_without_git(monkeypatch):
]
+def test_doctor_surfaces_configuration_recovery_warnings(monkeypatch, tmp_path):
+ config_path = tmp_path / "config.json"
+ config_path.write_text("{}", encoding="utf-8")
+ doctor_path = tmp_path / "doctor.json"
+ warning = "Recovered invalid config section 'platforms': sk-leaked-platform-token"
+ config = cli.V2Config.default()
+ config.language = "zh"
+ config.load_warnings = (warning,)
+
+ monkeypatch.setattr(paths, "get_config_path", lambda: config_path)
+ monkeypatch.setattr(paths, "get_runtime_doctor_path", lambda: doctor_path)
+ monkeypatch.setattr(cli.V2Config, "load", lambda _path: config)
+ monkeypatch.setattr(cli, "_home_migration_items", lambda: [])
+ monkeypatch.setattr(cli, "_service_lifecycle_items", lambda **_kwargs: [])
+ monkeypatch.setattr(cli, "_service_install_family_items", lambda **_kwargs: [])
+ monkeypatch.setattr(cli, "_restart_state_items", lambda: [])
+ monkeypatch.setattr(cli, "_runtime_architecture_items", lambda: [])
+ monkeypatch.setattr(cli, "_show_git_checkpoint_items", lambda: [])
+ monkeypatch.setattr(cli, "_managed_dependencies_doctor_items", lambda **_kwargs: [])
+ monkeypatch.setattr(cli, "_show_runtime_doctor_items", lambda **_kwargs: [])
+ monkeypatch.setattr(cli, "_local_cli_installation_items", lambda: [])
+ monkeypatch.setattr(cli.api, "detect_cli", lambda _path: {})
+
+ result = cli._doctor()
+
+ config_group = next(group for group in result["groups"] if group["name"] == "Configuration")
+ recovery_item = next(item for item in config_group["items"] if item.get("code") == "config.recovery")
+ assert recovery_item["status"] == "warn"
+ assert recovery_item["code"] == "config.recovery"
+ assert recovery_item["message"] != warning
+ assert recovery_item["action"] == cli.i18n_t("error.configRecovery.action", "zh")
+ assert "sk-leaked-platform-token" not in json.dumps(result)
+ assert result["summary"]["warn"] >= 1
+
+
def test_status_and_doctor_use_running_checkpoint_service_state(monkeypatch):
monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)
monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: False)
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index a319709c9..4a8bbae8b 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';
-import { ArrowLeft, Bot, Brain, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';
+import { AlertTriangle, ArrowLeft, Bot, Brain, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -216,6 +216,36 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
);
};
+type ConfigRecoveryProjection = {
+ config_recovery?: {
+ required?: boolean;
+ warnings?: unknown[];
+ };
+};
+
+const ConfigRecoveryNotice: React.FC<{ config: ConfigRecoveryProjection | null }> = ({ config }) => {
+ const { t } = useTranslation();
+ if (!config?.config_recovery?.required) return null;
+
+ return (
+ <div className="fixed inset-x-2 top-2 z-[70] mx-auto flex max-w-3xl items-start gap-3 rounded-lg border border-gold/45 bg-surface px-3 py-2.5 shadow-xl" role="alert">
+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-gold" />
+ <div className="min-w-0 flex-1">
+ <p className="text-[13px] font-semibold text-foreground">{t('configRecovery.title')}</p>
+ <p className="mt-0.5 break-words text-[12px] text-muted">
+ {t('configRecovery.body')}
+ </p>
+ </div>
+ <Link
+ to="/admin/settings/diagnostics"
+ className="shrink-0 text-[12px] font-semibold text-gold hover:underline"
+ >
+ {t('configRecovery.action')}
+ </Link>
+ </div>
+ );
+};
+
export const AppShell: React.FC = () => {
const { t } = useTranslation();
const { status } = useStatus();
@@ -323,7 +353,7 @@ export const AppShell: React.FC = () => {
const isRunning = status.state === 'running';
if (location.pathname === '/setup') {
- return <Outlet />;
+ return <><ConfigRecoveryNotice config={config} /><Outlet /></>;
}
// Two shell modes share the same chrome (brand + bottom status):
@@ -464,6 +494,7 @@ export const AppShell: React.FC = () => {
!chromeless && 'md:block md:h-auto md:min-h-screen md:overflow-visible'
)}
>
+ <ConfigRecoveryNotice config={config} />
{/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < window
layer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.
The Apps button no longer floats on top in full-screen (a Dock redesign comes later);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d025645da..a3444f8b8 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1812,6 +1812,11 @@
"newFolderName": "Folder name"
}
},
+ "configRecovery": {
+ "title": "Configuration repair required",
+ "body": "Avibe recovered part of the configuration and preserved the original file. Repair it before changing settings.",
+ "action": "Diagnostics"
+ },
"appShell": {
"title": "Avibe",
"subtitle": "Agent OS · Workbench",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4c1579253..998d1161f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1812,6 +1812,11 @@
"newFolderName": "文件夹名称"
}
},
+ "configRecovery": {
+ "title": "配置需要修复",
+ "body": "Avibe 已恢复部分配置并保留原文件。请先修复,再修改设置。",
+ "action": "诊断"
+ },
"appShell": {
"title": "Avibe",
"subtitle": "Agent OS · 工作台",
diff --git a/vibe/api.py b/vibe/api.py
index fdc87dc7f..8dea99872 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -671,6 +671,28 @@ def load_config() -> V2Config:
return V2Config.load()
+def config_recovery_notice(config: V2Config) -> Optional[str]:
+ """Return the localized, non-diagnostic message for a recovered config."""
+
+ if not getattr(config, "load_warnings", ()):
+ return None
+ return backend_t(
+ "error.configRecovery.beforeAuth",
+ getattr(config, "language", "en") or "en",
+ )
+
+
+def _config_recovery_message() -> Optional[str]:
+ """Return a localized guard message before mutating backend-owned auth files."""
+
+ with CONFIG_LOCK:
+ try:
+ config = load_config()
+ except FileNotFoundError:
+ return None
+ return config_recovery_notice(config)
+
+
def _deep_merge_dicts(base: dict, patch: dict) -> dict:
merged = dict(base)
for key, value in patch.items():
@@ -917,6 +939,9 @@ def save_config(
if not isinstance(payload, dict):
raise ValueError("Config payload must be an object")
+ # This read-only projection is returned by GET /api/config so the browser
+ # can explain a recovered load; it must never become persisted config data.
+ payload = {key: value for key, value in payload.items() if key != "config_recovery"}
if not allow_memory:
payload = {key: value for key, value in payload.items() if key != "memory"}
# Model Hub mutations must pass through ModelHubService so runtime source
@@ -934,6 +959,11 @@ def save_config(
base_config: Optional[V2Config] = None
try:
base_config = load_config()
+ if base_config.load_warnings:
+ raise ValueError(
+ "Config was loaded with recovery warnings; repair the backed-up "
+ "config before saving changes"
+ )
base_payload = config_to_payload(base_config, include_secrets=True, include_internal=True)
except FileNotFoundError:
# Fresh install: no config file yet. Seed the same workbench-only
@@ -1227,6 +1257,12 @@ def client_config_payload(config: V2Config) -> dict:
payload = config_to_payload(config)
payload.pop("memory", None)
+ recovery_notice = config_recovery_notice(config)
+ recovery_warnings = [recovery_notice] if recovery_notice else []
+ payload["config_recovery"] = {
+ "required": bool(config.load_warnings),
+ "warnings": recovery_warnings,
+ }
return payload
@@ -8857,6 +8893,9 @@ async def start_oauth_web_async(
return {"ok": False, "error": "unsupported_backend"}
if backend == "opencode" and not (isinstance(provider_id, str) and provider_id.strip()):
return {"ok": False, "error": "opencode_provider_id_required"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
service = _get_oauth_service()
try:
flow = await service.start_web_setup(
@@ -8902,6 +8941,9 @@ async def submit_oauth_web_code_async(flow_id: str, code: str) -> dict:
flow_id = (flow_id or "").strip()
if not flow_id:
return {"ok": False, "error": "missing_flow_id"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
service = _get_oauth_service()
try:
return await service.submit_web_code(flow_id, code or "")
@@ -8919,6 +8961,9 @@ async def remove_backend_auth_async(backend: str) -> dict:
backend = (backend or "").strip().lower()
if not supports_web_oauth(backend):
return {"ok": False, "error": "unsupported_backend"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
service = _get_oauth_service()
try:
return await service.remove_web_auth(backend)
@@ -8929,6 +8974,9 @@ async def remove_backend_auth_async(backend: str) -> dict:
async def remove_claude_oauth_credentials_async() -> dict:
"""Clear only Claude Code OAuth credentials, preserving API-key auth."""
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
service = _get_oauth_service()
try:
return await service.clear_claude_oauth_credentials_only()
@@ -8972,6 +9020,9 @@ def remove_backend_api_key(backend: str) -> dict:
backend = (backend or "").strip().lower()
if backend not in {"claude", "codex"}:
return {"ok": False, "error": "unsupported_backend"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
notices: list = []
if backend == "codex":
@@ -9230,6 +9281,10 @@ def save_codex_auth(payload: dict) -> dict:
if base_url_change == "":
base_url_change = None
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
+
if auth_mode == "api_key" and not api_key:
# Allow callers to PATCH base_url alone by reusing the stored key.
# ``auth.json`` is the live source Codex reads at launch, and it
@@ -9499,6 +9554,10 @@ def save_claude_auth(payload: dict) -> dict:
if base_url_change == "":
base_url_change = None
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
+
settings_env: dict[str, str] = {}
existing_credential_type: str | None = None
existing_credential: str | None = None
@@ -10418,6 +10477,9 @@ async def save_opencode_custom_provider_async(payload: dict) -> dict:
provider_id, name, adapter, base_url, api_key = _normalize_custom_provider_payload(payload)
except ValueError as exc:
return {"ok": False, "message": str(exc)}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
try:
from vibe.opencode_config import is_reserved_opencode_provider_id
@@ -10517,6 +10579,14 @@ async def delete_opencode_custom_provider_async(provider_id: str) -> dict:
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
pid = provider_id.strip().lower()
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {
+ "ok": False,
+ "error": "config_recovery",
+ "provider_id": pid,
+ "message": recovery_message,
+ }
try:
from vibe.opencode_config import (
is_opencode_custom_provider,
@@ -10847,6 +10917,9 @@ async def save_opencode_provider_auth_async(provider_id: str, payload: dict) ->
return {"ok": False, "message": "provider_id is required"}
if not isinstance(payload, dict):
return {"ok": False, "message": "Payload must be an object"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
raw_key = payload.get("api_key")
# ``api_key`` is optional when the provider is already configured: the
# UI's "Replace" flow hides the plaintext and only sends ``base_url``
@@ -10998,6 +11071,9 @@ async def delete_opencode_provider_auth_async(provider_id: str) -> dict:
"""
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
+ recovery_message = _config_recovery_message()
+ if recovery_message:
+ return {"ok": False, "error": "config_recovery", "message": recovery_message}
pid = provider_id.strip()
try:
from vibe.opencode_config import (
diff --git a/vibe/cli.py b/vibe/cli.py
index 9549d9c62..2df5c42f9 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -10712,13 +10712,26 @@ def _doctor(*, deep: bool = False):
config = None
try:
config = V2Config.load(config_path)
- config_items.append(
- {
- "status": "pass",
- "message": "Configuration loaded successfully",
- }
- )
- summary["pass"] += 1
+ if config.load_warnings:
+ recovery_notice = api.config_recovery_notice(config)
+ if recovery_notice:
+ recovery_language = getattr(config, "language", "en") or "en"
+ _add_doctor_item(
+ config_items,
+ "warn",
+ recovery_notice,
+ i18n_t("error.configRecovery.action", recovery_language),
+ code="config.recovery",
+ )
+ summary["warn"] += 1
+ else:
+ config_items.append(
+ {
+ "status": "pass",
+ "message": "Configuration loaded successfully",
+ }
+ )
+ summary["pass"] += 1
except Exception as exc:
config_items.append(
{
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 23369aacd..b62c07abf 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -214,6 +214,10 @@
"message": "Agent routing changed while these settings were open.",
"hint": "Reload the settings and apply your change again."
},
+ "configRecovery": {
+ "beforeAuth": "Config was loaded with recovery warnings; repair the backed-up config before changing backend credentials",
+ "action": "Review the preserved config backup and repair it before changing settings."
+ },
"scopeAgentUnavailable": {
"message": "Agent `{agent}` is unavailable for this route.",
"hint": "Choose an enabled Agent and apply the setting again."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index eb9ef5b6c..a06f881f6 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -214,6 +214,10 @@
"message": "这些设置打开后,Agent 路由已发生变化。",
"hint": "请重新加载设置后再次修改。"
},
+ "configRecovery": {
+ "beforeAuth": "配置加载时发生了恢复;请先修复备份的配置,再修改 backend 凭据。",
+ "action": "请检查保留的配置备份并修复后,再修改设置。"
+ },
"scopeAgentUnavailable": {
"message": "Agent `{agent}` 无法用于此路由。",
"hint": "请选择一个已启用的 Agent 后重新保存。"